/* dialog.js */ 
﻿/*
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
*/

var dlg_parent;
var dialogh_ref;
var device_dpi;
var dialog2_html;
var modal_dialog;
var dlg_width;
var dlg_height;
var dlg_autosizeheight = false;
var callback_end = "";
var isopened = false;

function setParent(parentDialog) {
    dlg_parent = parentDialog;
}

function Click1() {
    closeDialog();
    $("#graydiv").remove();
}

function getDPI() {
    return device_dpi;
}

function setWidth(dlg, width) {
    $(dlg).css("width", width);
}

function setHeight(dlg, height) {
    $(dlg).css("height", height);
}

function getFullWidth() {
    return IsIE7() ? $(window).width() : document.body.scrollWidth;
}

function getFullHeight() {
    return IsIE7() ? $(window).height() : document.body.scrollHeight;
}

function setPadding(content, padding, classvalue) {
    s = "<div style='padding:" + padding + "px'";
    if (classvalue && classvalue != "")
        s += " class='" + classvalue + "'";
    s += ">" + content + "</div>";
    return s;
}

function getContentSize(html) {
    var size = { width: 0, height: 0 };
    o = $("<div style='display:visible;position:absolute;top:0px;left:0px;' id='04A98DB973UPK'>" + html + "</div>");
    $('body').append(o);
    size.width = $("#04A98DB973UPK").outerWidth(true);
    size.height = $("#04A98DB973UPK").outerHeight(true);
    $("#04A98DB973UPK").remove();
    return size;
}

function showDialog3(html, xpos, ypos, width, height, modal, dpi, noborder, outcontent) {

    showDialog2(html, xpos, ypos, width, height, modal, dpi, noborder);
    outcontent = "<div id='04A98DB974UPK'>" + outcontent + "</div>";
    $('body').append(outcontent);
}

function showDialog2(html, xpos, ypos, width, height, modal, dpi, noborder) {
    if (height == -1) {
        dlg_autosizeheight = true;
    }
    else dlg_autosizeheight = false;
    dialog2_html = html;
    showDialog("", xpos, ypos, width, height, modal, dpi, "", noborder);
}

function showDialog(href, xpos, ypos, width, height, modal, dpi, dialog1_path, noborder) {
    isopened = true;
    if (dpi == 0) dpi = 96;

    if (xpos != -1) xpos = PtToPx(xpos, dpi);
    if (ypos != -1) ypos = PtToPx(ypos, dpi);
    width = PtToPx(width, dpi);
    height = PtToPx(height, dpi);

    dlg_width = width;
    dlg_height = height;
    device_dpi = dpi;
    dialogh_ref = href;
    modal_dialog = modal;

    var wpx, hpx;
    wpx = width;
    hpx = height;

    if (xpos == -1 || ypos == -1) {
        // if the browser is IE then we can use pixel positioning
        centerx = $(window).width() / 2 - (wpx / 2) + $(document).scrollLeft();
        centery = $(window).height() / 2 - (hpx / 2) + $(document).scrollTop();
    }
    else {
        //do we need scroll adjustment here too???
        centerx = xpos;
        centery = ypos;
    }
    if (noborder)
        mainref = dialogh_ref;
    else
        if (dialog1_path && dialog1_path != "")
            mainref = dialog1_path + "dialog1.html";
        else
            mainref = "../dialog1.html"

        if (href == "") mainref = "../dialog2.html";

        var bodyWidth = getFullWidth();
        var bodyHeight = getFullHeight();

        // scrollarea ////////////////////////////////////////////////
        if (modal) $(document.body).append('<div id="scrollarea" scrolling="no" style="display:visible;position:absolute; top:0px; left: 0px; overflow:auto; z-index: 100;width:' + bodyWidth + 'px;height:' + bodyHeight + 'px;"></div>');
        else $(document.body).append('<div id="scrollarea" scrolling="yes"  style="overflow:auto; z-index: 99;" onclick="Click1();"></div>');
        //////////////////////////////////////////////////////////////

        if (bodyHeight < hpx) centery = 0;

        $(document.body).append('<div id="ehandlerdiv" style="display:none;position:absolute; top:0px; left: 0px; width:100%; height:100%; display:none; z-index: 999;"></div>');

        if (modal) $(document.body).append('<div id="graydiv" scrolling="yes" class="pointerdiv" style="display:none;z-index: 99;width:' + bodyWidth + 'px;height:' + bodyHeight + 'px;"></div>');
        else $(document.body).append('<div id="graydiv" scrolling="yes" class="pointerdiv2" style="display:none;z-index: 99;" onclick="Click1();"></div>');
        $("#graydiv").show();

        if (noborder) $("#scrollarea").append('<div id="draggable" style="visibility:hidden;position:absolute; left:' + centerx + 'px; top:' + centery + 'px; width: ' + wpx + 'px; height: ' + hpx + 'px;z-index: 998; overflow:hidden;">');
        else $("#scrollarea").append('<div id="draggable" style="visibility:hidden;position:absolute; left:' + centerx + 'px; top:' + centery + 'px; width: ' + wpx + 'px; height: ' + hpx + 'px;z-index: 998; overflow:hidden;">');

        $('#draggable').append('<iframe id="if1" scrolling="no" src="' + mainref + '" frameborder="0" style="width: 100%; height: 100%; margin:0px; padding:0px; position: absolute;top: 0px; left: 0px; background-color: white;"></iframe>');
    }

    function isOpenDialog() {
        return isopened;
    }

    function removeDiv(dlgName) {
        $(dlgName).remove();
    }

    function appendDiv(div) {
        $(document.body).append(div);
    }

    function resizeDialog() {
        var bodyWidth = getFullWidth();
        var bodyHeight = getFullHeight();
        $("#graydiv").css("width", bodyWidth + "px");
        $("#graydiv").css("height", bodyHeight + "px");

        $("#scrollarea").css("width", bodyWidth + "px");
        $("#scrollarea").css("height", bodyHeight + "px");
    }

    function closeDialog() {
        $("#ehandlerdiv").remove();
        $("#draggable").remove();
        $("#04A98DB974UPK").remove();
        $("#graydiv").remove();
        $("#scrollarea").remove();
        isopened = false;
        if (dlg_parent) {
            if (callback_end) dlg_parent.eval(callback_end);
        }
        else
            if (callback_end) eval(callback_end);
    }

    function setOnCloseEvent(functionname) {
        callback_end = functionname;
    }

    function getOnCloseEvent() {
        return callback_end;
    }

    function getDialog2Content() {
        return dialog2_html;
    }/* common.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

// Common functions between toc and lms

function filterHTML(s) {
    s = replaceString("&", "&amp;", s);
    s = replaceString("<", "&lt;", s);
    s = replaceString(">", "&gt;", s);
    return s;
}

function replaceString(oldString, newString, fullS) {
    if (fullS == null) return;
    var cReg = new RegExp(oldString, "g");
    var nString = fullS.replace(cReg, newString);
    return nString;
}

function PtToPx(pt, dpi) {
    return (pt * dpi) / 72;
}

function PxToPt(px, dpi) {
    return (px / dpi) * 72;
}

/*****************************************************************************/

function getDPICookie() {
    var cookie = new Cookie(document, "UPKDpiDailyWarning", "today", "/");
    cookie.Load();
    if (cookie.DPIdailyWarning == 1) {
        return true;
    }
    cookie.DPIdailyWarning = 1;
    cookie.Store();
    return false;
}
/* browser.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

var _simulate_120_dpi = false;

function IsTouchDevice() {
    return (window.Touch);
}

function IsMacOs() {
    k = (navigator.userAgent.indexOf("Macintosh") >= 0);
    return k;
}

function IsFF3() {
    if (this.navigator) {
        if (this.navigator.userAgent) {
            if (this.navigator.userAgent.indexOf("Firefox/3") > 0) {
                return true;
            }
        }
    }
    return false;
}

function IsFF() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    return (bi.name == "Firefox");
}

function IsFF4() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    if (bi.name != "Firefox")
        return false;
    return (bi.version == 4);
}

function checkFFVersion(i) {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    if (bi.name != "Firefox")
        return false;
    return (bi.version == i);
}

function IsSafari() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    return (bi.name == "Safari" || bi.name == "Chrome");
}

function IsExplorer() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    return (bi.name == "MSIE");
}

function IsIE7() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    if (bi.name != "MSIE")
        return false;
    return (bi.version == 7);
}

function IsIE8() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    if (bi.name != "MSIE")
        return false;
    return (bi.version == 8 || (bi.trident && bi.tridentVersion == 4));
}

function IsIE9() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    if (bi.name != "MSIE")
        return false;
    return (bi.version == 9 || (bi.trident && bi.tridentVersion == 5));
}

function IsIE10() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    if (bi.name != "MSIE")
        return false;
    return (bi.version == 10 || (bi.trident && bi.tridentVersion == 6));
}

function IsActiveXEnabled() {
    var supported = null;
    try {
        supported = !!new ActiveXObject("htmlfile");
    }
    catch (e) {
        supported = false;
    }
    return supported;
}

function IsIE10Modern() {
    if (IsIE10() == false)
        return false;
    return !IsActiveXEnabled();
}

function IsiOS() {
    p = navigator.platform;
    if (p === 'iPad' || p === 'iPad Simulator' || p === 'iPhone' || p === 'iPod')
        return true;
    return false;
}

function IsiOS5() {
    p = navigator.userAgent;
    return (p.indexOf("CPU OS 5_") >= 0);
}

function IsiOS6() {
    p = navigator.userAgent;
    return (p.indexOf("CPU OS 6_") >= 0);
}

function IsSoundSupported() {
    if (IsiOS())
        return false;
    if (swfobject.getFlashPlayerVersion().major > 0)
        return true;
    return true;
}

function BrowserInfo() {
    this.name = "";
    this.version = 0;
    this.subversion = 0;
    this.trident = false;
    this.tridentVersion = 0;
}

function GetBrowserInfo(bi) {
    s = navigator.userAgent;
    k = 0 - 1;
    if (s.indexOf("Chrome") >= 0) {
        bi.name = "Chrome";
        k = s.indexOf("Chrome") + 7;
    }
    else if (s.indexOf("Opera") >= 0) {
        bi.name = "Opera";
        k = s.indexOf("Opera") + 6;
    }
    else if (s.indexOf("Firefox") >= 0) {
        bi.name = "Firefox";
        k = s.indexOf("Firefox") + 8;
    }
    else if (s.indexOf("Safari") >= 0) {
        bi.name = "Safari";
        k = s.indexOf("Version") + 8;
    }
    else if (s.indexOf("MSIE") >= 0) {
        bi.name = "MSIE";
        k = s.indexOf("MSIE") + 5;
        var ti = s.indexOf("Trident/");
        if (ti >= 0) {
            bi.trident = true;
            bi.tridentVersion = parseInt(s.substr(ti + 8));
        }
    }
    else {
        bi.name = "other";
        bi.version = 0;
        return;
    }
    bi.version = parseInt(s.substr(k));
    bi.subversion = parseInt(s.substr(k + 2, 1));
}

function IsSupportedBrowser() {
    var bi = new BrowserInfo();
    GetBrowserInfo(bi);
    k = false;
    if (bi.name == "MSIE" && bi.version >= 7)
        k = true;
    if (bi.name == "Firefox" && ((bi.version >= 3 && bi.subversion >= 5) || bi.version >= 4))
        k = true;
    if (bi.name == "Safari" && bi.version >= 4)
        k = true;
    if (bi.name == "Chrome" && bi.version >= 18)
        k = true;
    return k;
}

//
// Browser-independent object access (NS4, IE5+, Mozilla)
//

function getDIV(id) {
    try {
        if (document.all) {
            return document.all(id);
        }
        else if (document.getElementById) {
            return document.getElementById(id);
        }
        else if (document.layers) {
            var obj = document.layers.screen.document.layers[id];
            if (!obj) {
                obj = document.layers[id];
            }
            return obj;
        }
        return 0;
    }
    catch (error) {
        return (null);
    }
}

function getDIVstyle(id) {
    try {
        if (document.all) {
            return (document.all(id).style);
        }
        else if (document.getElementById) {
            if (document.getElementById(id).style != null) {
                return (document.getElementById(id).style);
            }
        }
        else if (document.layers) {
            var obj = document.layers.screen.document.layers[id];
            if (!obj) {
                obj = document.layers[id];
            }
            return (obj);
        }
        return 0;
    }
    catch (error) {
        //alert ("##### ERROR #####:\n" + error + "\n\n##### CALLER #####" + getDIVstyle.caller);
        return (null);
    }
}

function shiftTo(id, x, y) {
    var obj = getDIVstyle(id);
    if (obj.moveTo) {
        obj.moveTo(x, y);
    }
    else {
        obj.left = x + "px";
        obj.top = y + "px";
    }
}

/**
* #####################
* # START NEW CONTENT #
* #####################
*/

function getUniWidth(id) {
    try {
        var cObj = getDIV(id);
        var w;
        if (id.style.width) {
            w = parseInt(id.style.width);
        }
        else if (id.style.pixelWidth) {
            w = id.style.pixelWidth;
        }
        else if (id.offsetWidth) {
            w = id.offsetWidth;
        }
        else if (document.defaultView && document.defaultView.getComputedStyle) {
            w = document.defaultView.getComputedStyle(cObj, '').getPropertyValue('width');
        }
        if (typeof w == "string") {
            w = parseInt(w);
        }
        return w;
    }
    catch (error) {
        return (null);
    }
}

function getUniHeight(id) {
    try {
        var cObj = getDIV(id);
        var w;
        if (id.style.height) {
            w = parseInt(id.style.height);
        }
        else if (id.style.pixelHeight) {
            w = id.style.pixelHeight;
        }
        else if (id.offsetHeight) {
            w = id.offsetHeight;
        }
        else if (document.defaultView && document.defaultView.getComputedStyle) {
            w = document.defaultView.getComputedStyle(cObj, '').getPropertyValue('height');
        }
        if (typeof w == "string") {
            w = parseInt(w);
        }
        return w;
    }
    catch (error) {
        return (null);
    }
}

function getClientWidth(id) {
    try {
        var cObj = getDIV(id);
        if (cObj.clientWidth) {
            return cObj.clientWidth
        }
        else {
            return parseInt(cObj.width);
        }
    }
    catch (error) {
        return id.offsetWidth;
    }
}

function getClientHeight(id) {
    try {
        var cObj = getDIV(id);
        if (cObj.clientHeight) {
            return cObj.clientHeight
        }
        else {
            return parseInt(cObj.height);
        }
    }
    catch (error) {
        return id.offsetHeight;
    }
}

/**
* ###################
* # END NEW CONTENT #
* ###################
*/

function getObjHeight(id) {
    var obj = getDIV(id);
    if (obj.clip) {
        return obj.clip.height;
    }
    else {
        return obj.offsetHeight;
    }
}

function getObjWidth(id) {
    var obj = getDIV(id);
    if (obj.clip) {
        return obj.clip.width;
    }
    else {
        return obj.offsetWidth;
    }
}

function getObjLeft(id) {
    try {
        var obj = getDIVstyle(id);
        if (obj.pixelLeft) {
            return obj.pixelLeft;
        }
        else {
            return parseInt(obj.left);
        }
    }
    catch (error) {
        return parseInt(id.offsetLeft);
    }
}

function getObjTop(id) {
    try {
        var obj = getDIVstyle(id);
        if (obj.pixelTop) {
            return obj.pixelTop;
        }
        else {
            return parseInt(obj.top);
        }
    }
    catch (error) {
        return parseInt(id.offsetTop);
    }
}


function getInsideWindowWidth() {
    if (window.innerWidth) {
        return window.innerWidth;
    }
    else {
        return document.body.clientWidth;
    }
}

function getInsideWindowHeight() {
    if (window.innerHeight) {
        return window.innerHeight;
    }
    else {
        return document.body.clientHeight;
    }
}

function getScrollLeft() {
    if (window.pageXOffset || window.pageXOffset == 0) {
        return window.pageXOffset;
    }
    else {
        return document.body.scrollLeft;
    }
}

function getScrollTop() {
    if (window.pageYOffset || window.pageYOffset == 0) {
        return window.pageYOffset;
    }
    else {
        return document.body.scrollTop;
    }
}

function show(id, strinput) {
    var obj = getDIVstyle(id);
    obj.visibility = "visible";
    if (strinput && IsiOS()) {
        try {
            if (playMode == "S") {
                if (showActObj.type == "Input") {
                    $("#" + id + " input").attr('readonly', true);
                }
            }
        }
        catch (e) { };
    }
}

function hide(id, strinput) {
    var obj = getDIVstyle(id);
    obj.visibility = "hidden";
}

var __DPIwidth = 0;

function getDpiInfo() {
    var d = document.getElementById("DPIInfoDiv");
    if (d != null) {
        __DPIwidth = d.clientWidth;
        if (__DPIwidth != 0)
            document.getElementsByTagName("body")[0].removeChild(d);
    }
    return _simulate_120_dpi == true ? 120 : __DPIwidth;
}

function initDpiInfo() {
    document.write('<div id="DPIInfoDiv" style="visibility:hidden; width: 72pt; height: 1pt;">DPIINFODIV</div>');
}

function checkIEDPI() {
    return true;
}
/* cookie.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

/** @constructor */
function Cookie(doc, name, exp, path, domain, secure) {
    this.$document = doc;
    this.$name = name;
    if (exp == "today") {
        var d = new Date();
        d.setHours(23);
        d.setMinutes(59);
        d.setSeconds(59);
        this.$exp = d;
    }
    else if (exp)
        this.$exp = new Date((new Date()).getTime() + exp * 3600000 * 24);
    else
        this.$exp = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}

Cookie.prototype.Store = function() {
    if (!PlayerConfig.EnableCookies)
        return;

    var cookieval = "";
    for (var prop in this) {
        if ((prop.charAt(0) == "$") || ((typeof this[prop]) == 'function'))
            continue;
        if (cookieval != "") cookieval += "&";
        cookieval += prop + ":" + escape(this[prop]);
    }

    var cookie = this.$name + "=" + cookieval;
    if (this.$exp)
        cookie += "; expires=" + this.$exp.toGMTString();
    if (this.$path) cookie += "; path=" + this.$path;
    if (this.$domain) cookie += "; domain=" + this.$domain;
    if (this.$secure) cookie += "; secure=";

    this.$document.cookie = cookie;
}

Cookie.prototype.Load = function() {
    if (!PlayerConfig.EnableCookies)
        return false;

    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    var start = allcookies.indexOf(this.$name + "=");
    if (start == -1) return false;
    start += this.$name.length + 1;

    var end = allcookies.indexOf(";", start);
    if (end == -1)
        end = allcookies.length;

    var cookieval = allcookies.substring(start, end);

    var a = cookieval.split("&");
    for (var i = 0; i < a.length; i++) {
        var p = a[i].split(":");
        this[p[0]] = unescape(p[1]);
    }

    return true;
}

Cookie.prototype.Remove = function() {
    if (!PlayerConfig.EnableCookies)
        return;

    var cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}
/* escape.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

var Escape = {};

//*****************************************************************
//Safe Escape/UnEscape support

Escape.SafeUri_EscapeCharacter = '/';

Escape.SafeUri_UnsafeCharacters = ['<', '>', '"', '\'', '%', ';', '(', ')', '&', '+'];

Escape.SafeUriEscape = function(s) {
    return Escape.__Escape(s, 1);
}

Escape.SafeUriUnEscape = function(s) {
    return Escape.__UnEscape(s, 1);
}


//*****************************************************************
// Simple Escape/UnEscape support

Escape.MyEscape = function(s) {
    return Escape.__Escape(s, 0);
}

Escape.MyUnEscape = function(s) {
    return Escape.__UnEscape(s, 0);
}

//*****************************************************************
// private

Escape.__Escape = function(s, safe) {
    var snew = "";
    for (var i = 0; i < s.length; i++) {
        ss = s.substr(i, 1);
        if (safe == 0 ? Escape.__Normal_Contains(ss) : !Escape.__SafeUri_Contains(ss)) {
            snew += ss;
        }
        else {
            ss = s.charCodeAt(i);
            a = "0000" + ss.toString(16).toUpperCase();
            snew += (safe == 0 ? "$" : Escape.SafeUri_EscapeCharacter) + a.substr(a.length - 4);
        }
    }
    return snew;
}

Escape.__UnEscape = function(s, safe) {
    var snew = "";
    var bEscape = false;
    for (var i = 0; i < s.length; i++) {
        if (bEscape) {
            ss = s.substr(i, 4);
            snew += String.fromCharCode(parseInt("0x" + ss));
            i += 3;
            bEscape = false;
        }
        else {
            ss = s.substr(i, 1);
            if (ss == (safe == 0 ? '$' : Escape.SafeUri_EscapeCharacter))
                bEscape = true;
            else
                snew += ss;
        }
    }
    return snew;
}

Escape.__Normal_Contains = function(s) {
    return ((s >= '0' && s <= '9') || (s >= 'a' && s <= 'z') || (s >= 'A' && s <= 'Z'));
}

Escape.__SafeUri_Contains = function(s) {
    var l = Escape.SafeUri_UnsafeCharacters.length;
    for (var i = 0; i < l; i++) {
        if (s == Escape.SafeUri_UnsafeCharacters[i])
            return true;
    }
    if (s == Escape.SafeUri_EscapeCharacter)
        return true;
    return false;
}

////////////////////////////////////////////////////////////////////////////////////////
// UrlParser object

/** @constructor */
function UrlParser() {
    this.params = new Array();
    this.safemode = false;
}

UrlParser.prototype.Clone = function() {
    var url = new UrlParser();
    url.params = new Array();
    url.safemode = this.safemode;
    for (var k in this.params) {
        var v = this.params[k];
        if (v == null)
            continue;
        url.params[k] = this.params[k];
    }
    return url;
}

UrlParser.prototype.Parse = function() {
    var strArgs;
    var strArg;
    var ss = document.location.hash.substring(1);
    strArgs = ss.split("&");
    if (strArgs.length == 0 || strArgs[0] == "") {
        ss = document.location.search.substring(1);
        strArgs = ss.split("&");
    };
    if (strArgs.length > 0) {
        if (strArgs[0].toLowerCase().substr(0, 3) == "su=") {
            this.safemode = true;
            strArgs = strArgs[0].substr(3);
            strArgs = Escape.SafeUriUnEscape(strArgs);
            strArgs = strArgs.split("&");
        }
    }
    for (var i = 0; i < strArgs.length; i++) {
        strArg = (strArgs[i]);
        if (strArg.length == 0)
            continue;
        var param = strArg.split("=");
        if (param.length == 2) {
            this.params[param[0].toLowerCase()] = param[1];
        }
        else if (param.length < 2) {
            this.params[param[0].toLowerCase()] = "";
        }
        else {
            this.params[param[0].toLowerCase()] = strArg.substr(param[0].length + 1);
        }
    }
}

UrlParser.prototype.GetSafeMode = function() {
    return this.safemode;
}

UrlParser.prototype.SetSafeMode = function(k) {
    this.safemode = k;
}

UrlParser.prototype.GetParameter = function(s) {
    return this.params[s.toLowerCase()];
}

UrlParser.prototype.AddParameter = function(s, v) {
    this.params[s.toLowerCase()] = v;
}

UrlParser.prototype.RemoveParameter = function(s) {
    this.params[s.toLowerCase()] = null;
}

UrlParser.prototype.ClearParameterList = function(s) {
    this.params = null;
    this.params = new Array();
}

UrlParser.prototype.BuildParameterList = function(s) {
    var s = "";
    var first = true;
    for (var k in this.params) {
        var v = this.params[k];
        if (v == null) {
            continue;
        }
        if (first == false) {
            s += "&";
        }
        first = false;
        if (v.length == 0) {
            s += k;
        }
        else {
            s += k + "=" + this.params[k];
        }
    }
    if (this.safemode) {
        s = "su=" + Escape.MyEscape(s);
    }
    return s;
}

UrlParser.prototype.GetCorrectUrl = function(url, nosu) {
    if (!this.safemode) { return url; }
    var strArgs;
    var k = url.indexOf("#");
    if (k == -1) { k = url.indexOf("?") }
    if (k >= 0) {
        var paramss = url.substring(k + 1);
        strArgs = paramss.split("&");
        if (strArgs[0].toLowerCase().substr(0, 3) == "su=") {
            return url;
        }
        var ss = url.substring(0, k + 1) + "su=" + Escape.SafeUriEscape(paramss);
        return ss;
    }
    else {
        return url + (nosu ? "" : "?su=");
    }
}

/* xmlloader.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

//////////////////////////////////////////////////////////////////////////////
// Simple function for load XML file by HTTPRequest
// Parameters:
//	url				url of xml file
//	workerFunction	name of callback function will be called with request in the following form:
//					workerFunction(req,extraInfo);
//	extraInfo		extra information for user will be give back with callback function

var _workerFunction = "";
var _errorFunction = "";
var _extraInfo = "";
var _req;
var _url;

function AbsUrl(url) {
    for (var i = 0; i < url.length; i++) {
        c = url.substr(i, 1);
        if (c == ':')
            return url;
    }
    base = window.location.href;

    var k1 = base.indexOf('?');
    var k2 = base.indexOf('#');
    if (k1 >= 0 || k2 >= 0) {
        if (k1 >= 0 && k2 >= 0) {
            base = base.substr(0, (k1 < k2 ? k1 : k2));
        }
        else if (k1 >= 0) {
            base = base.substr(0, k1);
        }
        else {
            base = base.substr(0, k2);
        }
    }

    if (url.substr(0, 3) == "../") {
        var k = base.lastIndexOf('/');
        base = base.substr(0, k);
        while (url.substr(0, 3) == "../") {
            k = base.lastIndexOf('/');
            base = base.substr(0, k);
            url = url.substr(3);
        }
        base = base + "/" + url;
    }
    else {
        if (url.substr(0, 1) == "/")
            url = url.substr(1);
        k = base.lastIndexOf('/');
        base = base.substr(0, k);
        base = base + "/" + url;
    }
    return (base);
}

function LoadXMLDoc(url, workerFunction, errorFunction, extraInfo) {
    _workerFunction = workerFunction;
    _errorFunction = errorFunction;
    _extraInfo = extraInfo;
    _url = AbsUrl(url);

    _req = null;
    try {
        if (window.location.href.substr(0, 7).toLowerCase() == "http://" ||
            window.location.href.substr(0, 8).toLowerCase() == "https://") {
            _req = new XMLHttpRequest();
        }
    }
    catch (e) { }
    finally {
        if (_req == null)
            _req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    _req.onreadystatechange = state_Change;
    _req.open("GET", _url, true);
    _req.send(null);
}

function state_Change() {
    if (_req.readyState == 4) {
        if (_req.status == 200) {
            eval(_workerFunction + "(_req,_extraInfo)");
        }
        else if (_req.status == 0) {
            if (_req.responseXML.documentElement == null) {
                var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(_req.responseText);
                _req = new Object();
                _req.responseXML = xmlDoc;
            }
            eval(_workerFunction + "(_req,_extraInfo)");

        }
        else {
            if (_url.substr(0, 3) == "../") {
                LoadXMLDoc(_url.substr(3), _workerFunction, _errorFunction, _extraInfo);
            }
            else if (_errorFunction.length > 0) {
                alert(_url + " not found. Logged...");
                eval(_errorFunction + "(_extraInfo)");
            }
            else
                alert("Problem retrieving data: " + _req.statusText);
        }
    }
}

//////////////////////////////////////////////////////////////////////////////
// Function to load XML files contain simple arrays
// Parameters:
//	url				url of xml file
//	returnFunction	function will be call back with a simple array loaded from xml file
//	nodeName		name of node for load

var _returnFunction = "";
var _nodes;
var _nodesArray = new Array();

function LoadXMLDocArray(url, returnFunction, errorFunction, nodeName, xmlmode) {
    _returnFunction = returnFunction;
    _nodeName = nodeName;
    if (!xmlmode)
        LoadXMLDoc(url, "XMLDocArrayWorker", errorFunction, nodeName);
    else
        LoadXMLDoc(url, "XMLDocArrayWorker2", errorFunction, nodeName);
}

function XMLDocArrayWorker(req, extraInfo) {
    _nodesArray = new Array();
    _nodes = req.responseXML.getElementsByTagName(extraInfo);
    for (var i = 0; i < _nodes.length; i++) {
        n = _nodes[i];
        s = (n.textContent ? n.textContent : n.text);
        if (!s)
            s = "";
        k = s.length;
        if (k >= 2) {
            if ((s.substr(0, 1) == '\"') && (s.substr(k - 1, 1) == '\"')) {
                ss = s.substr(1, k - 2);
                s = ss;
            }
        }
        _nodesArray[_nodesArray.length] = s;
    }
    sfn = _returnFunction + "(_nodesArray)";
    setTimeout(sfn, 1);
}

function XMLDocArrayWorker2(req, extraInfo) {
    _nodesArray = new Array();
    _nodes = req.responseXML.getElementsByTagName(extraInfo);
    for (var i = 0; i < _nodes.length; i++) {
        n = _nodes[i];
        xmlname = n.attributes[0].nodeValue;
        xmltext = "";
        for (var j = 0; j < n.childNodes.length; j++) {
            if (n.childNodes[j].xml) {
                xmltext += n.childNodes[j].xml;
            } else {
                var oSerializer = new XMLSerializer;
                xmltext += oSerializer.serializeToString(n.childNodes[j]);
            }
        }
        _nodesArray[_nodesArray.length] = xmlname + "=" + xmltext;
    }
    sfn = _returnFunction + "(_nodesArray)";
    setTimeout(sfn, 1);
}

/* lms_toc.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

// include lms_init.js
/*
document.write('<script type="text/javascript" src="./../config.js"></script>');
document.write('<script type="text/javascript" src="./../js/cookie.js"></script>');
document.write('<script type="text/javascript" src="./../js/lms_init.js"></script>');
*/
// callback functions from toc

var lms_TOCState = null;

function lms_LoadAdapterComplete() {
    __Ialert("lms_LoadAdapterComplete() called");

    var lmscom = document.LmsCom;
    lmscom.Begin();
    var parentlmscom = lmscom.ParentLmsCom;
    if (parentlmscom && parentlmscom.bigScoItemCount) {
        lmscom.OpenTOCStatus(parentlmscom.bigScoItemCount, parentlmscom.bigScoHash);
        lms_TOCState = lmscom.status_obj.getTocState();
        lmscom.bigsco = true;   // save/store asset stats differently
    } else
        lmscom.OpenBasicStatus();

    lms_UpdateUI(lmscom.status_obj.getStatus());
    lms_initialized = true;
    setTimeout(lms_store.callbackfunction, 1);
}

function GetChildLmsCom(child_store) {
    __Ialert("lms_GetChildLmsCom() called");
    var lmscom = document.LmsCom;
    var childlmscom = child_store.window.document.LmsCom = (Kpath_launch && child_store.cguid) ? new LmsComKPath() : new LmsComBase(lmscom);
    childlmscom.owner = child_store.window;
    var childindex = parseInt(child_store.childIndex, 10);
    childlmscom.SetOrdinalNumber(childindex);
    childlmscom.lesson_data = lms_TOCState ? (lms_TOCState.GetStatus(childindex) + lms_TOCState.GetChildren(childindex)) : "";
    lmscom.child = childlmscom;
    lmscom.lesson_location = child_store.childIndex;
}

function ListenChildClose() {
    __alert("lms_ListenChildClose() called");

    if (!_sco)
        return;
    var lmscom = document.LmsCom;
    var childlmscom = lmscom.child;
    if (childlmscom.lesson_status === LMS_NOT_ATTEMPTED)
        return;
    var index = childlmscom.GetOrdinalNumber();
    var state = Lms2Stat(childlmscom.lesson_status);
    var score = childlmscom.score;
    var childrenstatus = childlmscom.lesson_data.substring(1);
    lms_TOCState.SetStatus(index, state);
    lms_TOCState.SetScore(index, score);
    lms_TOCState.SetChildren(index, childrenstatus);
    lms_ItemStatus_Changed(index);
}

/////////////////////////////////////////////////////////////////////////////////////////////////
// Status handling in big sco


// get ordinal number of last item in toc visited
function lms_getBookmark() {
    __alert("lms_getBookmark called()");
    var lmscom = document.LmsCom;
    if (lmscom.lesson_location)
        return parseInt(lmscom.lesson_location, 10);
    else
        return lmscom.GetBookmark(this.toc_hash);
}

function lms_GetItemStatus(chindex) {
    return lms_TOCState.GetStatus(chindex);
}

function lms_SetItemStatus(chindex, value) {
    lms_TOCState.SetStatus(chindex, value);
}

function lms_ItemStatus_Changed(index) {
    o = this.frames["mytreeframe"];
    o.UpdateItemStatus(index);
}

//----------------------------------------------------------------------------------------------/

var _lms_module_name = "lms_toc.js";
var _lms_show_alert = false;
var _lms_show_Ialert = false;/* tocfunctions.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

var lastExpressionF = "";
var lastExpressionH = "";
var roleStatusChanged = false;

var viewApplicable = false;
var viewSearch = false;
var selectorMode = "A";
var actuallySelected;
var actuallyChildIndex;

var playerwindow;

// ODS variables
var toc_safeUriMode = false;
var playMode = "P";
var odsTopicID;

var _goToFlatMode = false;
var _lastSearchResultIsEmpty = false;

//SCORM Runtime Communication
/*
var API_1484_11 = null;
var api = null;
var UserID = 1;
*/

function InitRoles(roleexpression) {
    if (roleexpression == "NOROLES") {
        setTimeout("Init1();", 10);
        return;
    }
    QueryParser.Parse("URI", roleexpression);
    if (QueryParser.ev) {
        QueryProcessor.Start(QueryParser.ev, Init0);
    }
}

function SetRoles(roleexpression) {
    SearchProcess_Show(true);

    o = this.frames["mytreeframe"];
    o.modeDescA.treeCreated = false;
    o.modeDescF.treeCreated = false;
    o.modeDescH.treeCreated = false;
    o.modeDescFH.treeCreated = false;

    roleStatusChanged = true;
    if (roleexpression != "NOROLES") {
        QueryParser.Parse("URI", roleexpression);
        if (QueryParser.ev) {
            QueryProcessor.Start(QueryParser.ev, result_Roles_Search);
        }
    }
    else {
        o.SetTopicList("NOROLES", null, "parent.result_Search2");
    }
}

function Trim(s) {
    if (s.length == 0)
        return "";
    while (s.substr(0, 1) == " ") {
        s = s.substr(1);
        if (s.length == 0)
            return "";
    }
    while (s.substr(s.length - 1, 1) == " ") {
        s = s.substr(0, s.length - 1);
    }
    return s;
}

function IsFilteredChar(s) {
    var filters = ".,;:!?(){}[]\\\'";
    for (var i = 0; i < filters.length; i++) {
        if (s == filters.substr(i, 1))
            return " ";
    }
    return s;
}

function SearchStringFilter(s) {
    var sret = "";
    var inQuot = false;
    for (var i = 0; i < s.length; i++) {
        var c = s.substr(i, 1);
        if (c == '\"') {
            inQuot = !inQuot;
            sret += c;
        }
        else {
            sret += (inQuot == true ? c : IsFilteredChar(c));
        }
    }
    return sret;
}

function TrimQuotes(s) {
    if (s.length == 0)
        return s;
    var ss = s;
    if (s.substr(0, 1) == '\"')
        ss = ss.substr(1);
    if (s.substr(s.length - 1, 1) == '\"')
        ss = ss.substr(0, ss.length - 1);
    return ss;
}

function Select(k) {
    SearchProcess_Show(true);
    if (k == 0)		// All view
    {
        if (viewApplicable && viewSearch) {
            selectorMode = "FH";
            setTimeout("ShowFilteredHemi()", 5);
        }
        else if (viewApplicable) {
            selectorMode = "H";
            setTimeout("ShowHemi()", 5);
        }
        else if (viewSearch) {
            selectorMode = "F";
            setTimeout("ShowFiltered()", 5);
        }
        else {
            selectorMode = "A";
            setTimeout("ShowAll()", 5);
        }
    }
    else if (k == 1)	// Filtered view
    {
        o = this.frames["mytreeframe"];
        o._lastChangeIsFilterOnly = false;
        var sb = getObjectById("searchbox");
        var stext = sb.value;
        stext = Trim(SearchStringFilter(stext));
        sb.value = TrimQuotes(stext);
        if (stext.length == 0) {
            SearchProcess_Show(false);
            return;
        }
        ks = stext.indexOf("\'");
        if (ks >= 0) {
            SearchProcess_Show(false);
            return;
        }
        selectorMode = "F";
        if (lastExpressionF != stext) {
            o.modeDescF.treeCreated = false;
            o.modeDescFH.treeCreated = false;
            lastExpressionF = stext;
            datasourceroot = "/querydb/";
            QueryParser.Parse("EXPR", stext);
            if (QueryParser.ev) {
                QueryProcessor.Start(QueryParser.ev, result_Search);
            }
        }
        else {
            if (viewApplicable)
                setTimeout("ShowFilteredHemi()", 5);
            else
                setTimeout("ShowFiltered()", 5);
        }
        return;
    }
    else if (k == 2)	// Hemi view
    {
        o = this.frames["mytreeframe"];
        var stext = hemiParam;
        if (stext.length == 0) {
            SearchProcess_Show(false);
            return;
        }
        selectorMode = "H";
        if (lastExpressionH != stext) {
            o.modeDescH.treeCreated = false;
            o.modeDescFH.treeCreated = false;
            lastExpressionH = stext;
            ss = 'e' + stext;
            datasourceroot = "/querydb/";
            QueryParser.Parse("URI", ss);
            if (QueryParser.ev) {
                QueryProcessor.Start(QueryParser.ev, result_Search);
            }
        }
        else {
            if (viewApplicable)
                setTimeout("ShowFilteredHemi()", 5);
            else
                setTimeout("ShowHemi()", 5);
        }
        return;
    }
    else if (k == 3)	//Filtered Hemi view part 1
    {
        o = this.frames["mytreeframe"];
        var sb = getObjectById("searchbox");
        var stext = Trim(sb.value);
        stext = SearchStringFilter(stext);
        o.modeDescF.treeCreated = false;
        lastExpressionF = stext;
        selectorMode = "FH1";
        datasourceroot = "/querydb/";
        QueryParser.Parse("EXPR", stext);
        if (QueryParser.ev) {
            QueryProcessor.Start(QueryParser.ev, result_Search);
        }
        return;
    }
    else if (k == 4)	// Filtered Hemi view part 2
    {
        o = this.frames["mytreeframe"];
        var stext = hemiParam;
        o.modeDescH.treeCreated = false;
        lastExpressionH = stext;
        ss = 'e' + stext;
        selectorMode = "FH2";
        datasourceroot = "/querydb/";
        QueryParser.Parse("URI", ss);
        if (QueryParser.ev) {
            QueryProcessor.Start(QueryParser.ev, result_Search);
        }
        return;
    }
    else if (k == 5)	// generic mode
    {
        selectorMode = "H";
        onTocLoaded = true;
    }
}

function result_Search2() {
    if (selectorMode == "F") {
        if (viewApplicable)
            setTimeout("ShowFilteredHemi()", 5);
        else
            setTimeout("ShowFiltered()", 5);
    }
    else if (selectorMode == "H") {
        if (viewSearch)
            setTimeout("ShowFilteredHemi()", 5);
        else
            setTimeout("ShowHemi()", 5);
    }
    else if (selectorMode == "FH1") {
        setTimeout("Select(4)", 5);
    }
    else if (selectorMode == "FH2" || selectorMode == "FH") {
        setTimeout("ShowFilteredHemi()", 5);
    }
    else {
        setTimeout("ShowAll()", 5);
    }
}

function result_Roles_Search(topiclist) {
    o = window.frames["mytreeframe"];       /////
    o.SetTopicList("ROLES", topiclist, "parent.result_Search2");
}

function result_Search(topiclist) {
    _lastSearchResultIsEmpty = (topiclist.length == 0);
    if (genericMode_SearchHemi == true) {
        ShowGenToc2(topiclist);
        return;
    }
    o = window.frames["mytreeframe"];   /////
    if (selectorMode == "F") {
        o.SetTopicList("FILTERED", topiclist, "parent.result_Search2");
    }
    else if (selectorMode == "H") {
        o.SetTopicList("HEMI", topiclist, "parent.result_Search2");
    }
    else if (selectorMode == "FH1") {
        o.SetTopicList("FILTERED", topiclist, "parent.result_Search2");
    }
    else if (selectorMode == "FH2") {
        o.SetTopicList("HEMI", topiclist, "parent.result_Search2");
    }
}

var _showBookmark = true;

function ShowAll() {
    o = this.frames["mytreeframe"];
    if (!o)
        return;
    dA = o.document.getElementById("treeControlHostForAll");
    dS = o.document.getElementById("treeControlHostForFiltered");
    dSf = o.document.getElementById("flatControlHostForFiltered");
    dH = o.document.getElementById("treeControlHostForHemi");
    dHf = o.document.getElementById("flatControlHostForHemi");
    dFH = o.document.getElementById("treeControlHostForFilteredHemi");
    dFHf = o.document.getElementById("flatControlHostForFilteredHemi");
    dA.style.display = "block";
    dS.style.display = "none";
    dSf.style.display = "none";
    dH.style.display = "none";
    dHf.style.display = "none";
    dFH.style.display = "none";
    dFHf.style.display = "none";
    o.treeViewMode = "ALL";

    var bookmarkIndex = lms_getBookmark();
    var troot = (_tree_root == "" ? o.titles[0] : _tree_root);
    if (_associated_content == false && _see_also == false && _showBookmark) {
        var kb = troot.substr(37);
        if (_treeIndex >= 0) {
            bookmarkIndex = parseInt(_treeIndex, 10);
            kb = 0;
        }
        var chindex = null;
        try {
            chindex = parseInt(kb, 10) + bookmarkIndex;
        }
        catch (e) { };
        o.createTreeControl(troot, false, null, null, chindex);
    }
    else {
        o.createTreeControl(troot, false, null, _seealso_selecteditem);
    }
    SearchResult_Show(false);
    _showBookmark = false;
}

function ShowFiltered() {
    o = this.frames["mytreeframe"];
    if (!o)
        return;
    dA = o.document.getElementById("treeControlHostForAll");
    dS = o.document.getElementById("treeControlHostForFiltered");
    dSf = o.document.getElementById("flatControlHostForFiltered");
    dH = o.document.getElementById("treeControlHostForHemi");
    dHf = o.document.getElementById("flatControlHostForHemi");
    dFH = o.document.getElementById("treeControlHostForFilteredHemi");
    dFHf = o.document.getElementById("flatControlHostForFilteredHemi");
    // hide other divs
    dA.style.display = "none";
    dH.style.display = "none";
    dHf.style.display = "none";
    dFH.style.display = "none";
    dFHf.style.display = "none";
    // determine view
    var _fm = o.GetActualFlatView();
    if (_goToFlatMode == true)
        _fm = true;
    // set filtered view
    dS.style.display = (_fm ? "none" : "block");
    dSf.style.display = (_fm ? "block" : "none");

    _goToFlatMode = false;
    o.treeViewMode = "FILTERED";
    o.createTreeControl(o.titles[0], _fm);
    SearchResult_Show(true);
    _showBookmark = false;
    document.getElementById("resulttext").innerHTML = filterHTML(lastExpressionF);
}

function ShowHemi() {
    o = this.frames["mytreeframe"];
    if (!o)
        return;
    dA = o.document.getElementById("treeControlHostForAll");
    dS = o.document.getElementById("treeControlHostForFiltered");
    dSf = o.document.getElementById("flatControlHostForFiltered");
    dH = o.document.getElementById("treeControlHostForHemi");
    dHf = o.document.getElementById("flatControlHostForHemi");
    dFH = o.document.getElementById("treeControlHostForFilteredHemi");
    dFHf = o.document.getElementById("flatControlHostForFilteredHemi");
    // hide other divs
    dA.style.display = "none";
    dS.style.display = "none";
    dSf.style.display = "none";
    dFH.style.display = "none";
    dFHf.style.display = "none";
    // determine view
    var _fm = o.GetActualFlatView();
    if (_goToFlatMode == true)
        _fm = true;
    // set hemi view
    dH.style.display = (_fm ? "none" : "block");
    dHf.style.display = (_fm ? "block" : "none");
    _goToFlatMode = false;
    o.treeViewMode = "HEMI";
    o.createTreeControl(o.titles[0], _fm);
    SearchResult_Show(false);
    _showBookmark = false;
}

function ShowFilteredHemi() {
    o = this.frames["mytreeframe"];
    if (!o)
        return;
    dA = o.document.getElementById("treeControlHostForAll");
    dS = o.document.getElementById("treeControlHostForFiltered");
    dSf = o.document.getElementById("flatControlHostForFiltered");
    dH = o.document.getElementById("treeControlHostForHemi");
    dHf = o.document.getElementById("flatControlHostForHemi");
    dFH = o.document.getElementById("treeControlHostForFilteredHemi");
    dFHf = o.document.getElementById("flatControlHostForFilteredHemi");

    // hide other divs
    dA.style.display = "none";
    dS.style.display = "none";
    dSf.style.display = "none";
    dH.style.display = "none";
    dHf.style.display = "none";
    // determine view
    var _fm = o.GetActualFlatView();
    if (_goToFlatMode == true)
        _fm = true;
    // set filtered hemi view
    dFH.style.display = (_fm ? "none" : "block");
    dFHf.style.display = (_fm ? "block" : "none");
    _goToFlatMode = false;
    o.treeViewMode = "FILTEREDHEMI";
    _goToFlatMode = false;
    o.createTreeControl(o.titles[0], _fm);
    SearchResult_Show(true);
    _showBookmark = false;
    document.getElementById("resulttext").innerHTML = filterHTML(lastExpressionF);
}

function EmptyContent(hemi) {
    if (!hemi)
        hemi = false;
    if (hemi == true) {
        return '<div style="text-align: center; color: red; font-size: 16px;">' + R_no_results +
                            '<br/><br/><a class="tocMyRoles" href="javascript:viewAll()">' + R_no_results_linkToAll + "</a></div>";
    }
    else {
        return '<div style="text-align: center; color: red; font-size: 16px;">' + R_toc_emptycontent + "</div>";
    }
}

function FastDoIt() {
    p = topicDescriptorCache[actuallySelected];
    if (p.playmodes.indexOf("D") >= 0) {
        HideToc();
        PlayFastDoIt();
    }
    bypassToc = false;
}

var TocFirstCall = true;



//callback function for test

/*
function UserDefinedIASHook(o, b) {
var s = "CONTEXT info:\n";
if (o !== null) {
s += "Application: '" + o.Application + "'\n";
s += "ContextType: '" + o.ContextType + "'\n";
s += "LaunchType: '" + o.LaunchType + "'\n";
s += "Context parts:\n";
for (var i = 0; i < o.Context.Parts.length; i++) {
var a = o.Context.Parts[i];
s += "Id: '" + a.Id + "', Value: '" + a.Value + "'\n";
}
s += "User Defined Value: '" + o.UDV + "'\n";
}
s += "\nGUIDs:\n";
for (var i = 0; i < b.length; i++) {
s += "'" + b[i] + "'\n";
}
alert(s);
}
*/

function TreeFinished(mode, isEmpty) {

    // IAS HOOK !!!
    if (TocFirstCall === true) {
        if (typeof UserDefinedIASHook === 'function' && hemiParam !== null && hemiParam !== undefined) {
            var o = new Object();
            o.Application = (appParam === undefined ? "" : decodeURIComponent(appParam));
            o.ContextType = "ExactMatch";
            o.LaunchType = "Hint";
            if (ctxParam === undefined)
                o.LaunchType = (shParam === undefined ? "External" : "SmartHelp");
            o.Context = new Object();
            o.Context.Parts = new Array();
            if (ctxParam !== undefined) {
                var ctxArray = decodeURIComponent(ctxParam).split(";");
                for (var i = 0; i < ctxArray.length; i++) {
                    var k = ctxArray[i].indexOf(":");
                    var id = ctxArray[i].substr(0, k);
                    var value = ctxArray[i].substr(k + 1);
                    var a = new Object();
                    a.Id = id;
                    a.Value = value;
                    o.Context.Parts.push(a);
                }
            }
            o.UDV = (udvParam === undefined ? "" : udvParam);
            UserDefinedIASHook(o, this.frames["mytreeframe"].foundApplicableList);
        }
    }
    TocFirstCall = false;

    SetSelectionViewText();

    var FDI_called = false;
    if (bypassToc == true) {
        ooo = this.frames["mytreeframe"];
        if (ooo.treeViewMode == "HEMI") {
            if (ooo.GetActualFlatView() == true) {
                if (ooo.GetActualFlatItemCounter() == 1) {
                    FDI_called = true;
                    setTimeout("FastDoIt()", 100);
                }
            }
        }
    }
    if (FDI_called == false)
        bypassToc = false;

    if (!isEmpty) {
        //    	SetSelectionViewText(true);
        EnableSelectionViewText(true);
        return;
    }
    var d;
    o = this.frames["mytreeframe"];
    dA = o.document.getElementById("treeControlHostForAll");
    dS = o.document.getElementById("treeControlHostForFiltered");
    dSf = o.document.getElementById("flatControlHostForFiltered");
    dH = o.document.getElementById("treeControlHostForHemi");
    dHf = o.document.getElementById("flatControlHostForHemi");
    dFH = o.document.getElementById("treeControlHostForFilteredHemi");
    dFHf = o.document.getElementById("flatControlHostForFilteredHemi");
    if (mode == "ALL") {
        dA.innerHTML = EmptyContent();
    }
    else if (mode == "FILTERED") {
        dS.innerHTML = EmptyContent();
        dSf.innerHTML = EmptyContent();
    }
    else if (mode == "HEMI") {
        dH.innerHTML = EmptyContent(true);
        dHf.innerHTML = EmptyContent(true);
    }
    else if (mode == "FILTEREDHEMI") {
        dFH.innerHTML = EmptyContent(true);
        dFHf.innerHTML = EmptyContent(true);
    }
    EnableSelectionViewText(false);

    //	SetSelectionViewText(true,true);
    Refresh(null);
}

var _tocHidden = false;

function HideToc() {
    return;
    /*
    _tocHidden = true;
    window.moveBy(-2000, 0);
    */
}

function ResumeToc() {
    return;
    /*
    if (_tocHidden == true) {
    window.moveBy(2000, 0);
    }
    _tocHidden = false;
    */
}

function DoItFinished(closeToc) {
    if (_closing)
        return;
    window.focus();
    ResumeToc();
    if (closeToc == true) {
        opener = null;
        window.open('', '_self');
        window.close();
    }
}

var topicDescriptorCache = new Array();

function topicDescriptorObj(title, type, tpc, playmodes, jumpInArray, leadin, concept, printitname, userdefined, remediation) {
    this.title = title;
    this.type = type;
    this.tpc = tpc;
    this.playmodes = playmodes;
    this.jumpInArray = jumpInArray;
    this.leadin = leadin;
    this.concept = concept;
    this.printitname = encodeURIComponent(printitname);
    this.userdefined = userdefined;
    this.remediation = remediation;
    this.seealsoroot = "";
    this.seealsolinks = new Array();
}

function _getFilteredStatus(guid) {
    var o = this.frames["mytreeframe"];
    return o.getFilteredStatus(guid);
}

function seeAlsoLink(type, title, guid) {
    this.type = type;
    this.title = title;
    this.guid = guid;
    this.filtered = false;
}

function JumpInPoint(label, frameid) {
    this.label = label;
    this.frame_id = frameid;
}

function CheckSeeAlso(tdesc) {
    if (_see_also == true)
        return false;
    return true;
}

var _playConceptSound = true;

function PlayConceptSound() {
    return _playConceptSound;
}

function SCO_Supported() {
    return _sco;
}

var _launchMode = "";
var _lastSelectedItem = "";
var _lastMode = "Init";
var _lastTpc = "Init";

function TreeItemSelected(tpc, mode) {
    _launchMode = "";
    if (tpc) {
        o = this.frames["mytreeframe"];
        kb = o.getBaseIndex();
        var ki = tpc.substr(37);
        var chIndex = ki - kb;
        if (_lastMode != mode || _lastTpc != tpc)
            actuallyChildIndex = -2222;
        _lastMode = mode;
        _lastTpc = tpc;
        if (chIndex == actuallyChildIndex) {
            SearchProcess_Show(false);
            try {
                if (viewApplicable == true) {
                    this.frames["myconceptframeToc"].SetCtxexParam(lastExpressionH);
                }
                else {
                    this.frames["myconceptframeToc"].SetCtxexParam(null);
                }
            }
            catch (e) { };
            if (roleStatusChanged == true) {
                try {
                    this.frames["myconceptframeToc"].RoleStatusChanged();
                }
                catch (e) { }
                roleStatusChanged = false;
            }
            if (tpc == null && mode == null)
                SetSelectionViewText(null, true);
            else
                SetSelectionViewText();
            EnableSelectionViewText(!_lastSearchResultIsEmpty);
            return;
        }
        actuallyChildIndex = ki - kb;
        //        alert(actuallyChildIndex);

        //        setTimeout("lms_ItemStatus_Changed('" + tpc + "')", 1000);

    }
    _lastMode = mode;
    _lastTpc = tpc;

    if (tpc == null && mode == null)
        SetSelectionViewText(null, true);
    else
        SetSelectionViewText();

    EnableSelectionViewText(!_lastSearchResultIsEmpty);
    if (mode == "HIDE") {
        SearchProcess_Show(false);
        return;
    }
    FocusToSearchField();
    if (tpc == null) {
        //    	SetSelectionViewText(true,true);
        Refresh(null);
        return;
    }
    guid = tpc.substr(0, 36);
    actuallySelected = guid;
    _playConceptSound = true;
    if (topicDescriptorCache[guid]) {
        Refresh(guid);
    }
    else {
        var s = "tpc/" + guid + "/descriptor.xml";
        LoadXMLDoc(s, "TreeItemSelected_Returned_Descriptor", "", guid);
    }
}

function _StartTopic(lMode) {
    try {
        var s = this.frames["myconceptframeToc"].location.href;
        if (s.indexOf("lmstart.html") < 0) {
            setTimeout("_StartTopic('" + lMode + "')", 100);
            return;
        }
        s = this.frames["myconceptframeToc"].frames["myframe"].location.href;
        if (s.indexOf("lmsui.html") < 0) {
            setTimeout("_StartTopic('" + lMode + "')", 100);
            return;
        }
        if (!this.frames["myconceptframeToc"].frames["myframe"].launchTopic) {
            setTimeout("_StartTopic('" + lMode + "')", 100);
            return;
        }
        if (actuallySelected != this.frames["myconceptframeToc"].topicID) {
            setTimeout("_StartTopic('" + lMode + "')", 100);
            return;
        }
    }
    catch (e) {
        setTimeout("_StartTopic('" + lMode + "')", 100);
        return;
    }
    setTimeout("this.frames['myconceptframeToc'].StartTopic('" + lMode + "')", 100);
}

function TreeItemDoubleSelected() {
    tdc = topicDescriptorCache[actuallySelected];

    try {
        if (tdc.type == "Topic") {
            UserPrefs.LoadCookie();
            mode = UserPrefs.DefaultPlayMode;
            _playConceptSound = false;
            if (tdc.playmodes.indexOf(mode) >= 0) {
                //            PlayTopic(mode);
                _launchMode = mode;
                if (_lastSelectedItem == actuallySelected) {
                    _StartTopic(_launchMode);
                }
            }
            else {
                modestr = R_mode_seeit;
                switch (mode) {
                    case "T":
                        modestr = R_mode_tryit;
                        break;
                    case "K":
                        modestr = R_mode_knowit;
                        break;
                    case "D":
                        modestr = R_mode_doit;
                        break;
                    case "P":
                        modestr = R_mode_printit;
                        break;
                    default:
                        modestr = R_mode_seeit;
                        break;
                }
                alert(R_not_playable1 + modestr + R_not_playable2);
            }
        }
    }
    catch (e) {
        setTimeout("TreeItemDoubleSelected()", 100);
        return;
    }

}

function fixHTMLString(strHTMLString) {
    strHTMLString = replaceString("<", "&lt;", strHTMLString);
    strHTMLString = replaceString(">", "&gt;", strHTMLString);
    strHTMLString = replaceString("'", "&#39;", strHTMLString);
    strHTMLString = replaceString('"', "&#34;", strHTMLString);

    return strHTMLString;
}

function getDescriptorItem(req, itemname) {
    var item = "";
    try {
        var nodes = req.responseXML.getElementsByTagName(itemname);
        if (nodes.length > 0) {
            n = nodes[0];
            if (n.textContent != null)
                item = n.textContent;
            else if (n.text != null)
                item = n.text;
            else if (n.firstChild.data != null)
                item = n.firstChild.data;
        }
    }
    catch (e) { };
    return item;
}

function TreeItemSelected_Returned_Descriptor(req, id) {
    var playmodes = getDescriptorItem(req, "PlayModes");

    jumpInArray = new Array();
    nodes = req.responseXML.getElementsByTagName("JumpIn");
    for (var i = 0; i < nodes.length; i++) {
        n = nodes[i];
        if (n.textContent)
            label = n.textContent;
        else if (n.text)
            label = n.text;
        else if (n.firstChild.data)
            label = n.firstChild.data;
        a = n.attributes[0];
        frameid = a.nodeValue;
        jumpInArray[jumpInArray.length] = new JumpInPoint(fixHTMLString(label), frameid);
    }
    _leadIn = "./toc/empty.html";
    nodes = req.responseXML.getElementsByTagName("Leadin");
    if (nodes.length > 0) {
        _leadIn = "./tpc/" + id + "/leadin.html";
    }
    _concept = "";
    nodes = req.responseXML.getElementsByTagName("Concept");
    if (nodes.length > 0) {
        n = nodes[0];
        if (n.textContent)
            _concept = n.textContent;
        else if (n.text)
            _concept = n.text;
        else if (n.firstChild.data)
            _concept = n.firstChild.data;

        if (_concept.indexOf('odrel://') == 0)
            _concept = resolve(_concept);
    }
    _title = getDescriptorItem(req, "Title");
    _type = getDescriptorItem(req, "Type");
    _printitname = getDescriptorItem(req, "PrintItName");
    _userdefined = getDescriptorItem(req, "UserDefined");

    _remediation = getDescriptorItem(req, "Remediation");
    if (_remediation == "")
        _remediation = "Always";

    topicDescriptorCache[id] = new topicDescriptorObj(_title, _type, id, playmodes, jumpInArray, _leadIn, _concept, _printitname, _userdefined, _remediation);

    nodes = req.responseXML.getElementsByTagName("SeeAlsoRoot");
    if (nodes.length > 0) {
        n = nodes[0];
        var saroot = "";
        if (n.textContent)
            saroot = n.textContent;
        else if (n.text)
            saroot = n.text;
        else if (n.firstChild.data)
            saroot = n.firstChild.data;
        topicDescriptorCache[id].seealsoroot = saroot;
    }

    nodes = req.responseXML.getElementsByTagName("SeeAlso");
    for (var i = 0; i < nodes.length; i++) {
        n = nodes[i];
        var type = "";
        var title = "";
        var guid = "";
        for (var j = 0; j < n.attributes.length; j++) {
            var a = n.attributes[j];
            if (a.nodeName == "Type")
                type = getTextContent(a);
            if (a.nodeName == "Title")
                title = getTextContent(a);
            if (a.nodeName == "Guid")
                guid = getTextContent(a);
        }
        if (type.length > 0 && title.length > 0) {
            topicDescriptorCache[id].seealsolinks[topicDescriptorCache[id].seealsolinks.length] = new seeAlsoLink(type, title, guid);
        }
    }

    Refresh(id);
}

function getTextContent(n) {
    try {
        if (n.textContent)
            return n.textContent;
        else if (n.text)
            return n.text;
        else if (n.firstChild.data)
            return n.firstChild.data;
        return "";
    }
    catch (e) {
        return "";
    }
}

var lastConcept = "";

var rcTimeout = null;

var nextConcept = "";

function EmptyHtmlLoaded() {
    this.frames["myconceptframeToc"].location.replace(urlParser.GetCorrectUrl(nextConcept));
}

function SetConceptLocation(s) {
    nextConcept = AbsUrl(s);
    EmptyHtmlLoaded();
    //    this.frames["myconceptframe"].location.replace(AbsUrl("./toc/empty.html?callback"));
}

function _RefreshConcept(noplaysound) {
    if (!noplaysound)
        noplaysound = false;
    if (lastConcept != "") {
        if (lastConcept.indexOf(".htm") > 0) {
            if (noplaysound == true)
                _playConceptSound = false;
            SetConceptLocation(lastConcept);
        }
    }
}

function RefreshConcept() {
    try {
        clearTimeout(rcTimeout);
    }
    catch (e) {
    }
    //    rcTimeout = setTimeout("_RefreshConcept();", 300);
}

function OnUpdatePreferences() {
    _RefreshConcept(true);
}

var psInit = null;

function PlaySound_Init() {
    try {
        this.frames["myconceptframeToc"].PlaySound_Init();
    }
    catch (e) { };
}

function ShowConcept(s) {
    if (s == lastConcept) {
        try {
            if (_playConceptSound == true)
                psInit = setTimeout("PlaySound_Init()", 500);
            else
                clearTimeout(psInit);
        }
        catch (e) { };
        return;
    }
    lastConcept = s;
    SetConceptLocation(s);
}

/*
// I don't know what the assessment player is going to need yet, so these are just copied from the
// PlayerPackage sample referenced by "Assessments in the Player" [Alan Groupe]
function api_endcourse()
{
if (api != null)
{
api.SetValue("cmi.exit", "suspended"); // if completed, then exit=normal, else exit=suspended
api.SetValue("cmi.session_time", "PT1H5M") ;
api.SetValue("cmi.suspend_data", "suspend_data") ;
api.SetValue("cmi.completion_status", "incomplete") 
//if (assess || question || topic that has knowit) && TrackScore==true)
//{
//    api.SetValue("cmi.score.scaled") 
//    api.SetValue("cmi.score.raw") 
//    api.SetValue("cmi.score.min") 
//    api.SetValue("cmi.score.max") 
//}
api.Terminate("");
}
}

function api_Getparam()
{
if (api != null)
{
api.Initialize("");
var completionStatus = api.GetValue("cmi.completion_status")  
var suspendData = api.GetValue("cmi.suspend_data")	
var studendID = api.GetValue("cmi.student_id")
var studentName = api.GetValue("cmi.student_name")
}
}
*/


function Refresh(id) {
    //End Leaerner Session
    /*    
    if (apiframe.APIControl != undefined && apiframe.APIControl != null)
    {
    apiframe.APIControl.EndLearnerSession();
    }
    api=null;
    API_1484_11 = null;
    */
    //Continue to Launch new item
    if (id != null)
        TreeRefreshed(id.substr(0, 36));
    RefreshNavigationButtons();
    SearchProcess_Show(false);
    if (_conceptContainerObj == null)
        _conceptContainerObj = getObjectById("conceptcontainerToc");
    //    _conceptContainerObj.style.height = "0px";
    if (id == null || id == "null") {
        setTimeout('ShowConcept("./toc/empty.html")', 1);
        conceptVisible = false;
        if (IsIE7()) {
            var cw = $("#contentdiv").width();
            var ch = $("#contentdiv").height();
            $("#conceptcontainerToc").css({ "width": cw + "px", "height": ch + "px" });
            $("#myconceptframeToc").css({ "width": cw + "px", "height": ch + "px" });
        }
        Resize();
        return;
    }
    desc = topicDescriptorCache[id];
    concept = desc.concept;

    if (desc.type == "Outline" || desc.type == "Section" || desc.type == "Topic") {
        var mparam = "";
        if (_launchMode.length > 0) {
            mparam = "&mode=" + _launchMode;
        }
        if (desc.type == "Topic" && viewApplicable == true) {
            if (lastExpressionH.length > 0) {
                mparam += "&ctxex=" + lastExpressionH;
            }
        }
        concept = "./tpc/" + id + "/lmstart.html?toc" + (_launchFromKPath ? "&launchFromKPath" : "") + "&lmsChildIndex=" + actuallyChildIndex + mparam;
    }

    if (desc.type == "Question") {
        concept = "./tpc/" + id + "/lmstart.html?toc" + (_launchFromKPath ? "&launchFromKPath" : "") + "&lmsChildIndex=" + actuallyChildIndex;
    }
    if (desc.type == "Assessment") {
        o = this.frames["mytreeframe"];
        ownerid = "";
        if (o != null) {
            ownerid = o.getOwnerOfSelection().substr(0, 36);
        }
        concept = "./tpc/" + id + "/lmstart.html?toc" + (_launchFromKPath ? "&launchFromKPath" : "") + "&owner=" + ownerid + "&lmsChildIndex=" + actuallyChildIndex;
    }
    _lastSelectedItem = actuallySelected;
    if (concept.length == 0)
        concept = desc.leadin;

    setTimeout('ShowConcept("' + concept + '")', 50);
    //	this.frames["myconceptframe"].location.href=AbsUrl(concept);
    conceptVisible = true;
    //	document.getElementById("concepttitle").innerHTML=desc.title;

    if (IsIE7()) {
        var cw = $("#contentdiv").width();
        var ch = $("#contentdiv").height();
        $("#conceptcontainerToc").css({ "width": cw + "px", "height": ch + "px" });
        $("#myconceptframeToc").css({ "width": cw + "px", "height": ch + "px" });
    }

    RolesRemoved();

    Resize();

    //    LoadRuntime(id);
}

function LoadRuntime(id) {
    var desc = topicDescriptorCache[id];
    var concept = desc.concept;

    /*	
    //SCORM get runtime
    if (desc.playmodes.length != 0 || concept.length != 0)
    {
    try
    {
    apiframe.LoadRuntime(UserID, id, 0, 0, 0);
    api = apiframe.API;            
    }
    catch(e)
    {
    api = null;
    }
    }
	
    if (desc.playmodes.length != 0) //Topic
    {
    api_Getparam();
    API_1484_11 = null;
    }
    else //Concept
    {    
    API_1484_11 = api; //Concept SCO tries to find API_1484_11 in parent window when it is launched.
    }
    */
    if (concept.length == 0)
        concept = desc.leadin;

    setTimeout('ShowConcept("' + concept + '")', 50);
    conceptVisible = true;
    RolesRemoved();

    Resize();
}

function GetBasePath() {
    base = this.location.href;
    k = base.indexOf('?');
    if (k < 0)
        k = base.indexOf('#');
    if (k >= 0)
        base = base.substr(0, k);
    k = base.lastIndexOf('/');
    b = base.substr(0, k);
    return b;
}

function ClosePlayer() {
    try {
        if (playerwindow) {
            if (!playerwindow.closed) {
                playerwindow.close();
            }
        }
    }
    catch (e) { };
}

function PlayFastDoIt() {
    _playConceptSound = false;
    try {
        this.frames["myconceptframeToc"].Sound_Stop();
    }
    catch (e) { };

    var params = "mode=D";
    if (viewApplicable == true) {
        if (lastExpressionH.length > 0) {
            params += "&ctxex=" + lastExpressionH;
        }
    }
    desc = topicDescriptorCache[actuallySelected];
    var k = desc.playmodes.indexOf("P");
    if (k >= 0 && desc.printitname.length > 0) {
        params += "&printitname=" + desc.printitname;
    }
    if (bypassToc == true) {
        params += "&fastdoit=true";
    }
    if (toc_safeUriMode == true) {
        params = "su=" + Escape.SafeUriEscape(params);
    }
    b = GetBasePath();
    LaunchDoIt(b + "/tpc/" + actuallySelected + "/", params);
}

function OnQuestionContinue() {
    //    alert("next");
    o = this.frames["mytreeframe"];
    if (!o)
        return;
    o.GoToNext();

}

function ShowNewToc(guid) {
    var base = GetBasePath();
    window.open(base + "/toc.html?sac=sac_" + guid, "SacTocWnd");
}

/**** moved here from toc0 *****************************************************************************/


var showParameters = false;
var searchParam = null;
var hemiParam = null;
var appParam = null;
var ctxParam = null;
var udvParam = null;
var shParam = null;
var genericMode = false;
var genericMode_SearchHemi = false;
var searchVisible = false;
var conceptVisible = false;
var allRoles = new Array();
var _rolesRemoved = false;
var ctxTopicList = new Array();
var ctxTopicList2 = new Array();
var onTocLoaded = false;
var showButtons = new Array();
var _tree_root = "";
var _sco = false;
var _associated_content = false;
var _see_also = false;
var _seealso_selecteditem = 0;
var isTocHtml = true;
var _selectedItemId = 0;
var _deviceDPI = 0;
var _launchFromKPath = false;
var _treeIndex = -1;

function IsReducedMode() {
    return (_tree_root.length > 0);
}

function NoWrap(s) {
    var ss = "";
    for (var i = 0; i < s.length; i++) {
        if (s.substr(i, 1) == " ") {
            ss += "&nbsp;";
        }
        else {
            ss += s.substr(i, 1);
        }
    }
    return ss;
}

function _getObjectById(owner, id) {
    for (var i = 0; i < owner.childNodes.length; i++) {
        cni = owner.childNodes[i];
        if (cni.id == id) {
            return cni;
        }
        else {
            obj = _getObjectById(cni, id);
            if (obj != null)
                return obj;
        }
    }
    return null;
}

function getObjectById(id) {
    return document.getElementById(id);
    //				return _getObjectById(document.body,id);
}

////////////////////////////////////////////////////////////////////////////

var _ftcobj = null;
var _myTableObj = null;
var _header1DivObj = null;
var _treeContainerObj = null;
var _conceptContainerObj = null;
var _searchResultObj = null;
var _pmTableObj = null;
var _ctTableObj = null;
var _searchBoxObj = null;
var _changeViewObj = null;
var _sres0Obj = null;
var _sres1Obj = null;
var _sres2Obj = null;
var _resulttextObj = null;
var _vbordersize = 10;
var _hbordersize = 10;
var _sbordersize = 10;

function getOffsetLeft(myobj) {
    var parentOffsets = 0;
    if (myobj.parentNode)
        parentOffsets = getOffsetLeft(myobj.parentNode);
    var offset = (myobj.offsetLeft ? myobj.offsetLeft : 0);
    return offset + parentOffsets;
}

function getOffsetTop(myobj) {
    var parentOffsets = 0;
    if (myobj.parentNode)
        parentOffsets = getOffsetTop(myobj.parentNode);
    var offset = (myobj.offsetTop ? myobj.offsetTop : 0);
    return offset + parentOffsets;
}

function coverToSep() {
    if (_cover_dragged)
        return;
    var sepobj = document.getElementById("sepdiv");
    var coverobj = document.getElementById("cover");
    coverobj.style.width = sepobj.clientWidth + "px";
    coverobj.style.height = sepobj.clientHeight + "px";
    offsetLeft = getOffsetLeft(sepobj);
    offsetTop = getOffsetTop(sepobj);
    coverobj.style.top = offsetTop + "px";
    coverobj.style.left = offsetLeft + "px";
}

function coverToFull() {
    var coverobj = document.getElementById("cover");
    coverobj.style.top = "0px";
    coverobj.style.left = "0px";
    coverobj.style.width = "100%";
    coverobj.style.height = "100%";
}

var _cover_dragged = false;

function sepD() {
    _cover_dragged = true;
    coverToFull();
    var coverobj = document.getElementById("cover");
    if (coverobj.setCapture)
        coverobj.setCapture();
}

function sepM(event) {
    if (!_cover_dragged)
        return;
    if (_ftcobj == null)
        _ftcobj = getObjectById("ftc");
    e = event;
    if (e == null)
        e = window.event;
    w = e.clientX - _sbordersize - _sbordersize / 2;
    if (IsIE7()) {
        w += 28;
    }
    if (w > 200) {
        _ftcobj.style.width = "" + w + "px";
        $("#contentdiv").css("left", (w + 10) + "px");
        if (IsIE7()) {
            var cw = $("#contentdiv").width();
            $("#conceptcontainerToc").css("width", cw + "px");
            $("#myconceptframeToc").css("width", cw + "px");
        }
    }
    else { w = 200; }
    if (_treeContainerObj == null)
        _treeContainerObj = getObjectById("treecontainer");
    w = _treeContainerObj.clientWidth - 40;
    setTimeout("_HResize()", 1);
}

function sepU() {
    _cover_dragged = false;
    coverToSep();
    var coverobj = document.getElementById("cover");
    if (coverobj.releaseCapture)
        coverobj.releaseCapture();
    if (document.frames)
        document.frames[0].focus();
    if (_ftcobj == null)
        _ftcobj = getObjectById("ftc");
    var c = new Cookie(document, "OnDemandToc", 365);
    c.Load();
    c.Separator = _ftcobj.offsetWidth;
    c.Store();
}

////////////////////////////////////////////////////////////////////////////

function OpenSeeAlso(seeAlsoRoot, index) {
    this.frames["myconceptframeToc"].OpenSeeAlso(seeAlsoRoot, index);
    //			var base = GetBasePath();
    //			window.open(base + "/toc.html?seealso=" + seeAlsoRoot + "&selectitem=" + index);
}

function launchTopic(mode, frame_id, fromjumpin) {
    // launch topic (in lms.js)
    this.frames["myconceptframeToc"].StartTopic(mode, frame_id, fromjumpin);
}

function ShowAbout() {
    // in pt (400x500px)
    showDialog("data/toc/about.html", -1, -1, 300, 375, true, _deviceDPI);
}

function TreeRefreshed(id) {
    _selectedItemId = id;
}

function ConnectionLostEvent(errText) {
    this.frames["myconceptframeToc"].ConnectionLostEvent(errText);
}

////////////////////////////////////////////////////////////////////////////

function SearchResult_Show(k) {
    if (_searchResultObj == null)
        _searchResultObj = getObjectById("searchresult");
    _searchResultObj.style.display = (k ? "" : "none");
    viewSearch = k;
    searchVisible = k;
    Resize();
}

function SearchProcess_Show(k) {
    if (k) {
        document.getElementById("coversearch").style.width = "100%";
        document.getElementById("coversearch").style.height = "100%";
        sprd = document.getElementById("searchprdiv");
        sprd.style.display = "block";
        w = Math.round((document.body.clientWidth / 2) - 60);
        h = Math.round((document.body.clientHeight / 2) - 20);
        sprd.style.left = (document.all ? w : "" + w + "px");
        sprd.style.top = (document.all ? h : "" + h + "px");
    }
    else {
        document.getElementById("coversearch").style.width = "0px";
        document.getElementById("coversearch").style.height = "0px";
        document.getElementById("searchprdiv").style.display = "none";
    }
}

function Resize() {
    setTimeout("_Resize()", 1);
}

function Resize0() {
    setTimeout("_Resize()", 0);
}

function _HResize() {
    if (checkIEDPI() == false)
        return;

    if (isOpenDialog)
        if (isOpenDialog() == true)
            resizeDialog();

    coverToSep();

    if (_sres0Obj == null)
        _sres0Obj = getObjectById("sres0");
    if (_sres1Obj == null)
        _sres1Obj = getObjectById("sres1");
    if (_sres2Obj == null)
        _sres2Obj = getObjectById("sres2");
    if (_resulttextObj == null)
        _resulttextObj = getObjectById("resulttext");
    w0 = _sres0Obj.clientWidth;
    w1 = _sres1Obj.clientWidth;
    w2 = _sres2Obj.clientWidth;
    if (w1 == 0)
        return;
    w = w0 - w1 - 8;
    _sres2Obj.style.width = "" + w + "px";
    if (document.all) {
        if (w >= 12)
            _resulttextObj.style.width = "" + (w - 12) + "px";
    }
}

function _Resize() {
    if (checkIEDPI() == false)
        return;
    if (document.body.clientHeight < 100 || document.body.clientWidth < 100) {
        _HResize();
        return false;
    }
    if (viewApplicable == true || (allRoles.length > 0 && PlayerConfig.EnableCookies == true)) {
        getObjectById("appandroles").className = 'tocSearchColor modebuttonshow';
    }
    if (_myTableObj == null)
        _myTableObj = getObjectById("myTableToc");
    if (_header1DivObj == null)
        _header1DivObj = getObjectById("header1table");
    if (_treeContainerObj == null)
        _treeContainerObj = getObjectById("treecontainer");
    if (_conceptContainerObj == null)
        _conceptContainerObj = getObjectById("conceptcontainerToc");
    if (_searchResultObj == null)
        _searchResultObj = getObjectById("searchresult");
    if (_changeViewObj == null)
        _changeViewObj = getObjectById("changeview");
    if (_pmTableObj == null)
        _pmTableObj = getObjectById("playmodetable");
    if (_ctTableObj == null)
        _ctTableObj = getObjectById("concepttitletable");

    _HResize();

    h = document.body.clientHeight - _hbordersize * 2 - _header1DivObj.clientHeight;

    if (IsSafari() || IsFF3())
        h -= 2;

    h -= 4;
    if (h >= 0)
        _myTableObj.style.height = "" + h + "px";

    var showChangeView = (viewApplicable || searchVisible);

    _changeViewObj.className = (showChangeView ? 'tocSearchColor modebuttonshow' : 'tocSearchColor modebuttonhide');

    hh = 0;
    if (searchVisible)
        hh = _searchResultObj.clientHeight;

    if (showChangeView)
        hh += getObjectById("changeview").clientHeight;

    try {
        _approles_correction = 46;
        if (document.all && (viewApplicable == true || allRoles.length > 0)) {
            _approles_correction = 52;
        }
        if (_tree_root != "") {
            if (IsFF() || IsSafari())
                _approles_correction -= 19;
            else
                _approles_correction -= 25;
        }
        _treeContainerObj.style.height = "" + (h - _approles_correction - hh) + "px";
    }
    catch (e) {
        _treeContainerObj.style.height = "0px";
    }

    hh = h;
    hh += 4;
    if (hh >= 0)
        _conceptContainerObj.style.height = "" + (hh + (IsFF() || IsSafari() ? 3 : 1)) + "px";
    RefreshConcept();

    w = getObjectById("blogo").clientWidth;
    getObjectById("blogoframe").style.width = "" + (w + 20) + "px";

    if (IsIE7()) {
    	var cd = $("#contentdiv");
    	var cdh = cd.height();
    	var cdw = cd.width();
    	$("#myconceptframeToc").css({ "height": cdh + "px", "width": cdw + "px" });
    }
    try {
        document.frames["myconceptframeToc"].ResizeFrame();
    }
    catch (e) { };
}

function MyEventKeyDown(event) {
    if (!event)
        event = window.event;
    code = event.keyCode;
    if (code == 27) {
        // todo: this must be handled in some way
        // probably dialog2.html should handle key events
        // this function is obsolete
        //				JumpIn_Show(null, null);
        try {
            if (parent.isOpenDialog()) {
                parent.closeDialog();
                return;
            }
        }
        catch (e) { };
    }
    if (code == 13 && _inputHasFocus == true) {
        Search_Click();
        return false;
    }
}

function FocusToSearchField() {
    return;
    /*
    try {
    var sb = getObjectById("searchbox");
    sb.focus();
    }
    catch (e) {
    }
    */
}

function applicable_Click() {
    var o = getObjectById("chapp");
    if (o.checked) {
        viewApplicable = true;
        _goToFlatMode = true;
        Select(0);
    }
    else {
        viewApplicable = false;
        Select(0);
    }
}

function applicable_Clear() {
    var o = getObjectById("chapp");
    o.checked = false;
    applicable_Click();
}

function Search_Click() {
    if (_inputIsEmpty == true)
        return;
    try {
        a = moduleName;
    }
    catch (e) {
        return;
    }
    viewSearch = true;
    _goToFlatMode = true;
    FocusToSearchField();
    SetSelectionViewText(true);
    Select(1);
}

function Search_Clear_Click() {
    var sb = getObjectById("searchbox");
    sb.value = "";
    OnInputBlur();
    if (viewSearch == false)
        return;
    viewSearch = false;
    FocusToSearchField();
    Select(0);
    SearchProcess_Show(false);
}

function SetSelectionViewText(flatMode, empty) {
    o = this.frames["mytreeframe"];
    flatMode = o.GetActualFlatView();
    if (!empty)
        empty = o.IsActualViewEmpty();
    if (empty == true) {
        document.getElementById("selectionviewtext").innerHTML = "";
    }
    else {
        document.getElementById("selectionviewtext").innerHTML = (flatMode ? R_toc_tree_view_in_outline : R_toc_tree_view_resultlist);
    }
}

function EnableSelectionViewText(enable) {
    if (viewApplicable)
        enable = true;
    s = (enable ? 'visible' : 'hidden');
    document.getElementById("selectionviewtext").style.visibility = s;
}

function ChangeView_Click() {
    o = this.frames["mytreeframe"];
    if (!o)
        return;
    flatMode = o.ChangeTreeView();
    SetSelectionViewText(flatMode);
}

var _inputIsEmpty = true;
var _inputHasFocus = false;

function OnInputFocus() {
    _inputHasFocus = true;
    if (_inputIsEmpty == true) {
        var sb = getObjectById("searchbox");
        sb.value = "";
        sb.className = "tocSearch";
    }
    _inputIsEmpty = false;
}

function OnInputBlur() {
    _inputHasFocus = false;
    var sb = getObjectById("searchbox");
    if (sb.value == "") {
        _inputIsEmpty = true;
        sb.value = R_Toc_search;
        sb.className = "tocSearchBarText";
    }
    else {
        _inputIsEmpty = false;
        sb.className = "tocSearch";
    }
}

function SearchFontSize(s) {
    for (var i = 1; i < document.styleSheets.length; i++) {
        var ss = document.styleSheets[i];
        if (ss.rules) {
            for (var j = 0; j < ss.rules.length; j++) {
                var rr = ss.rules[j];
                if (rr.selectorText == s) {
                    return rr.style.fontSize;
                }
            }
        }
        else if (ss.cssRules) {
            for (var j = 0; j < ss.cssRules.length; j++) {
                var rr = ss.cssRules[j];
                if (rr.selectorText == s) {
                    return rr.style.fontSize;
                }
            }
        }
    }
    return "";
}

function getAbsoluteXPosInToc(nonabspos) {
    b = getObjectById("tvertical1");
    _vbordersize = b.clientWidth;
    b = getObjectById("tsep1");
    _sbordersize = b.clientWidth;
    ftcwidth = Number(String(_ftcobj.style.width).substring(0, String(_ftcobj.style.width).length - 2));
    return ftcwidth + nonabspos + _vbordersize + _sbordersize;
}

function getAbsoluteYPosInToc(nonabspos) {
    b = getObjectById("thorizontal1");
    _hbordersize = b.clientHeight;
    return _header1DivObj.clientHeight + _hbordersize + nonabspos;
}

function Toc_onCloseDialog() {
    $("#searchbox").focus();
    $("#searchbox").blur();
}

function Init() {

    // Get the current device DPI
    if (_deviceDPI == 0)
        _deviceDPI = getDpiInfo();

    if (_deviceDPI == 0) {
        setTimeout("Init()", 100);
        return;
    }

    if (_deviceDPI != 96) {
        if (getDPICookie() == false) {
            this.location.replace("./../js/unsuppdpi.html?" + Escape.MyEscape(AbsUrl(this.location.href)));
            return;
        }
    }

    setOnCloseEvent("Toc_onCloseDialog()");
    ParseArguments();

    if (_see_also == false && _associated_content == false)
        InitLmsMode("toc");
    var chindex = 0;
    if (_lmsMode != null)
        chindex = 0 - 1;
    if (_see_also == true || _associated_content == true)
        chindex = 0 - 1;

    try {
        if (soundIsExported == undefined)
            soundIsExported = false;
        if (soundIsExported == null)
            soundIsExported = false;
    }
    catch (e) {
        soundIsExported = false;
    }

    if (_lmsMode != null) {
        if (urlParser.GetParameter("nosound") == null) {
            if (Sound_Init(soundIsExported, UserPrefs.PlayAudio, null, false, "../") == false)
                return;
        }
    }

    if (lms_initialized == false) {
        lms_InitPage(chindex, (_lmsMode == null ? window.opener : null), null, "Init()");
        return;
    }

    if (urlParser.GetParameter("nosound") != null) {
        SetNoSound(true);
    }

    this.frames["mytreeframe"].location.replace("./toc/outline-tree.html");
}

function Init_treeloaded() {
    /*
    if (!document.all) {
    bypassToc = false;
    }
    */
    var h1 = getObjectById("header1table");
    h3img = getObjectById("bannerimg");
    w = h3img.clientWidth;
    h3img.style.height = "" + (h1.clientHeight) + "px";
    h3img.style.width = "" + w + "px";
    b = getObjectById("thorizontal1");
    _hbordersize = b.clientHeight;
    b = getObjectById("tvertical1");
    _vbordersize = b.clientWidth;
    b = getObjectById("tsep1");
    _sbordersize = b.clientWidth;

    {
        var sbox = document.getElementById("searchbox");
        var fs = parseInt(SearchFontSize(".tocSearch"));
        var h = parseInt(sbox.style.height);
        var d = Math.floor((h - fs) / 2);
        sbox.style.height = "" + (h - d) + "px";
        sbox.style.paddingTop = "" + d + "px";
    }

    try {
        if (_sco == false) {
            var tpref = (UIComponents.TitlePrefix == true ? R_toc_title + " - " : "");
            document.title = tpref + UnescapeQuotes(moduleName);
        }
    }
    catch (e) {
        _Resize();
        //				alert("The content is empty");
        window.onresize = Resize0;
        document.getElementById("cover").onmousemove = sepM;
        document.getElementById("searchbox").disabled = true;
        document.getElementById("contentisemptydiv").innerHTML = R_toc_content_empty;
        document.getElementById("treecontainer").style.verticalAlign = "top";
        document.getElementById("mytreeframe").style.display = "none";
        document.getElementById("contentisemptydiv").style.display = "block";
        return;
    }

    if (_resulttextObj == null)
        _resulttextObj = getObjectById("resulttext");
    if (document.all) {
        _resulttextObj.style.width = "100px";
    }

    //	Enable Preferences button
    if (PlayerConfig.EnableCookies == true && UserPrefs.EnablePreferences == true) {
        var o = getObjectById("prefsbutton");
        //				o.style.display = 'block';
    }

    LoadXMLDocArray("roles.xml", "Roles_Returned", "Roles_Error", "Role", false);

}

function RolesRemoved() {
    if (_rolesRemoved == true)
        alert(R_roles_all_removed);
    _rolesRemoved = false;
}

function Roles_Returned(ret) {

    if (UIComponents.Help === false) {
        ret = new Object();
        ret.length = 0;
    }

    for (var i = 0; i < ret.length; i++) {
        allRoles[i] = ret[i];
    }
    var o = getObjectById("hasrole");
    if (allRoles.length > 0 && PlayerConfig.EnableCookies == true) {
        o.style.display = 'inline';
        s0 = getObjectById("sres0");
        s0.style.height = "30px";

        //					setTimeout("Init1()",50);
    }

    if (UIComponents.Help === false) {
        setTimeout("Init1()", 50);
        return;
    }

    UserRoles.LoadCookie();
    var topLevelLmsMode = GetTopLevelLmsMode();
    if ((topLevelLmsMode != "Cookie") && (topLevelLmsMode != "KPT"))
        UserRoles.Filtering = false;
    if (UserRoles.Filtering == true && allRoles.length == 0) {
        UserRoles.Filtering = false;
        UserRoles.StoreCookie();
        _rolesRemoved = true;
    }
    var o = getObjectById("chroles");
    o.checked = UserRoles.Filtering;
    if (UserRoles.Filtering == true) {
        InitRoles(GetRolesQueryString());
    }
    else {
        setTimeout("Init1()", 50);
    }
}

function Roles_Error() {
    setTimeout("Init1()", 50);
}

function Init0(topiclist) {
    o = window.frames["mytreeframe"];
    o.SetTopicList("ROLES", topiclist, "parent.Init1");
}

function GetAllRoles() {
    return allRoles;
}

function onRoles() {
    showDialog(GetBasePath() + "/../preferences/roles.html", -1, -1, 320, 290, true, _deviceDPI);
}

function roles_Click() {
    var o = getObjectById("chroles");
    if (o.checked == true && UserRoles.Roles.length == 0) {
        o.checked = false;
        onRoles();
        return;
    }
    UserRoles.Filtering = o.checked;
    UserRoles.StoreCookie();
    setRoleFiltering();
}

function onUpdateRoles() {
    setRoleFiltering();
}

function GetRolesQueryString() {
    if (!UserRoles.Filtering) {
        return "NOROLES";
    }
    l = UserRoles.Roles.length;
    if (l == 0) {
        return "NOROLES";
    }
    s = "r";
    for (var i = 0; i < l; i++) {
        rolestr = UserRoles.Roles[i];
        rolestr = Escape.MyUnEscape(rolestr);
        rolestr = rolestr.toLowerCase();
        rolestr = Escape.MyEscape(rolestr);
        s += "'" + rolestr + "'";
        if (i != (l - 1))
            s += "-";
    }
    return s;
}

function setRoleFiltering() {
    SetSelectionViewText(true)
    var o = getObjectById("chroles");
    UserRoles.LoadCookie();
    o.checked = UserRoles.Filtering;
    s = GetRolesQueryString();
    SetRoles(s);
}

function Init1() {
    if (IsSafari())
        document.onkeydown = MyEventKeyDown;
    else
        document.onkeypress = MyEventKeyDown;

    FocusToSearchField();

    if (hemiParam != null || genericMode == true) {
        sb = getObjectById("hasapp");
        sb.style.display = "inline";
        s0 = getObjectById("sres0");
        s0.style.height = "30px";
        if (!document.all)
            sb.style.paddingLeft = "7px";
    }
    else {
        if (allRoles.length > 0 && PlayerConfig.EnableCookies == true) {
            if (!document.all) {
                sb = getObjectById("hasrole");
                sb.style.paddingLeft = "7px";
            }
        }
    }

    if (hemiParam == null && genericMode == false || allRoles.length == 0) {
        var sbox = document.getElementById("searchbox");
        if (IsFF3()) {
            sbox.style.marginTop = "" + (-1) + "px";
        }
        else {
            sbox.style.marginTop = "" + (0) + "px";
        }
    }

    if (_ftcobj == null)
        _ftcobj = getObjectById("ftc");
    var c = new Cookie(document, "OnDemandToc", 365);
    c.Load();
    if (c.Separator) {
        _ftcobj.style.width = "" + c.Separator + "px";
        $("#contentdiv").css("left", (Number(c.Separator) + 10) + "px");
    }
    $("#contentdiv").css("top", (Number($("#header1").height()) + 5) + "px");
    _Resize();
    window.onresize = Resize0;
    document.getElementById("cover").onmousemove = sepM;
    var sb = getObjectById("searchbox");
    sb.value = "";
    OnInputBlur();

    if (showNavigationButtons != true) {
        document.getElementById("navigation1").style.display = "none";
        document.getElementById("navigation2").style.display = "none";
        document.getElementById("nav_and_search_separator").style.display = "none";
    }
    if (_tree_root != "") {
        document.getElementById("appandroles").style.display = "none";
        document.getElementById("searchcontainer1").style.display = "none";
        document.getElementById("searchcontainer2").style.display = "none";
        document.getElementById("searchcontainer3").style.display = "none";

        if (_associated_content == true) {
            document.getElementById("specialcontentdiv").style.display = "block";
            document.getElementById("specialcontenttext").innerHTML = R_toc_associated_content;
            s0 = getObjectById("sres0");
            s0.style.height = "30px";
        }
        if (_see_also == true) {
            document.getElementById("specialcontentdiv").style.display = "block";
            document.getElementById("specialcontenttext").innerHTML = R_toc_see_also;
            s0 = getObjectById("sres0");
            s0.style.height = "30px";
        }
        if (_sco == true) {
            document.getElementById("specialcontentdiv").style.display = "block";
            document.getElementById("specialcontenttext").innerHTML = "";
            document.getElementById("nav_and_search_separator").style.display = "none";
            s0 = getObjectById("sres0");
            s0.style.height = "30px";
        }

        if (IsFF() || IsSafari()) {
            document.getElementById("specialcontentdiv").style.paddingTop = "5px";
        }

    }
    document.getElementById("sres0").style.visibility = "visible";
    if (genericMode == true)              // generic mode
    {
        OnInputBlur();
        var sb = getObjectById("chapp");
        sb.disabled = false;
        sb.checked = true;
        viewApplicable = true;
        Select(5);
    }
    else if (searchParam != null && hemiParam != null) // Filtered Hemi view
    {
        var sb = getObjectById("searchbox");
        sb.value = searchParam;
        OnInputBlur();
        sb = getObjectById("chapp");
        sb.disabled = false;
        sb.checked = true;
        viewApplicable = true;
        Select(3);
    }
    else if (searchParam != null)	// Filtered view
    {
        var sb = getObjectById("searchbox");
        sb.value = searchParam;
        OnInputBlur();
        Select(1);
    }
    else if (hemiParam != null)	// Hemi view
    {
        var sb = getObjectById("chapp");
        sb.disabled = false;
        sb.checked = true;
        viewApplicable = true;
        Select(2);
    }
    else	// All view
    {
        Select(0);
    };
}

function UnescapeHemiParam(s) {
    return replaceString("%27", "'", s);
}

function ParseArguments() {

    if (showParameters == true) {
        var ss = document.location.hash.substring(1);
        var strArgs = ss.split("&");
        if (strArgs.length == 0 || strArgs[0] == "") {
            ss = document.location.search.substring(1);
        };
        alert(ss);
    }


    urlParser = new UrlParser();
    urlParser.Parse();
    toc_safeUriMode = urlParser.GetSafeMode();

    var k = null;
    if (searchParam = urlParser.GetParameter("search")) {
        _goToFlatMode = true;
    }
    if (hemiParam = urlParser.GetParameter("ctxex")) {
        hemiParam = UnescapeHemiParam(hemiParam);
        _goToFlatMode = true;
        appParam = urlParser.GetParameter("app");
        ctxParam = urlParser.GetParameter("ctx");
        udvParam = urlParser.GetParameter("udv");
        shParam = urlParser.GetParameter("sh");
    }
    if (urlParser.GetParameter("genctx") != null) {
        genericMode = true;
        _goToFlatMode = true;
    }
    if (k = urlParser.GetParameter("sac") || "") {
        _tree_root = k;
        _associated_content = true;
    }
    if (k = urlParser.GetParameter("sco") || "") {
        _tree_root = k;
        _sco = true;
        var bsr = GetBigScoReference(_tree_root);
        if (bsr != null) {
            _tree_root = bsr.reference;
            var tpref = (UIComponents.TitlePrefix == true ? R_toc_title + " - " : "");
            document.title = tpref + UnescapeQuotes(bsr.title);
        }
    }
    if (k = urlParser.GetParameter("seealso") || "") {
        _tree_root = k;
        _see_also = true;
    }
    var si;
    if (si = urlParser.GetParameter("selectitem")) {
        _seealso_selecteditem = parseInt(si, 10);
    }
    if (urlParser.GetParameter("launchfromkpath") != null) {
        _launchFromKPath = true;
    }
    if (genericMode == true) {
        searchParam = null;
    }
    if (k = urlParser.GetParameter("treeindex") || "") {
        _treeIndex = k;
    }
}

function BigScoReference() {
    this.reference = "";
    this.title = "";
}

function GetBigScoReference(source) {
    var url = "./toc/" + source + ".xml";
    var xmlHttpRequest = null;
    try {
        if (window.location.href.substr(0, 7).toLowerCase() == "http://" ||
            window.location.href.substr(0, 8).toLowerCase() == "https://") {
            xmlHttpRequest = new XMLHttpRequest();
        }
    }
    catch (e) { }
    finally {
        if (xmlHttpRequest == null)
            xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlHttpRequest.open("GET", url, false);
    try {
        xmlHttpRequest.send();
    }
    catch (e) {
        return null;
    }

    if (location.hostname == "" && xmlHttpRequest.status == 0) {
        if (xmlHttpRequest.responseXML.documentElement == null) {
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = false;
            xmlDoc.loadXML(xmlHttpRequest.responseText);
            xmlHttpRequest = new Object();
            xmlHttpRequest.responseXML = xmlDoc;
        }
    }

    for (var i = 0; i < xmlHttpRequest.responseXML.childNodes.length; i++) {
        var n = xmlHttpRequest.responseXML.childNodes[i];
        if (n.nodeName == "reference") {
            var bsr = new BigScoReference();
            for (var a = 0; a < n.attributes.length; a++) {
                var aa = n.attributes[a];
                if (aa.nodeName == "link")
                    bsr.reference = aa.nodeValue;
                if (aa.nodeName == "title")
                    bsr.title = aa.nodeValue;
            }
            return bsr;
        }
    }
    return null;
}

function IndexObject(index, score) {
    this.index = index;
    this.score = score;
}

function SortFunction(a, b) {
    k = b.score - a.score;
    return k;
}

function ShowGenToc(x) {
    ctxTopicList = new Array();
    ctxTopicList2 = new Array();
    for (var i = 0; i < x.length; i++) {
        ctxTopicList[ctxTopicList.length] = new IndexObject(x[i].index, x[i].score);
    }
    ctxTopicList.sort(SortFunction);
    if (hemiParam == null) {
        ShowGenToc2(null);
    }
    else {
        genericMode_SearchHemi = true;
        Select(2);
    }
}

function ShowGenToc2(x) {
    genericMode_SearchHemi = false;
    if (x != null) {
        for (var i = 0; i < x.length; i++) {
            var ki = x[i].index;
            var _found = false;
            for (var j = 0; j < ctxTopicList.length; j++) {
                var kj = ctxTopicList[j].index;
                if (ki == kj) {
                    _found = true;
                    break;
                }
            }
            if (_found == false) {
                for (var j = 0; j < ctxTopicList2.length; j++) {
                    var kj = ctxTopicList2[j].index;
                    if (ki == kj) {
                        _found = true;
                        break;
                    }
                }
            }

            if (_found == false) {
                ctxTopicList2[ctxTopicList2.length] = new IndexObject(ki, 1);
            }
        }
        if (ctxTopicList2.length > 0) {
            for (var i = 0; i < ctxTopicList.length; i++) {
                ctxTopicList2[ctxTopicList2.length] = ctxTopicList[i];
            }
            ctxTopicList = ctxTopicList2;
        }
    }
    result_Search(ctxTopicList);
}

function IsEmptyArgument(s, keywordlen) {
    if (s.length <= keywordlen)
        return true;
    if (s.length > keywordlen + 2)
        return false;
    ss = s.substr(keywordlen);
    if (ss == '""' || ss == "''")
        return true;
    return false;
}

var _closing = false;

function Closing() {
    lms_ClosePage();
    _closing = true;
    ClosePlayer();
    var c = new Cookie(document, "OnDemandToc", 365);
    c.Load();
    try {
        if (window.screenLeft != null)	// IE
        {
            c.TocLeft = window.screenLeft - 4;
            c.TocTop = window.screenTop - 30;
            c.TocWidth = document.body.clientWidth;
            c.TocHeight = document.body.clientHeight;
        }
        else	// Mozilla
        {
            c.TocLeft = window.screenX;
            c.TocTop = window.screenY;
            c.TocWidth = window.innerWidth;
            c.TocHeight = window.innerHeight;
        }
        c.Store();
    }
    catch (e) { };
}

function buttonDetection(o, simple) {
    if (!simple)
        simple = false;
    var s = o.className;
    if (s.indexOf("previoustraversalarrow_") > -1) {
        return (simple == true ? "prev" : "previoustraversalarrow_");
    }
    if (s.indexOf("nexttraversalarrow_") > -1) {
        return (simple == true ? "next" : "nexttraversalarrow_");
    }
    return "";
}

function buttonStatus(o) {
    var s = o.className;
    var k = s.indexOf("arrow_");
    return s.substr(k + 6, 3);
}

function buttonOver(o) {
    var s = buttonDetection(o);
    if (buttonStatus(o) == "dis")
        return;
    if (s.length > 0)
        o.className = s + "ovr";
}

function buttonOut(o) {
    var s = buttonDetection(o);
    if (buttonStatus(o) == "dis")
        return;
    if (s.length > 0)
        o.className = s + "ena";
}

function buttonEnable(o) {
    var s = buttonDetection(o);
    if (s.length > 0)
        o.className = s + "ena";
}

function buttonDisable(o) {
    var s = buttonDetection(o);
    if (s.length > 0)
        o.className = s + "dis";
}

function buttonClick(o) {
    if (buttonStatus(o) == "dis")
        return;
    if (buttonDetection(o, true) == "prev") {
        this.frames["mytreeframe"].Navigation_Up();
    }
    else {
        this.frames["mytreeframe"].Navigation_Down();
    }
}

function RefreshNavigationButtons() {
    if (this.frames["mytreeframe"].isFirstItem()) {
        buttonDisable(document.getElementById("prevButton"))
    }
    else {
        buttonEnable(document.getElementById("prevButton"))
    }
    if (this.frames["mytreeframe"].isLastItem()) {
        buttonDisable(document.getElementById("nextButton"))
    }
    else {
        buttonEnable(document.getElementById("nextButton"))
    }
}

function NotSupportedYet() {
    alert("Coming soon ...");
}
/* query.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

// OnDemand query parser

datasourceroot = "querydb/";
ConvertDbSelector = { t: "text", u: "ctxod", e: "ctxex", r: "role", g: "genctx" };

var q_search_and = " and ";
var q_search_or = " or ";

function ToHalfWidth(str)
{
  var halfKatakanaSet = "ｦｧｨｩｪｫｬｭｮｯｰｱｲｳｴｵｶｷｸｹｺｻｼｽｾｿﾀﾁﾂﾃﾄﾅﾆﾇﾈﾉﾊﾋﾌﾍﾎﾏﾐﾑﾒﾓﾔﾕﾖﾗﾘﾙﾚﾛﾜﾝ";
  var fullKatakanaSet = "ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン";
  
  var result="";
  
  for (var i=0; i<str.length; i++)
  {
	var k = fullKatakanaSet.indexOf(str.charAt(i));
	if (k!=-1)
		result += halfKatakanaSet.charAt(k);
	else if (str.charCodeAt(i)>=0xff01 && str.charCodeAt(i)<=0xff5f)
		result += String.fromCharCode(str.charCodeAt(i)-0xfee0);
	else
		result += str.charAt(i);
  }
  
  return result;
}

var QueryParser = { 
	PS: null, // stack
	PT: [ 0,
//     e   (   )   &|  !  EOT q
	[  2,  3,  0,  0,  0,  0, 4 ],
	[ -1, -1, -1, -1,  5, -1, 0 ],
	[  2,  3,  0,  0,  0,  0, 6 ],
	[  0,  0,  0,  7,  0, 10, 0 ],
	[ -2, -2, -2, -2, -2, -2, 0 ],
	[  0,  0,  8,  7,  0,  0, 0 ],
	[  2,  3,  0,  0,  0,  0, 9 ],
	[ -4, -4, -4, -4, -4, -4, 0 ],
	[ -3, -3, -3, -3, -3, -3, 0 ]],

Parse: function(query_type, query_expression)
{
	if (window.R_search_AND)
		q_search_and = " " + R_search_AND.toLowerCase() + " ";
	if (window.R_search_OR)
		q_search_or = " " + R_search_OR.toLowerCase() + " ";

	var lexer;
	var keyws;
	if ("URI" == query_type) {
		lexer = /\(|\)|\+|-|[u,e,k,r,g]|!|\d|'[^']+'/g;
		keyws = ["(",")","+","-","u","e","t","r","g","!","0","1","2","3","4","5","6","7","8","9"];
	} else {
		lexer = new RegExp('\\(|\\)|'+q_search_and+'|'+q_search_or+'|"[^"]+"|[^ \\(\\)]+(?=\\(|\\)|\\s|$)','gi'); //doesn't support db|!|\d
		keyws = ["(",")",q_search_and,q_search_or];
	}
	var codem = [1,2,3,3,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4];
	var semvm = [0,0,"&","|",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];


	if (query_type!='URI')
	{
		query_expression = ToHalfWidth(query_expression);
		query_expression = query_expression.toLowerCase();
	}
	
	this.ev = null;
	this.pr = null;
	this.PS = new Array()
	this.PS.push({st: 1, se: 0});
	
	var result;
	var i;
	var opm = 0; // operator missing
	var cdb = "t"; // current database
	while ((result = lexer.exec(query_expression)) != null) {
		var sem = result[0]; // semantic value
		var sym = 0; // symbol value
		for (i in keyws) {
			if (sem == keyws[i]) {
				sym = codem[i];
				if (semvm[i])
					sem = semvm[i];
				break;
			}
		}

		// lexical preprocessor
		// 1) implicit db settings
		// 2) implicit operator '&'
		if (sym == 5) { // db change is stored but not passed
			cdb = sem;
			continue;
		}
		if (sym == 3) // operator
			opm = 0;
		if ((sym == 0 || sym == 1) && opm) { 
			if (this.SM(3, "&")) // insert missing '&'
				return;
			opm = 0;
		}
		if (sym == 0) { // condition
			if (sem.charAt(0) == '"' || sem.charAt(0) == "'")
				sem = sem.slice(1, sem.length - 1);
			if ("URI" != query_type) 
			{
				// remove trailing % or *
				if (sem.length > 1) {
					var lc = sem[sem.length - 1];
					if (lc == '%' || lc == '*')
						sem = sem.slice(0, -1);
				}
				sem = Escape.MyEscape(sem.toLowerCase());
			}
			sem = cdb + sem;
			opm = 1;
		}
		if (this.SM(sym, sem))
			return;
	}
	if (!this.SM(5, "$")) {
		this.ev = this.PS[1].se.ev;
		this.pr = this.PS[1].se.pr;
	}
//	alert(this.ev + "\n" + this.pr);
},

SM: function(sym, sem)
{
//	alert(sym + ", " + sem);
	while (1) {
		var sp = this.PS[this.PS.length - 1];
		var ptv = this.PT[sp.st][sym];
		if (ptv == 10) {
//			alert("accept");
			return false;
		}
		if (ptv == 0) {
//			alert("error");
			return true; // error
		}
		if (ptv > 0) { // shift
			this.PS.push({st: ptv, se: sem});
			return false;
		}
		if (ptv < 0) {
			var nsem;
			var p = this.PS.length;
			var p1 = this.PS[p - 1];
			var p2 = this.PS[p - 2];
			var p3 = this.PS[p - 3];
			switch (-ptv) {
				case 1: 
					nsem = { 
					ev: "{a:'s', d:'" + p1.se.charAt(0) + "', p:'" + p1.se.slice(1) + "'}", 
					pr: p1.se.slice(1) }; 
					break;
				case 2:	
					if (p1.se == "!") {
						nsem = { ev: "{a:'s', d:'" + p2.se.charAt(0) + "', p:'" + p2.se.slice(1) + "', m:'" + p1.se + "'}" };
					} else {
						var ss = p2.se.slice(1, parseInt(p1.se) + 1) + "$002A";
						nsem = {
						ev: "{a:'s', d:'" + p2.se.charAt(0) + "', p:'" + p2.se.slice(1) +
						"'}, {a:'s', d:'" + p2.se.charAt(0) + "', p:'" + ss + 
						"'}, {a:'o', p:'|'}" };
					}
					nsem.pr = p2.se.slice(1);
					break;
				case 3: nsem = {
					ev: p3.se.ev + ", " + p1.se.ev + ", {a:'o', p:'" + p2.se + "'}",
					pr: p3.se.pr + (p2.se == "|" ? " or " : " ") + p1.se.pr };
					break;
				case 4: nsem = {
					ev: p2.se.ev,
					pr: "(" + p2.se.pr + ")" };	
					ptv = -3;
					break;
			}
			if (ptv == -1 || ptv == -2) {
				nsem.pr = decodeURIComponent(nsem.pr);
				if (nsem.pr.search(/\s/) != -1)
					nsem.pr = '"' + nsem.pr + '"';
			}
			this.PS.length += ptv;
			this.PS.push({st: this.PT[this.PS[this.PS.length - 1].st][6], se: nsem});
		}
	}
},

o: function(op, op1, op2)
{
	debug.insertAdjacentHTML("beforeEnd", "<div>" + op + ", " + op1 + ", " + op2 + "</div>");
	return op1 + op + op2;
},

e: function(db, se, st)
{
	if (!st)
		st = "";
	se = decodeURIComponent(se);
	debug.insertAdjacentHTML("beforeEnd", "<div>" + db + ", " + se + ", " + st + "</div>");
	
	return db + "=" + se + st;
}
};

var QueryProcessor = {
	rr: null,
Start: function(q, r)
{
	this.rr = r;
	eval("this.qa = [" + q + "]");
	this.qp = 0;
	this.Eval();
},

Eval: function()
{
	var n = this.qa[this.qp];
	if (n.a == "s") {
		var m = n.d == "t" ? false : true;
		if (n.m == "!")
			m = !m;
		SearchDBs[n.d].Search(decodeURIComponent(n.p), m);
	} else if (n.a == "o") {
		if (n.p == "&")
			this.qa[this.qp - 2].And(this.qa[this.qp - 1]);
		else
			this.qa[this.qp - 2].Or(this.qa[this.qp - 1]);
		this.qp -= 2;
		this.qa.splice(this.qp + 1, 2);
		this.Next();
	}
},

Next: function()
{
	if (this.qa.length == 1) {
		this.rr(this.qa[0].rs);
		return;
	}
	this.qp++;
	this.Eval();
},

ReportResult: function(r)
{
	this.qa[this.qp] = r;
	this.Next();
}
};

function ReadBase64_6(i)
{
	if (i == 43)
		return 62;
	if (i == 45)
		return 63;
	if (i < 58)
		return i - 48;
	if (i < 91)
		return i - 55;
	else
		return i - 61;
}

function ReadBase64_32(s)
{
	var i, j;
	j = 0;
	i = 0x20;
	while (i & 0x20) {
		i = ReadBase64_6(s.s.charCodeAt(s.p));
		j <<= 5;
		j |= (i & 0x1f);
		s.p++;
	}
	return j;
}

function ReadBase64_ITP(s, ctr)
{
	var r = new Array();
	var c, n, l = 0;
	while (s.p < s.s.length) {
		n = ReadBase64_32(s);
		c = 1 == n ? ReadBase64_32(s) : 1;
		while (c) {
			l += n;
			r.push(new ctr(l));
			c--;
		}
	}
	return r;
}

function SearchDB(dbid)
{
	this.db_id = dbid;
	this.ResetIndex();
	this.request_total = 0;
	this.request_count = 0;
}

SearchDB.prototype.ResetIndex = function()
{
	this.index = new Array();
	this.index.push({ key: null, node: "1" });
}

SearchDB.prototype.k = function(args)
{
	var prev = "";
	for (var i = 0; i < args.length; i++) {
		var s = { s: args[i], p: 0 };
		var l;
		var w = "";
		l = ReadBase64_32(s);
		var nk;
		nk = i == args.length - 1 ? this.index[this.index_insert_position]: new Object;
		nk.node = l > 0 ? s.s.slice(s.p, s.p + l): 0;
		s.p += l;
		l = ReadBase64_32(s);
		w += prev.slice(0, l);
		l = ReadBase64_32(s);
		w += s.s.slice(s.p, s.p + l);
		s.p += l;
		if (w.length > 0) {
			nk.key = w;
		}
		prev = w;
		while (s.p < s.s.length) {
			nk.values = new Array();
			l = ReadBase64_32(s);
			nk.values.push(s.s.slice(s.p, s.p + l));
			s.p += l;
		}
		if (i < args.length - 1) {
			this.index.splice(this.index_insert_position, 0, nk);
			this.index_insert_position++;
		}
	}
	this.d();
}

SearchDB.prototype.LoadScript = function(f)
{
	CDB=this;
	var dbPath = ConvertDbSelector[this.db_id];
//	setTimeout("jsdbfile.src='" + datasourceroot + dbPath + "/" + f + ".js'", 1);
	var s="SearchDBs."+this.db_id+".LoadScript_Callback";
	LoadXMLDocArray(datasourceroot+dbPath+"/"+f+".xml",s,"","N");
	this.request_total++;
	this.request_count++;
}

SearchDB.prototype.LoadScript_Callback = function(a)
{
	CDB=this;
	CDB.k(a);	
}

SearchDB.prototype.Search = function(s, m)
{
	this.RequestCount = 0;
	this.search = s;
	this.exact_match = m;
	this.results = new SearchResultSet();
	if (this.search.length == 0)
		return;
	this.index_match = 0;
	this.d = this.d1;
	this.d();
}

SearchDB.prototype.IndexSearch = function()
{
	var i;
	for (i = this.index_match; i < this.index.length; i++)
		if (null == this.index[i].key || this.search <= this.index[i].key)
			break;

	this.index_match = i;
}

SearchDB.prototype.d1 = function()
{
	this.IndexSearch();
	if (null != this.index[this.index_match].key && this.search == this.index[this.index_match].key) {
		if (!this.exact_match && this.index[this.index_match].values.length < 2) {
			this.d = this.d2;
			this.d();
		} else {
			var v = this.index[this.index_match].values;
			for (var j in v) {
				this.results.Or(new SearchResultSet(v[j]));
				if (this.exact_match)
					break;
			}			
			QueryProcessor.ReportResult(this.results);
		}
	} else {
		if (this.index[this.index_match].node != 0) {
			this.index_insert_position = this.index_match;
			this.LoadScript(this.index[this.index_match].node);
		} else {
			if (!this.exact_match) {
				this.d = this.d2;
				this.d();
			}
			else {
				QueryProcessor.ReportResult(this.results);
			}
		}
	}
}

SearchDB.prototype.d2 = function()
{
	if (null == this.index[this.index_match].key || (this.index[this.index_match].key.substring(0, this.search.length) != this.search && this.index[this.index_match].node == 0)) {
		QueryProcessor.ReportResult(this.results);
		return;
	}
	if (this.index[this.index_match].node == 0) {
		this.results.Or(new SearchResultSet(this.index[this.index_match].values[0]));
		this.index_match++;
		this.d2();
	} else {
		this.index_insert_position = this.index_match;
		this.LoadScript(this.index[this.index_match].node);
	} 
}

SearchDBs = { t: new SearchDB("t"), u: new SearchDB("u"), e: new SearchDB("e"), r: new SearchDB("r"), g: new SearchDB("g") };
CDB = null;

function SearchResult(index)
{
    this.index = index;
    this.weight = 1.0;
}

function SearchResultSet(s)
{
	if (s) {
		var ss = { s: s, p: 0 };
		this.rs = ReadBase64_ITP(ss, SearchResult);
	} else
		this.rs = new Array();
}

SearchResultSet.prototype.Or = function(srs)
{
    this.AOR(srs, true);
}

SearchResultSet.prototype.AOR = function(srs, or, weight)
{
	var i, j;
	for (i = 0, j = 0; i < srs.rs.length; i++) {
		while (j < this.rs.length && this.rs[j].index < srs.rs[i].index)
			j++;
		if (j == this.rs.length || this.rs[j].index != srs.rs[i].index)
			this.rs.splice(j, 0, srs.rs[i]);
		else {
		    var w1 = this.rs[j].weight;
		    var w2 = srs.rs[i].weight;
            this.rs[j].weight = or ? Math.max(w1, w2) : w1 + w2 * weight;
		}
	}
}

SearchResultSet.prototype.And = function(srs)
{
	var i, j;
	for (i = 0, j = 0; i < srs.rs.length && j < this.rs.length; i++) {
		while (j < this.rs.length && this.rs[j].index < srs.rs[i].index)
			this.rs.splice(j, 1);
		if (j < this.rs.length && srs.rs[i].index == this.rs[j].index) {
		    var w1 = this.rs[j].weight;
		    var w2 = srs.rs[i].weight;
	        this.rs[j].weight = Math.min(w1, w2);
			j++;
	    }
	}
	this.rs.splice(j, this.rs.length - j);
}

/* preferences.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

function UserPreferences() {
    this.EnablePreferences = true;
    this.TimeStamp = "000000000000";
    this.PlayAudio = "all";
    this.ShowLeadIn = "all";
    this.MarqueeColor = "red";
    this.TryIt = new Object;
    this.TryIt.EnableSkipping = true;
    this.DoIt = new Object
    this.DoIt.HotKey = new Object;
    this.DoIt.HotKey.Ctrl = "L";
    this.DoIt.HotKey.Shift = "N";
    this.DoIt.HotKey.Alt = "L";
    this.DefaultPlayMode = "S";
    this.WebPageAutoPlayback = true;
    this.NavbarVolume = 100;
}

UserPreferences.prototype.Copy = function (src) {
    this.TimeStamp = src.TimeStamp;
    this.PlayAudio = src.PlayAudio;
    this.ShowLeadIn = src.ShowLeadIn;
    this.MarqueeColor = src.MarqueeColor;
    this.TryIt.EnableSkipping = src.TryIt.EnableSkipping;
    this.DoIt.HotKey.Ctrl = src.DoIt.HotKey.Ctrl;
    this.DoIt.HotKey.Shift = src.DoIt.HotKey.Shift;
    this.DoIt.HotKey.Alt = src.DoIt.HotKey.Alt;
    this.DefaultPlayMode = src.DefaultPlayMode;
    this.WebPageAutoPlayback = src.WebPageAutoPlayback;
    this.NavbarVolume = src.NavbarVolume;
}

UserPreferences.prototype.Compare = function (src) {
    if (this.PlayAudio != src.PlayAudio) return true;
    if (this.ShowLeadIn != src.ShowLeadIn) return true;
    if (this.MarqueeColor != src.MarqueeColor) return true;
    if (this.TryIt.EnableSkipping != src.TryIt.EnableSkipping) return true;
    if (this.DoIt.HotKey.Ctrl != src.DoIt.HotKey.Ctrl) return true;
    if (this.DoIt.HotKey.Shift != src.DoIt.HotKey.Shift) return true;
    if (this.DoIt.HotKey.Alt != src.DoIt.HotKey.Alt) return true;
    if (this.DefaultPlayMode != src.DefaultPlayMode) return true;
    if (this.WebPageAutoPlayback != src.WebPageAutoPlayback) return true;
    if (this.NavbarVolume != src.NavbarVolume) return true;
    return false;
}

UserPreferences.prototype.GetCookie = function () {
    return new Cookie(document, "OnDemandPlayer", 365, "/");
}

UserPreferences.prototype.LoadCookie = function () {
    var cookie = this.GetCookie();
    cookie.Load();
    //    if (IsTouchDevice())
    //        this.PlayAudio = "none";

    if (UserPrefs.TimeStamp != "000000000000" && (!cookie.TimeStamp || UserPrefs.TimeStamp > cookie.TimeStamp))
        return;

    if (cookie.PlayAudio)
        this.PlayAudio = cookie.PlayAudio;
    if (cookie.ShowLeadIn)
        this.ShowLeadIn = cookie.ShowLeadIn;
    if (cookie.MarqueeColor)
        this.MarqueeColor = cookie.MarqueeColor;
    if (cookie.TryIt_EnableSkipping)
        this.TryIt.EnableSkipping = (cookie.TryIt_EnableSkipping == "true");
    if (cookie.DoIt_HotKey_Ctrl)
        this.DoIt.HotKey.Ctrl = cookie.DoIt_HotKey_Ctrl;
    if (cookie.DoIt_HotKey_Shift)
        this.DoIt.HotKey.Shift = cookie.DoIt_HotKey_Shift;
    if (cookie.DoIt_HotKey_Alt)
        this.DoIt.HotKey.Alt = cookie.DoIt_HotKey_Alt;
    if (cookie.DefaultPlayMode)
        this.DefaultPlayMode = cookie.DefaultPlayMode;
    if (cookie.WebPageAutoPlayback)
        this.WebPageAutoPlayback = cookie.WebPageAutoPlayback;
    if (cookie.NavbarVolume)
        this.NavbarVolume = cookie.NavbarVolume;
}

UserPreferences.prototype.StoreCookie = function () {
    var cookie = this.GetCookie();
    cookie.TimeStamp = this.TimeStamp;
    cookie.PlayAudio = this.PlayAudio;
    cookie.ShowLeadIn = this.ShowLeadIn;
    cookie.MarqueeColor = this.MarqueeColor;
    cookie.TryIt_EnableSkipping = this.TryIt.EnableSkipping;
    cookie.DoIt_HotKey_Ctrl = this.DoIt.HotKey.Ctrl;
    cookie.DoIt_HotKey_Shift = this.DoIt.HotKey.Shift;
    cookie.DoIt_HotKey_Alt = this.DoIt.HotKey.Alt;
    cookie.DefaultPlayMode = this.DefaultPlayMode;
    cookie.WebPageAutoPlayback = this.WebPageAutoPlayback;
    cookie.NavbarVolume = this.NavbarVolume;
    cookie.Store();
}

UserPreferences.prototype.GetUrlParamString = function () {
    return "PP_SOUND=" + this.PlayAudio +
		"&PP_LEADIN=" + this.ShowLeadIn +
		"&PP_SKIP=" + (this.TryIt.EnableSkipping ? "true" : "false") +
		"&PP_MARQUEE=" + this.MarqueeColor +
		"&PP_ENABLE=" + (this.EnablePreferences ? "true" : "false") +
		"&PP_HOTKEY=" + this.DoIt.HotKey.Ctrl + this.DoIt.HotKey.Shift + this.DoIt.HotKey.Alt;
}

UserPreferences.prototype.ParseUrlParamString = function (param_str) {
    var params = param_str.split('&');
    for (var p = 0; p < params.length; p++) {
        var paritem = params[p].split("=");
        if (paritem[0].toUpperCase() == "PP_SOUND")
            this.PlayAudio = paritem[1];
        else if (paritem[0].toUpperCase() == "PP_LEADIN")
            this.ShowLeadIn = paritem[1];
        else if (paritem[0].toUpperCase() == "PP_MARQUEE")
            this.MarqueeColor = paritem[1];
        else if (paritem[0].toUpperCase() == "PP_SKIP")
            this.TryIt.EnableSkipping = (paritem[1] == "true");
        else if (paritem[0].toUpperCase() == "PP_ENABLE")
            this.EnablePreferences = (paritem[1] == "true");
        else if (paritem[0].toUpperCase() == "PP_HOTKEY") {
            this.DoIt.HotKey.Ctrl = paritem[1].charAt(0);
            this.DoIt.HotKey.Shift = paritem[1].charAt(1);
            this.DoIt.HotKey.Alt = paritem[1].charAt(2);
        }
    }
}

var UserPrefs = new UserPreferences();

if (window.SetDefaultPreferences)
    SetDefaultPreferences();
if (UserPrefs.EnablePreferences)
    UserPrefs.LoadCookie();

var paramstr = unescape(document.location.hash.substring(1));
if (paramstr == "")
    paramstr = unescape(document.location.search.substring(1));

if (UserPrefs.EnablePreferences)
    UserPrefs.LoadCookie();

UserPrefs.ParseUrlParamString(paramstr);

function OpenPreferencesDialog(path, nosound, seeitonly) {
    if (!UserPrefs.EnablePreferences)
        alert(R_preferences_disabled);
    else {
        var p = path + "/preferences/preferences.html";
        h = 412;
        var params = new Array();
        try {
            if (lms_IsUserProfileAvailable()) {
                var url = lms_GetUserProfileUrl();
                if (url != "")
                    params[params.length] = "UserProfileUrl=" + Escape.MyEscape(url);
            }
        }
        catch (e) { };
        if (nosound) {
            params[params.length] = "nosound";
        }
        if (seeitonly) {
            params[params.length] = "seeitonly";
            h = 412;
        }
        for (var i = 0; i < params.length; i++) {
            p += (i == 0) ? "?" : "&";
            p += params[i];
        }
        window.open(p, "prefwin", "width=550,height=" + h + ",resizable=1,scrollbars=0,top=" + (screen.availHeight - 290) / 2 + ",left=" + (screen.availWidth - 550) / 2);
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////

function SessionPreferences() {
    this.swipeInstructionShowed = false;
}

SessionPreferences.prototype.GetCookie = function () {
    return new Cookie(document, "OnDemandPlayerSession", null, "/");
}

SessionPreferences.prototype.LoadCookie = function () {
    var cookie = this.GetCookie();
    cookie.Load();
    if (cookie.swipeInstructionShowed)
        this.swipeInstructionShowed = cookie.swipeInstructionShowed;
}

SessionPreferences.prototype.StoreCookie = function () {
    var cookie = this.GetCookie();
    cookie.swipeInstructionShowed = this.swipeInstructionShowed;
    cookie.Store();
}

var SessionPrefs = new SessionPreferences();

///////////////////////////////////////////////////////////////////////////////////////////////

function UserRolesClass() {
    this.Filtering = false;
    this.Roles = new Array;
}

UserRolesClass.prototype.Copy = function (src) {
    this.Filtering = src.Filtering;
    this.Roles = new Array;
    for (var r = 0; r < src.Roles.length; r++)
        this.Roles[r] = src.Roles[r];
}

UserRolesClass.prototype.Compare = function (src) {
    if (this.Filtering != src.Filtering) return true;
    if (this.Roles.length != src.Roles.length) return true;
    for (var r = 0; r < this.Roles.length; r++) {
        if (this.Roles[r] != src.Roles[r]) return true;
    }
    return false;
}

UserRolesClass.prototype.GetCookie = function () {
    return new Cookie(document, "OnDemandPlayerRoles", 365, "/");
}

UserRolesClass.prototype.LoadCookie = function () {
    var cookie = this.GetCookie();
    cookie.Load();
    this.Filtering = false;
    if (cookie.Filtering)
        this.Filtering = (cookie.Filtering == "true");
    this.Roles = new Array();
    if (cookie.Roles)
        this.Roles = cookie.Roles.split("+");
}

UserRolesClass.prototype.StoreCookie = function () {
    var cookie = this.GetCookie();
    cookie.Filtering = this.Filtering ? "true" : "false";
    cookie.Roles = this.Roles.join("+");
    cookie.Store();
}

UserRolesClass.prototype.GetUrlParamString = function () {
    return "PP_ROLEFILTERING=" + (this.Filtering ? "true" : "false") + "&PP_ROLES=" + encodeURIComponent(this.Roles.join('+'));
}

UserRolesClass.prototype.ParseUrlParamString = function (param_str) {
    var params = param_str.split('&');
    for (var p = 0; p < params.length; p++) {
        var paritem = params[p].split("=");
        if (paritem[0].toUpperCase() == "PP_ROLEFILTERING")
            this.Filtering = (paritem[1] == "true");
        else if (paritem[0].toUpperCase() == "PP_ROLES") {
            this.Roles = new Array;
            if (paritem[1])
                this.Roles = paritem[1].split('+');
        }
    }
}

var UserRoles = new UserRolesClass();
UserRoles.LoadCookie();
UserRoles.ParseUrlParamString(paramstr);

function OpenRolesDialog(path) {
    window.open(path + "/preferences/roles.html", "roleswin", "width=500,height=318,resizable=1,scrollbars=0,top=" + (screen.availHeight - 286) / 2 + ",left=" + (screen.availWidth - 500) / 2);
}
/* tree.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

// common variables

var treeControlDB = false;
var bigsco = false;

function ModeDesc(k) {
    this.treeCreated = false;
    this.lastSelected = null;
    this.filteredGuids = new Array();
    this.filteredGuidList = new Array();
    this.filteredTopicCount = 0;
    this.guidsForFlat = new Array();
    this.lastSelectedFlat = null;
    this.flatMode = false;
    this.modeLetter = k;
    this.treeControl = null;
    this.flatControl = null;
}

var modeDescA = new ModeDesc("A");
var modeDescF = new ModeDesc("F");
var modeDescH = new ModeDesc("H");
var modeDescFH = new ModeDesc("X");

var treeViewMode = "ALL"; 			// view mode ("ALL" or "FILTERED" or "HEMI" or "FILTEREDHEMI")
var treeIsEmpty;
var _rootData = "";

function GetJunctionId(s) {
    k = s.indexOf('_');
    kk = s.indexOf('_', k + 1)
    ss = s.substr(0, kk);
    return ss;
}

////////////////////////////////////
// filtering support

var filteredGuidsR = new Array(); // associative array contains all guid to show
var filteredTopicCountR = 0; 	// number of filtered topics (ROLES)
var rolefilter_enabled = false;

var selection_need = 0;
var stl_mode = "ALL";
var stl_callback = "";
var stl_myTopicArray = new Array();
var stl_myscoresArray = new Array();
var stl_i = 0;
var stl_topicMapId = -1;
var stl_newtMap = false;
var stl_topicMapPageLen = -1;
var global_topicMap = new Array();
var seeAlsoSelection = 0;

var _lastChangeIsFilterOnly = false;

function SetTopicList(mode, topicarray, callbackfn) {
    stl_mode = mode;
    stl_callback = callbackfn;
    _lastChangeIsFilterOnly = false;
    if (mode == "FILTERED") {
        modeDescF.filteredGuids = new Array();
        modeDescF.filteredGuidList = new Array();
        modeDescF.filteredTopicCount = topicarray.length;
        modeDescF.guidsForFlat = new Array();
        modeDescF.flatMode = true;
    }
    else if (mode == "HEMI") {
        modeDescH.filteredGuids = new Array();
        modeDescH.filteredGuidList = new Array();
        modeDescH.filteredTopicCount = topicarray.length;
        modeDescH.guidsForFlat = new Array();
        modeDescH.flatMode = true;
    }
    else if (mode == "ROLES") {
        filteredGuidsR = new Array();
        filteredTopicCountR = topicarray.length;
        rolefilter_enabled = true;
        _lastChangeIsFilterOnly = true;
    }
    else	// "NOROLES"
    {
        rolefilter_enabled = false;
        _lastChangeIsFilterOnly = true;
        eval(stl_callback + "()");
        return;
    }
    stl_myTopicArray = new Array();
    stl_myTopicArray = topicarray;
    stl_myscoresArray = new Array();
    if (topicarray.length > 0) {
        try {
            var a = topicarray[0].index;
            if (a) {
                stl_myTopicArray = new Array();
                for (var i = 0; i < topicarray.length; i++) {
                    stl_myTopicArray[stl_myTopicArray.length] = topicarray[i].index;
                    stl_myscoresArray[topicarray[i].index] = topicarray[i].score;
                }
            }
        }
        catch (e) {
        }
    }
    stl_i = 0;
    if (stl_topicMapPageLen == -1)
        SetTopicList_LoadPageLen();
    else
        SetTopicList_Next();
}

function SetTopicList_LoadPageLen() {
    LoadXMLDocArray("../querydb/topicmap/0.xml", "SetTopicList_LoadPageLen_Return", "", "T");
}

function SetTopicList_LoadPageLen_Return(retArray) {
    stl_topicMapPageLen = parseInt(retArray[0]);
    SetTopicList_Next();
}

function SetTopicList_Next() {
    fTC = modeDescF.filteredTopicCount;
    if (stl_mode == "HEMI")
        fTC = modeDescH.filteredTopicCount;
    if (stl_mode == "ROLES")
        fTC = filteredTopicCountR;
    if (!(stl_i < fTC)) {
        eval(stl_callback + "()");
        return;
    }
    j = stl_myTopicArray[stl_i];
    a = Math.floor((j - 1) / stl_topicMapPageLen);
    if (!global_topicMap["" + a]) {
        stl_topicMapId = a;
        stl_newtMap = true;
        LoadXMLDocArray("../querydb/topicmap/" + a + ".xml", "SetTopicList_Next2", "", "T");
    }
    else {
        stl_topicMapId = a;
        stl_newtMap = false;
        setTimeout("SetTopicList_Next2()", 1);
    }
}

function DecodeTMapArray(tmapArray) {
    var newArray = new Array();
    var fullstr = "";
    for (var i = 0; i < tmapArray.length; i++) {
        if (i == 0) {
            newArray[newArray.length] = tmapArray[i];
        }
        else {
            var s = { s: tmapArray[i], p: 0 };
            l = ReadBase64_32(s);
            str = fullstr.substr(0, l) + s.s.substr(s.p, s.s.length);
            fullstr = str;
            newArray[newArray.length] = str;
        }
    }
    return newArray;
}

function ItemDesc(type, title, empty) {
    this.type = type;
    this.title = title;
    this.empty = empty;
    this.found = false;
    this.parentguid = null;
    this.openable = new Array();
    this.treeitemdiv = null;
}

function AddItemdesc(o, array, ss, type, title, empty, found, topicguid, parentguid) {
    l = false;
    try {
        l = array[ss].title.length > 0;
    }
    catch (e) { };
    if (!l) {
        array[ss] = new ItemDesc(type, title, empty);
        if (o)
            o.filteredGuidList[o.filteredGuidList.length] = ss;
        AddToIndexMap(ss);
    }
    array[ss].parentguid = parentguid;
    if (found == true)
        array[ss].found = true;
    if (topicguid.length > 0)
        array[ss].openable[array[ss].openable.length] = topicguid;
}

function AddTreeItemToItemDesc(guid, itemdiv) {
    md = getModeDesc();
    try {
        if (treeViewMode == "FILTEREDHEMI") {
            if (!md.filteredGuids)
                md.filteredGuids = new Array();
            if (!md.filteredGuids[guid]) {
                md.filteredGuids[guid] = new ItemDesc("", "", false);
                md.filteredGuidList[md.filteredGuidList.length] = guid;
            }
            AddToIndexMap(guid);
        }
        md.filteredGuids[guid].treeitemdiv = itemdiv;
    }
    catch (e) { };
    saveModeDesc(md);
}

function GetTreeItemOfItemDesc(guid) {
    md = getModeDesc();
    var _item = null;
    try {
        _item = md.filteredGuids[guid].treeitemdiv;
    }
    catch (e) { };
    return _item;
}

function FlatItemDesc(type, title, empty, guid, isroot, score) {
    this.type = type;
    this.title = title;
    this.empty = empty;
    this.guid = guid;
    this.isroot = isroot;
    if (!score)
        score = 0;
    this.score = score;
}

function AddFlatItemdesc(array, guid, type, title, empty, isroot, score) {
    for (var i = 0; i < array.length; i++) {
        if (array[i].guid == guid)
            return;
        if (array[i].guid.substr(0, 36) == guid.substr(0, 36))
            return;
    }
    array[array.length] = new FlatItemDesc(type, title, empty, guid, isroot, score);
}

// IAS HOOK !!!
var foundApplicableList = new Array();
var foundApplicableTable = new Array();

function SetTopicList_Next2(tmapArray) {
    if (stl_newtMap) {
        global_topicMap["" + stl_topicMapId] = DecodeTMapArray(tmapArray);
    }
    j = stl_myTopicArray[stl_i];
    a = Math.floor((j - 1) / stl_topicMapPageLen);
    s = global_topicMap["" + stl_topicMapId][j - (a * stl_topicMapPageLen)];
    k = s.indexOf('#');
    s1 = s.substr(0, k);
    _tguid = s1;
    kk = s1.lastIndexOf('/')
    if (kk > 0)
        _tguid = s1.substr(kk + 1);

    var _isroot = (kk < 0);
    var _concept = (s.substr(k + 1, 1) == 'C');
    var _empty = (s.substr(k + 2, 1) == 'E');

    var rbs = { s: s.substr(k + 3), p: 0 };
    l = ReadBase64_32(rbs);
    s2 = rbs.s.substr(rbs.p + l);
    title = rbs.s.substr(rbs.p, l);
    type = s2;
    k = s2.indexOf('#');
    if (k >= 0) {
        type = s2.substr(0, k);
        s4 = s2.substr(k);
        s2 = s4;
    }
    else {
        s2 = "";
    }
    s = s1 + s2;
    k = s.indexOf('/');
    var _pguid = null;

    if (type == 'Topic' || _concept == true) {
        while (k >= 0) {
            ss = "" + s.substr(0, k);

            // IAS HOOK !!!
            if (parent.TocFirstCall) {
                var g = _tguid.substr(0, 36);
                if (foundApplicableTable[g] != true) {
                    foundApplicableTable[g] = true;
                    foundApplicableList.push(g);
                }
            }

            if (stl_mode == "FILTERED") {
                //  			filteredGuidsF[ss]=itemdesc;
                //  			filteredGuidsF[ss.substr(0,36)]=itemdesc;
                AddItemdesc(modeDescF, modeDescF.filteredGuids, ss, type, title, _empty, false, _tguid, _pguid);
                AddItemdesc(modeDescF, modeDescF.filteredGuids, ss.substr(0, 36), type, title, _empty, false, _tguid, _pguid);
            }
            else if (stl_mode == "HEMI") {
                //  			filteredGuidsH[ss]=itemdesc;
                AddItemdesc(modeDescH, modeDescH.filteredGuids, ss, type, title, _empty, false, _tguid, _pguid);
                AddItemdesc(modeDescH, modeDescH.filteredGuids, ss.substr(0, 36), type, title, _empty, false, _tguid, _pguid);
            }
            else	// "ROLES"
            {
                //  			filteredGuidsR[ss]=itemdesc;
                AddItemdesc(null, filteredGuidsR, ss, type, title, _empty, false, _tguid, null);
                AddItemdesc(null, filteredGuidsR, ss.substr(0, 36), type, title, _empty, false, _tguid, null);
            }
            _pguid = ss;
            ss = s.substr(k + 1);
            s = ss;
            k = s.indexOf('/');
        }
        if (s.length > 0) {
            ss = s;
            k = s.indexOf('#');
            if (k > 0)
                ss = s.substr(0, k);
            if (stl_mode == "FILTERED") {
                //  			filteredGuidsF[ss]=itemdesc;
                AddItemdesc(modeDescF, modeDescF.filteredGuids, ss, type, title, _empty, true, "", _pguid);
                AddFlatItemdesc(modeDescF.guidsForFlat, ss, type, title, _empty, _isroot);
            }
            else if (stl_mode == "HEMI") {
                //  			filteredGuidsH[ss]=itemdesc;
                AddItemdesc(modeDescH, modeDescH.filteredGuids, ss, type, title, _empty, true, "", _pguid);
                _score = stl_myscoresArray[stl_myTopicArray[stl_i]];
                AddFlatItemdesc(modeDescH.guidsForFlat, ss, type, title, _empty, _isroot, _score);
            }
            else {
                //  			filteredGuidsR[ss]=itemdesc;
                AddItemdesc(null, filteredGuidsR, ss, type, title, _empty, true, "", null);
                AddItemdesc(null, filteredGuidsR, ss.substr(0, 36), type, title, _empty, true, "", null);
            }
        }
    }
    stl_i++;
    SetTopicList_Next();
}

//////////////////////////////////////////////////////////////////////////////

function TreeViewModeLetter() {
    if (treeViewMode == "FILTEREDHEMI")
        return "X";
    return treeViewMode.substr(0, 1);
}

function IsFiltered(guid, tMode) // true if the guid must be show
{
    var k;
    l = 0;
    try {
        l = filteredGuidsR[guid].title.length;
    }
    catch (e) { };

    roles = 0; //not enabled
    if (rolefilter_enabled) {
        roles = (l > 0 ? 1 : 2); // 1 -> found, 2 -> not found
    }

    if (tMode == "ALL") {
        if (roles == 0) {
            treeIsEmpty = false;
            return true;
        }
        else if (roles == 1) {
            l = false;
            try {
                l = (filteredGuidsR[guid].openable.length > 0 || filteredGuidsR[guid].found);
            }
            catch (e) { };
            if (l == true)
                treeIsEmpty = false;
            return l;
        }
        else {
            return false;
        }


    }
    else if (tMode == "FILTERED") {
        l = 0;
        try {
            l = modeDescF.filteredGuids[guid].title.length;
        }
        catch (e) { };
        if (l == 0)
            return false;

        if (roles == 0) {
            treeIsEmpty = false;
            return true;
        }
        else if (roles == 1) {
            l = false;
            try {
                l = Cut(modeDescF.filteredGuids[guid].openable, filteredGuidsR[guid].openable) ||
							(modeDescF.filteredGuids[guid].found && filteredGuidsR[guid].found);
            }
            catch (e) { };
            if (l == true)
                treeIsEmpty = false;
            return l;
        }
        else {
            return false;
        }
    }
    else if (tMode == "HEMI") {
        l = 0;
        try {
            l = modeDescH.filteredGuids[guid].title.length;
        }
        catch (e) { };
        if (l == 0)
            return false;

        if (roles == 0) {
            treeIsEmpty = false;
            return true;
        }
        else if (roles == 1) {
            l = false;
            try {
                l = Cut(modeDescH.filteredGuids[guid].openable, filteredGuidsR[guid].openable) ||
							(modeDescH.filteredGuids[guid].found && filteredGuidsR[guid].found);
            }
            catch (e) { };
            if (l == true)
                treeIsEmpty = false;
            return l;
        }
        else {
            return false;
        }
    }
    else	// FILTEREDHEMI
    {
        if (roles == 0) {
            l = false;
            try {
                l = Cut(modeDescF.filteredGuids[guid].openable, modeDescH.filteredGuids[guid].openable) ||
							(modeDescF.filteredGuids[guid].found && modeDescH.filteredGuids[guid].found);
            }
            catch (e) { };
            if (l)
                treeIsEmpty = false;
            return l;
        }
        else if (roles == 1) {
            l = false;
            try {
                l = Cut3(modeDescF.filteredGuids[guid].openable, modeDescH.filteredGuids[guid].openable, filteredGuidsR[guid].openable) ||
							(modeDescF.filteredGuids[guid].found && modeDescH.filteredGuids[guid].found && filteredGuidsR[guid].found);
            }
            catch (e) { };
            if (l)
                treeIsEmpty = false;
            return l;

        }
        else {
            return false;
        }
    }
}

function Cut(array1, array2) {
    if (array2 == null) {
        return array1.length > 0;
    }
    for (var i = 0; i < array1.length; i++) {
        for (var j = 0; j < array2.length; j++) {
            if (array1[i] == array2[j])
                return true;
        }
    }
    return false;
}

function Cut3(array1, array2, array3) {
    if (array3 == null)
        return Cut(array1, array2);
    for (var i = 0; i < array1.length; i++) {
        for (var j = 0; j < array2.length; j++) {
            for (var k = 0; k < array3.length; k++) {
                if (array1[i] == array2[j] && array2[j] == array3[k])
                    return true;
            }
        }
    }
    return false;
}

function IsOpenable(guid) {
    var roleArray = null;
    if (rolefilter_enabled == true) {
        roleArray = filteredGuidsR[guid].openable;
    }

    if (treeViewMode == "ALL") {
        if (rolefilter_enabled) {
            l = false;
            try {
                l = roleArray.length > 0;
            } catch (e) { };
            return l;
        }
        return true;
    }
    else if (treeViewMode == "FILTERED") {
        l = true;
        try {
            l = Cut(modeDescF.filteredGuids[guid].openable, roleArray);
        }
        catch (e) { };
        return l;
    }
    else if (treeViewMode == "HEMI") {
        l = true;
        try {
            l = Cut(modeDescH.filteredGuids[guid].openable, roleArray);
        }
        catch (e) { };
        return l;
    }
    else		// FILTEREDHEMI
    {
        l = Cut3(modeDescF.filteredGuids[guid].openable, modeDescH.filteredGuids[guid].openable, roleArray);
        return l;
    }
}

function IsAutoExpand()	// true if the tree must be appear expanded
{
    if (treeViewMode == "ALL")
        return false;
    else if (treeViewMode == "FILTERED")
        return (modeDescF.filteredTopicCount < TreeConfig.AutoExpandLimit)
    else if (treeViewMode == "FILTEREDHEMI")
        return (modeDescF.filteredTopicCount < TreeConfig.AutoExpandLimit)
    else	//"HEMI"
        return (modeDescH.filteredTopicCount < TreeConfig.AutoExpandLimit)
}

////////////////////////////////////
// delayed tree load support

var treeLoadQueue = new Array();
var treeLoadQueueDivs = new Array();
var treeLoadQueuePtr = 0;

function Queue_Init()	// init queue internal variables
{
    treeLoadQueue = new Array();
    treeLoadQueueDivs = new Array();
    treeLoadQueuePtr = 0
}

function Queue_Add(s, div)	// add section html file to queue
{
    treeLoadQueue[treeLoadQueue.length] = s;
    treeLoadQueueDivs[treeLoadQueueDivs.length] = div;
}

function Queue_Next(t)	// load next section html file
{
    if (treeLoadQueuePtr < treeLoadQueue.length) {
        t.LoadScript(treeLoadQueue[treeLoadQueuePtr], treeLoadQueueDivs[treeLoadQueuePtr]);
        treeLoadQueuePtr++;
    }
    else if (_childItem_found) {
        _childItem_found = false;
        createTreeControl(null, false, null);
    }
    else {
        if (selection_need > 0) {
            var sel = false;
            if (_lastSelectedGlobal.length > 0) {
                if (rolefilter_enabled == true) {
                    l = 0;
                    try {
                        l = filteredGuidsR[_lastSelectedGlobal].title.length;
                    }
                    catch (e) { };
                    if (l > 0) {
                        sel = true;
                    }
                }
                else {
                    sel = true;
                }
            }

            if (sel == true) {
                selection_need = 0;
                if (ChangeTreeView_CallBack() == true)
                    return;
            }
            t.SelectFirstItem();
        }
        if (parent.TreeFinished) {
            parent.TreeFinished(treeViewMode, treeIsEmpty);
        }
        //		if (parent.selector.SearchEnable)
        //		{
        //			setTimeout("parent.selector.SearchEnable()",100);
        //		}
        //		else
        //		{
        //			setTimeout("parent.selector.SearchEnable()",500);
        //		}
    }
}

function SelectionCallBack(_item) {
    var t;
    md = getModeDesc();
    switch (treeViewMode) {
        case "ALL":
            if (_lastSelectedItem != null) {
                if (_lastSelectedItem.startAction == true) {
                    _lastSelectedItem.startAction = false;
                }
                else {
                    _lastSelectedItem.startAction = true;
                    ChangeTreeView_CallBack()
                    return;
                }
            }
            t = (_item == null ? md.lastSelected : _item);
            break;
        default:
            if (md.flatMode == true) {
                SetFlatSelection();
                return;
            }
            t = ((md.flatMode == true) ? md.lastSelectedFlat : (_item == null ? md.lastSelected : _item));
            break;
    }

    if (t == null) {
        if (parent.TreeItemSelected)
            parent.TreeItemSelected(null, null);
        return;
    };
    var tpc = t.getAttribute("tpc");
    if (tpc == null)
        tpc = t.parentNode.getAttribute("tpc");
    if (tpc == null)
        tpc = t.parentNode.parentNode.getAttribute("tpc");
    if (md.flatMode == false) {
        ChangeSelection(t);
        window.scrollTo(0, (t.parentNode.offsetTop / 2) + 10);
    }
    if (tpc != null)
        SetLastSelected(tpc, treeViewMode);
    if (parent.TreeItemSelected)
        parent.TreeItemSelected(tpc, treeViewMode);
}

function ClearDescriptor(md, fm) {
    md.treeCreated = true;
    md.lastSelected = null;
    md.lastSelectedFlat = null;
    //	if (_lastChangeIsFilterOnly==false)
    md.flatMode = fm;
    for (var i = 0; i < md.filteredGuidList.length; i++) {
        s = md.filteredGuidList[i];
        md.filteredGuids[s].treeitem = null;
        md.filteredGuids[s].treeitemdiv = null;
    }
}

function LastSelectedItem(guid, mode) {
    this.guid = guid;
    this.mode = mode;
    this.startAction = false;
    this.firsdBuild = false;
}

var _lastSelectedItem = null;
var _lastSelectedGlobal = "";
var _lastSelectedGlobalMode = "";

function SetLastSelected(guid, mode, force) {
    _lastSelectedGlobal = guid;
    _lastSelectedGlobalMode = mode;
    if (!force) {
        if (treeViewMode == "ALL")
            return;
    }
    _lastSelectedItem = new LastSelectedItem(guid, mode);
}

function GetTpcAttribute(obj) {
    var tpc = null;
    while (tpc == null) {
        try {
            tpc = obj.getAttribute("tpc");
        }
        catch (e) {
            return null;
        }
        if (tpc == null)
            obj = obj.parentNode;
    }
    return tpc;
}

var _childItem = null;
var _childItem_found = false;

function createTreeControl(rootData, flatmode, _item, selection, childitem) {
    if (rootData)
        _rootData = rootData;
    try {
        bigsco = parent.SCO_Supported();
    }
    catch (e) { }
    InitTocStates();
    if (selection)
        seeAlsoSelection = selection;
    if (childitem)
        _childItem = childitem;
    fm = (flatmode == true ? true : false);
    selection_need = 1;
    if (treeViewMode == "ALL") {
        if (modeDescA.treeCreated == true) {
            SelectionCallBack(_item);
            return;
        }
        ClearDescriptor(modeDescA, false);
        if (_lastSelectedItem != null) {
            _lastSelectedItem.startAction = true;
            _lastSelectedItem.firstBuild = true;
        }
        else {
            selection_need = 2;
        }
    }
    else if (treeViewMode == "FILTERED") {
        if (modeDescF.treeCreated == true) {
            //			if (fm==true && _lastChangeIsFilterOnly==false)
            //				modeDescF.flatMode=true;
            modeDescF.flatMode = fm;
            SelectionCallBack(_item);
            return;
        }
        ClearDescriptor(modeDescF, fm);
    }
    else if (treeViewMode == "FILTEREDHEMI") {
        if (modeDescFH.treeCreated == true) {
            //			if (fm==true && _lastChangeIsFilterOnly==false)
            //				modeDescFH.flatMode=true;
            modeDescFH.flatMode = fm;
            SelectionCallBack(_item);
            return;
        }
        ClearDescriptor(modeDescFH, fm);
    }
    else	//"HEMI"
    {
        if (modeDescH.treeCreated == true) {
            //			if (fm==true && _lastChangeIsFilterOnly==false)
            //				modeDescH.flatMode=true;
            modeDescH.flatMode = fm;
            SelectionCallBack(_item);
            return;
        }
        ClearDescriptor(modeDescH, fm);
    }
    treeIsEmpty = true;
    if (treeViewMode == "ALL")
        treeControl = new TreeControl(document.getElementById("treeControlHostForAll"), rootData);
    else if (treeViewMode == "FILTERED") {
        treeControl = new TreeControl(document.getElementById("treeControlHostForFiltered"), rootData);
        modeDescF.flatControl = new FlatControl("flatControlHostForFiltered");
        modeDescF.flatControl.Load();
        selection_need = (modeDescF.flatMode == true ? 0 : 1);
    }
    else if (treeViewMode == "FILTEREDHEMI") {
        treeControl = new TreeControl(document.getElementById("treeControlHostForFilteredHemi"), rootData);
        modeDescFH.flatControl = new FlatControl("flatControlHostForFilteredHemi");
        modeDescFH.flatControl.Load();
        selection_need = (modeDescFH.flatMode == true ? 0 : 1);
    }
    else	//"HEMI"
    {
        treeControl = new TreeControl(document.getElementById("treeControlHostForHemi"), rootData);
        modeDescH.flatControl = new FlatControl("flatControlHostForHemi");
        modeDescH.flatControl.Load();
        selection_need = (modeDescH.flatMode == true ? 0 : 1);
    }
    Queue_Init();

    treeControl.LoadScript(treeControl.rootData + ".html", treeControl.treeHost.id);
}

function TreeControl(host, rootData) {
    this.host = host;
    this.rootData = rootData;

    host.innerHTML = "";
    this.treeHost = document.createElement("div");
    this.treeHost.id = rootData + "_" + TreeViewModeLetter();
    this.treeHost.className = "treeControlNode";
    this.treeHost.onclick = this.OnClick;
    this.treeHost.onmouseup = this.OnMouseUp;
    this.treeHost.ondblclick = this.OnDoubleClick;
    this.host.appendChild(this.treeHost);

    if (treeViewMode == "ALL")
        this.loader = document.getElementById("treeControlDataForAll");
    else if (treeViewMode == "FILTERED")
        this.loader = document.getElementById("treeControlDataForFiltered");
    else if (treeViewMode == "FILTEREDHEMI")
        this.loader = document.getElementById("treeControlDataForFilteredHemi");
    else	//"HEMI"
        this.loader = document.getElementById("treeControlDataForHemi");
    this.loader.className = "treeControlData";

    /*var imagesToCache = new Array(
    "module_c.gif", "module_o.gif", "outl_f.gif", "outl_fc.gif", "outl_fo.gif", "outl_l.gif",
    "outl_lc.gif", "outl_lo.gif", "outl_m.gif", "outl_mc.gif", "outl_mo.gif", "outl_r.gif",
    "sco_empty.gif", "sco_completed.gif", "sco_incomplete.gif", "sco_failed.gif", "sco_notstarted.gif", "sco_passed.gif",
    "outl_rc.gif", "outl_ro.gif", "topic.gif", "question.gif", "assessment.gif", "vert_line.gif", "vert_line_wide.gif", "s.gif");

    this.imageCache = new Array();
    for (var i = 0; i < imagesToCache.length; i++) {
    this.imageCache[i] = new Image();
    this.imageCache[i].src = "../../img/" + imagesToCache[i];
    }*/
}

var _indexedSrc = "";

TreeControl.prototype.LoadScript = function (src, indexedSrc) {
    _indexedSrc = indexedSrc;
    setTimeout("treeControl.LoadScriptInternal('" + src + "')", 1);
}

TreeControl.prototype.LoadScriptInternal = function (src) {
    var l = this.loader;
    var d = (l.contentDocument ? l.contentDocument : (l.contentWindow ? l.contentWindow.document : null));
    if (!d)
        return;
    treeControlDB = true;
    d.location.replace(src);
}

TreeControl.prototype.Bind = function (data) {
    if (treeControlDB) {
        treeControlDB = false;
        this.TraverseChildren(data.c, document.getElementById(_indexedSrc));
        _childNode_Loaded();
    }
    if (directMode == true)
        ChangeTreeView_CallBack()
    else
        Queue_Next(this);
}

function UnescapeQuotes(s) {
    ss = s;
    k = ss.indexOf('&amp;');
    while (k >= 0) {
        sss = ss.substr(0, k) + "&" + ss.substr(k + 5);
        ss = sss;
        k = ss.indexOf('&amp;');
    }
    k = ss.indexOf('&gt;');
    while (k >= 0) {
        sss = ss.substr(0, k) + ">" + ss.substr(k + 4);
        ss = sss;
        k = ss.indexOf('&gt;');
    }
    k = ss.indexOf('&lt;');
    while (k >= 0) {
        sss = ss.substr(0, k) + "<" + ss.substr(k + 4);
        ss = sss;
        k = ss.indexOf('&lt;');
    }
    return ss;
}

function GetClassNameFromFile(filename) {

    var mytool_array = filename.split("/");
    cname = mytool_array[mytool_array.length - 1];
    return cname.replace(".gif", "");
}

TreeControl.prototype.TraverseNode = function (node, parentElement, image, last) {
    var e, f, g, hasChildren;
    var _empty = (node.e ? true : false);
    if (treeViewMode == "ALL") {
        var pGuid = parentElement.getAttribute("id");
        k = pGuid.lastIndexOf("_");
        pGuid = pGuid.substr(0, k);
        var iGuid = (node.d ? node.d : node.i);
        AddItemdesc(modeDescA, modeDescA.filteredGuids, iGuid, "", "-", _empty, false, "", pGuid);
        AddTreeItemToItemDesc(iGuid, true);
    }
    node.element = document.createElement("div");
    f = node.element;
    f.className = "treeControlNode";

    hasChildren = node.c || node.d;
    emptylesson = false;
    if (node.e)
        emptylesson = true;
    _openable = (node.d ? IsOpenable(node.d) : false)

    g = f.appendChild(document.createElement("div"));
    guid = (node.i ? node.i : node.d);
    g.setAttribute("tpc", guid);

    e = g.appendChild(document.createElement("img"));
    e.setAttribute("srcroot", "../../img/outl_" + image);
    if (emptylesson || (node.d && !_openable)) {
        esrc = e.getAttribute("srcroot") + ".gif";
        e.className = GetClassNameFromFile(esrc);
        e.openable = false;
        e.src = "../../img/empty.gif";
    }
    else {
        esrc = e.getAttribute("srcroot") + (hasChildren ? (IsAutoExpand() ? "o.gif" : "c.gif") : ".gif");
        e.className = GetClassNameFromFile(esrc);
        e.src = "../../img/empty.gif";
        e.openable = (hasChildren ? (IsAutoExpand() ? true : true) : false);
    }

    e = g.appendChild(document.createElement("img"));
    if (bigsco) {
        var stat = GetItemStatus(guid, true);
        e.className = _GetItemStatusFile(stat);
        e.src = "../../img/empty.gif";
        e.title = _GetItemStatusTitle(stat);
        e.alt = _GetItemStatusTitle(stat);
    }
    else {
        e.src = "../../img/sco_empty.gif";
    }

    e = g.appendChild(document.createElement("img"));

    if (emptylesson) {
        esrc = "../../img/emptysection.gif";
        e.className = GetClassNameFromFile(esrc);
        e.src = "../../img/empty.gif";

    }
    else {
        esrc = (hasChildren ? ((IsAutoExpand() && _openable) ? "../../img/module_o.gif" : "../../img/module_c.gif") :
							"../../img/topic.gif");
        e.src = "../../img/empty.gif";
        e.className = GetClassNameFromFile(esrc);

        if (node.q) {
            e.className = GetClassNameFromFile("../../img/question.gif");
        }
        if (node.a) {
            e.className = GetClassNameFromFile("../../img/assessment.gif");
        }

    }
    e = g.appendChild(document.createElement("span"));
    ee = e.appendChild(document.createElement("a"));
    ee.className = "";
    ee.style.cursor = "pointer";
    ee.onmouseover = this.OnOverItem;
    ee.onmouseout = this.OnOutItem;
    ee.appendChild(document.createTextNode(UnescapeQuotes(node.t)));
    AddTreeItemToItemDesc(guid, ee);

    parentElement.appendChild(f);

    if (hasChildren && _openable) {
        e = node.element.appendChild(document.createElement("table"));
        e.className = "treeControlChildren" + (!IsAutoExpand() ? "H" : "V");
        e.cellSpacing = 0;
        e = e.appendChild(document.createElement("tbody"));
        e = e.appendChild(document.createElement("tr"));
        f = e.appendChild(document.createElement("td"));
        f.className = "treeControlLine" + (last ? "H" : "V") + (bigsco ? "W" : "");
        f = f.appendChild(document.createElement("img"));
        f.src = "../../img/s.gif";

        f = e.appendChild(document.createElement("td"));
        if (node.c)
            this.TraverseChildren(node.c, f);
        if (node.d) {
            f.id = node.d + "_" + TreeViewModeLetter();
            return f.id;
        }
    }
    return null;
}

TreeControl.prototype.TraverseChildren = function (children, parentElement) {
    if (!children)
        return;

    var children2 = new Array();
    var childrendivs = new Array();

    for (var c = 0; c < children.length; c++) {
        var guid = (children[c].d ? children[c].d : children[c].i);
        if (IsFiltered(guid, treeViewMode))
            children2[children2.length] = children[c];
    }

    if (children2.length > 0) {
        if (parentElement.className == "treeControlNode") {
            if (children2.length == 1) {
                childrendivs[0] = this.TraverseNode(children2[0], parentElement, "r", true);
            }
            else {
                childrendivs[0] = this.TraverseNode(children2[0], parentElement, "f", false);
                var lasti = children2.length - 1;
                for (var i = 1; i < lasti; i++)
                    childrendivs[i] = this.TraverseNode(children2[i], parentElement, "m", false);
                childrendivs[lasti] = this.TraverseNode(children2[lasti], parentElement, "l", true);
            }
        }
        else {
            var lasti = children2.length - 1;
            for (var i = 0; i < lasti; i++)
                childrendivs[i] = this.TraverseNode(children2[i], parentElement, "m", false);
            childrendivs[lasti] = this.TraverseNode(children2[lasti], parentElement, "l", true);
        }
    }

    if (IsAutoExpand()) {
        for (var j = 0; j < children2.length; j++) {
            if (children2[j].d)
                Queue_Add(children2[j].d + ".html", childrendivs[j]);
        }
    }

    if (_childItem != null) {
        var maxindex = children2.length - 1;
        for (var j = 0; j < children2.length; j++) {
            var chindex = (children2[j].d ? children2[j].d.substr(37) : children2[j].i.substr(37));
            try {
                chindex = parseInt(chindex, 10);
            }
            catch (e) { };
            if (chindex > _childItem && j == 0) {
                _childItem = null;
                // FAILED
                break;
            }
            else if (chindex < _childItem && j == maxindex) {
                if (children2[j].d) {
                    Queue_Add(children2[j].d + ".html", childrendivs[j]);
                    break;
                }
                else {
                    _childItem = null;
                    // FAILED
                    break;
                }

            }
            else if (chindex == _childItem) {
                _childItem = null;
                _childItem_found = true;
                SetLastSelected(children2[j].d ? children2[j].d : children2[j].i, "ALL", true);
                // FOUND
                break;
            }
            else if (chindex > _childItem) {
                if (children2[j - 1].d) {
                    Queue_Add(children2[j - 1].d + ".html", childrendivs[j - 1]);
                    break;
                }
                else {
                    _childItem = null;
                    // FAILED
                    break;
                }
            }
        }
    }

}

TreeControl.prototype.OnOverItem = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    if (target.className == "tselected")
        return;
    target.className = "thover";
}

TreeControl.prototype.OnOutItem = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    if (target.className == "tselected")
        return;
    target.className = "";
}

TreeControl.prototype.OnMouseUp = function (event) {
    try {
        if (event.target.nodeName == "A") {
            event.target.focus();
        }
    }
    catch (e) { };
}

TreeControl.prototype.OnClick = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    treeControl.OnClickHandler(event, target);
}

TreeControl.prototype.OnDoubleClick = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    if (!target.tagName)
        target = target.parentNode;
    if (target.tagName == "A" || target.tagName == "IMG") {
        if (target.tagName == "IMG") {
            s = target.outerHTML;
            if ((s.substr(s.length - 11, 9) != "topic.gif") || (s.substr(s.length - 14, 12) != "question.gif") || (s.substr(s.length - 16, 14) != "assessment.gif")) {
                return;
            }
        }
        var t = target.parentNode.parentNode.firstChild;
        target = t;
        treeControl.OnClickHandler(event, target);
        if (parent.TreeItemDoubleSelected)
            parent.TreeItemDoubleSelected();
    }
    clearTextSelection();
}

function ChangeSelection(e, first) {
    ee = (e.tagName == "A" ? e : e.childNodes[0]);
    SetLastSelected(GetTpcAttribute(ee), treeViewMode);
    if (treeViewMode == "ALL") {
        if (modeDescA.lastSelected) {
            modeDescA.lastSelected.className = "";
        }
        modeDescA.lastSelected = ee;
        modeDescA.lastSelected.className = "tselected";
    }
    else if (treeViewMode == "FILTERED") {
        if (modeDescF.lastSelected) {
            modeDescF.lastSelected.className = "";
        }
        modeDescF.lastSelected = ee;
        modeDescF.lastSelected.className = "tselected";
    }
    else if (treeViewMode == "FILTEREDHEMI") {
        if (modeDescFH.lastSelected) {
            modeDescFH.lastSelected.className = "";
        }
        modeDescFH.lastSelected = ee;
        modeDescFH.lastSelected.className = "tselected";
    }
    else	//"HEMI"
    {
        if (modeDescH.lastSelected) {
            modeDescH.lastSelected.className = "";
        }
        modeDescH.lastSelected = ee;
        modeDescH.lastSelected.className = "tselected";
    }
    //	if (!first)
    //	{
    //		if (ee.parentNode.parentNode.focus)
    //			ee.parentNode.parentNode.focus();
    //	}

    //	if (parent["selector"].FocusToSearchField)
    //		parent["selector"].FocusToSearchField();
}

TreeControl.prototype.SelectFirstItem = function () {
    var hostname = "";
    if (treeViewMode == "ALL")
        hostname = "treeControlHostForAll";
    else if (treeViewMode == "FILTERED")
        hostname = "treeControlHostForFiltered";
    else if (treeViewMode == "FILTEREDHEMI")
        hostname = "treeControlHostForFilteredHemi";
    else	//"HEMI"
        hostname = "treeControlHostForHemi";
    var tpc = "";
    var span;
    var f = document.getElementById(hostname);

    f = f.firstChild;
    if (seeAlsoSelection >= f.childNodes.length) {
        f = f.firstChild;
    }
    else {
        f = f.childNodes[seeAlsoSelection];
    }

    while (tpc == "") {
        try {
            t = f.getAttribute("tpc");
        }
        catch (e) {
            return;
        }
        if (t) {
            tpc = t;
            span = f.lastChild;
        }
        f = f.firstChild;
    }
    ChangeSelection(span, true);
    mode = treeViewMode;
    if (selection_need == 1) {
        mode = "HIDE";
    }
    selection_need = 0;
    if (parent.TreeItemSelected)
        parent.TreeItemSelected(tpc, treeViewMode);
}

TreeControl.prototype.OnClickHandler = function (event, t) {
    var realselect = false;
    var callback = true;
    //	var t = event.target;
    if (!t.tagName)
        t = t.parentNode;
    if (t.tagName == "IMG") {
        var e = t.parentNode.parentNode.lastChild;
        if (e.tagName == "TABLE") // section icon
        {
            var f = t.parentNode.firstChild;

            if (t.openable || f.openable || e.openable) {
                if (e.className == "treeControlChildrenV") {
                    fsrc = f.getAttribute("srcroot") + "c.gif";
                    f.src = "../../img/empty.gif";
                    f.className = GetClassNameFromFile(fsrc);
                    f = f.nextSibling;
                    f = f.nextSibling;
                    f.src = "../../img/empty.gif";
                    f.className = GetClassNameFromFile("../../img/module_c.gif");
                    e.className = "treeControlChildrenH";
                    _go_closed = true;
                }
                else {
                    fsrc = f.getAttribute("srcroot") + "o.gif";
                    f.src = "../../img/empty.gif";
                    f.className = GetClassNameFromFile(fsrc);
                    f = f.nextSibling;
                    f = f.nextSibling;
                    f.src = "../../img/empty.gif";
                    f.className = GetClassNameFromFile("../../img/module_o.gif");
                    e.className = "treeControlChildrenV";
                    var g = e.firstChild.firstChild.lastChild;
                    if (!g.firstChild) {
                        goriginal = (g.id.length > 36 ? GetJunctionId(g.id) : g.id);
                        callback = false;
                        treeControl.LoadScript(goriginal + ".html", g.id);
                    }
                }
            }
        }
        else	// topic icon
        {
            var e = t.parentNode.lastChild;
            if (e.tagName == "IMG")
                return;
            ChangeSelection(e);
            realselect = true;
        }
    }
    if (t.tagName == "A") // text field in <A> tag
    {
        ChangeSelection(t);
        realselect = true;
    }

    var tpc = t.parentNode.getAttribute("tpc");
    if (tpc == null)
        tpc = t.parentNode.parentNode.getAttribute("tpc");
    if (realselect && parent.TreeItemSelected)
        parent.TreeItemSelected(tpc, treeViewMode);
    if (callback) {
        var n = null;
        try {
            n = f.parentNode.childNodes[f.parentNode.childNodes.length - 1].childNodes[0];
        }
        catch (e) { };
        _childNode_Loaded(n);
    }
}

function GetTableItemForThis(_item) {
    _tItem = _item.parentNode;
    if (_tItem == null)
        return null;
    while (_tItem.tagName != "TABLE") {
        _tItem = _tItem.parentNode;
        if (_tItem == null)
            return null;
    }
    return _tItem;
}

function ShowTreeItem(guid) {
    mdActual = getModeDesc();
    mdSource = getModeDesc(true);
    _item = GetTreeItemOfItemDesc(guid);
    if (_item == null) {
        while (_item == null) {
            var Item = null;
            Item = mdSource.filteredGuids[guid];
            if (Item == null)
                Item = modeDescF.filteredGuids[guid];
            if (Item == null)
                Item = modeDescH.filteredGuids[guid];
            if (Item == null)
                return false;
            guid = Item.parentguid;
            if (guid == null)
                return false;
            _item = GetTreeItemOfItemDesc(guid);
        }
        treeControl.LoadScript(guid + ".html", guid + "_" + mdActual.modeLetter);
    }
    return true;
}

function OpenItem(_tItem) {
    if (_tItem.className == "treeControlChildrenH") {
        f = _tItem.parentNode.firstChild.firstChild;
        f.src = "../../img/empty.gif";
        fscr = f.getAttribute("srcroot") + "o.gif";
        f.className = GetClassNameFromFile(fscr);
        f = f.nextSibling;
        f = f.nextSibling;
        f.src = "../../img/empty.gif";
        f.className = GetClassNameFromFile("../../img/module_o.gif");
        _tItem.className = "treeControlChildrenV";
    }
}

function ChangeTreeView() {
    retvalue = false;
    dA = document.getElementById("treeControlHostForAll");
    dS = document.getElementById("treeControlHostForFiltered");
    dSf = document.getElementById("flatControlHostForFiltered");
    dH = document.getElementById("treeControlHostForHemi");
    dHf = document.getElementById("flatControlHostForHemi");
    dFH = document.getElementById("treeControlHostForFilteredHemi");
    dFHf = document.getElementById("flatControlHostForFilteredHemi");

    if (treeViewMode == "FILTERED") {
        modeDescF.flatMode = !modeDescF.flatMode;
        retvalue = modeDescF.flatMode;
        dS.style.display = (modeDescF.flatMode ? "none" : "block");
        dSf.style.display = (modeDescF.flatMode ? "block" : "none");
    }
    else if (treeViewMode == "HEMI") {
        modeDescH.flatMode = !modeDescH.flatMode;
        retvalue = modeDescH.flatMode;
        dH.style.display = (modeDescH.flatMode ? "none" : "block");
        dHf.style.display = (modeDescH.flatMode ? "block" : "none");
    }
    else	// FILTEREDHEMI
    {
        modeDescFH.flatMode = !modeDescFH.flatMode;
        retvalue = modeDescFH.flatMode;
        dFH.style.display = (modeDescFH.flatMode ? "none" : "block");
        dFHf.style.display = (modeDescFH.flatMode ? "block" : "none");
    }
    ChangeTreeView_CallBack();
    return retvalue;
}

var directMode = false;

function _rec_SearchAInFlat(obj, tpc) {
    if (obj.nodeName == "IMG") {
        attr = obj.getAttribute("tpc");
        if (attr == tpc) {
            return obj;
        }
    }
    for (var i = 0; i < obj.childNodes.length; i++) {
        r = _rec_SearchAInFlat(obj.childNodes[i], tpc);
        if (r != null)
            return r;
    }
    return null;
}

function _rec_GetFirstObjInFlat(obj) {
    if (obj.nodeName == "IMG") {
        return obj;
    }
    for (var i = 0; i < obj.childNodes.length; i++) {
        r = _rec_GetFirstObjInFlat(obj.childNodes[i]);
        if (r != null)
            return r;
    }
    return null;
}

function SetFlatSelection() {
    mdActual = getModeDesc();
    obj = _rec_SearchAInFlat(mdActual.flatControl.host, _lastSelectedGlobal);
    if (obj == null)
        obj = _rec_GetFirstObjInFlat(mdActual.flatControl.host);
    if (obj != null) {
        mdActual.flatControl.OnClickHandler(null, obj);
        return;
    }
    if (parent.TreeItemSelected)
        parent.TreeItemSelected(null, null);
}

function ChangeTreeView_CallBack() {
    mdActual = getModeDesc();
    mdSource = getModeDesc(true);
    var _item = null;
    if (mdActual.flatMode == true) {
        SetFlatSelection();
        return true;
    }
    if (mdActual.flatMode == false || treeViewMode == "ALL") {
        var guid = null;
        //	    if (treeViewMode=="ALL")
        //	    {
        //	        guid=_lastSelectedItem.guid;
        //	    }
        //	    else
        //	    {
        //		    guid=mdSource.lastSelectedFlat.getAttribute("tpc");
        //		}
        guid = _lastSelectedGlobal;
        _item = GetTreeItemOfItemDesc(guid);
        if (_item == null) {
            if (!IsFiltered(guid, treeViewMode)) {
                return false;
            }
            directMode = true;
            k = ShowTreeItem(guid);
            return k;
        }
        if (_item != null) {
            _tItem = GetTableItemForThis(_item);
            while (_tItem != null) {
                OpenItem(_tItem);
                _tItem = GetTableItemForThis(_tItem);
            }
        }
    }
    directMode = false;
    createTreeControl(null, mdActual.flatMode, _item);
    return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FLAT VIEW
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function FlatControl(hostname) {
    this.host = document.getElementById(hostname);
    this.document = (this.host.document ? this.host.document : this.host.ownerDocument);
}

function showOnFlat(desc) {
    k = parseInt(desc.guid.split("_")[1]);
    if (desc.isroot == true && k == 1)
        return false;
    if (rolefilter_enabled == false)
        return true;
    ret = false;
    try {
        ret = filteredGuidsR[desc.guid].found;
    }
    catch (e) { };
    return ret;
}

function isInOutline(mydesc, guid) {
    if (mydesc.filteredGuids.length == 0)
        return true;
    var p = mydesc.filteredGuids[guid].parentguid;
    if (p == null)
        return false;
    var a = p.split("_");
    if (a[1] == "1")
        return true;
    else
        return isInOutline(mydesc, p);
}

function getModeDesc(source) {
    if (source == null)
        source = false;
    var mode = (source == true ? _lastSelectedGlobalMode : treeViewMode);
    if (mode == "ALL") {
        return modeDescA;
    }
    else if (mode == "FILTERED") {
        return modeDescF;
    }
    else if (mode == "HEMI") {
        return modeDescH;
    }
    else if (mode == "FILTEREDHEMI") {
        modeDescFH.guidsForFlat = new Array();
        for (var i = 0; i < modeDescF.guidsForFlat.length; i++) {
            guidF = modeDescF.guidsForFlat[i];
            for (var j = 0; j < modeDescH.guidsForFlat.length; j++) {
                guidH = modeDescH.guidsForFlat[j];
                if (guidF.guid == guidH.guid) {
                    modeDescFH.guidsForFlat[modeDescFH.guidsForFlat.length] = guidF;
                }
            }
        }
        return modeDescFH;
    }
    return null;
}

function saveModeDesc(md) {
    if (treeViewMode == "ALL") {
        modeDescA = md;
    }
    else if (treeViewMode == "FILTERED") {
        modeDescF = md;
    }
    else if (treeViewMode == "HEMI") {
        modeDescH = md;
    }
    else if (treeViewMode == "FILTEREDHEMI") {
        modeDescFH = md;
    }
}

FlatControl.prototype.Load = function () {
    myDesc = getModeDesc();
    this.host.innerHTML = "";

    div = this.host.appendChild(this.document.createElement("div"));
    div.className = "treeControlNode";
    div.onclick = this.OnClick;
    div.ondblclick = this.OnDoubleClick;
    div.onmouseup = this.OnMouseUp;
    table = div.appendChild(this.document.createElement("table"));
    table.cellSpacing = 0;
    first = true;
    var showCt = 0;
    for (var i = 0; i < myDesc.guidsForFlat.length; i++) {
        itemdesc = myDesc.guidsForFlat[i];
        if (showOnFlat(itemdesc) && isInOutline(myDesc, itemdesc.guid)) {
            showCt++;
            if (showCt > TreeConfig.SearchResultLimit)
                continue;
            myDesc.actualFlatCounter = showCt;
            tr = table.appendChild(this.document.createElement("tbody"));
            tr = tr.appendChild(this.document.createElement("tr"));
            td = tr.appendChild(this.document.createElement("td"));
            img = td.appendChild(this.document.createElement("img"));
            var esrc = (itemdesc.type == "Topic" ? "../../img/topic.gif" : (itemdesc.empty ? "../../img/emptysection.gif" : "../../img/module_c.gif"));
            img.className = GetClassNameFromFile(esrc);
            img.src = "../../img/empty.gif";
            img.setAttribute("tpc", itemdesc.guid);
            td = tr.appendChild(this.document.createElement("td"));
            td.className = "treeControlNode";
            a = td.appendChild(this.document.createElement("a"));
            if (first == true) {
                myDesc.lastSelectedFlat = a;
                saveModeDesc(myDesc);
            }
            a.className = (first == true ? "tselected" : "");
            if (first == true && _lastChangeIsFilterOnly == false) {
                SetLastSelected(itemdesc.guid, treeViewMode);
            }
            first = false;
            a.style.cursor = "pointer";
            a.setAttribute("tpc", itemdesc.guid);
            a.onmouseover = this.OnOverItem;
            a.onmouseout = this.OnOutItem;
            var _tname = itemdesc.title;
            if (treeViewMode == "HEMI" && parent.showscore > 0) {
                _tname = "" + Math.round(itemdesc.score * 100) + " " + itemdesc.title;
            }
            a.appendChild(this.document.createTextNode(_tname));
        }
    }
    if (myDesc.flatMode == true) {
        SetFlatSelection();
    }
    var tpc = null;
    try {
        tpc = myDesc.lastSelectedFlat.getAttribute("tpc");
    }
    catch (e) { };
    if (parent.TreeItemSelected)
        parent.TreeItemSelected(tpc, treeViewMode);

}

FlatControl.prototype.OnOverItem = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    if (target.className == "tselected")
        return;
    target.className = "thover";
}

FlatControl.prototype.OnOutItem = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    if (target.className == "tselected")
        return;
    target.className = "";
}

FlatControl.prototype.OnMouseUp = function (event) {
    try {
        if (event.target.nodeName == "A") {
            event.target.focus();
        }
    }
    catch (e) { };
}

FlatControl.prototype.OnClick = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    mdActual = getModeDesc();
    mdActual.flatControl.OnClickHandler(event, target);
}

FlatControl.prototype.OnDoubleClick = function (event) {
    if (!event)
        event = window.event;
    target = event.target;
    if (!target)
        target = event.srcElement;
    mdActual = getModeDesc();
    mdActual.flatControl.OnClickHandler(event, target);
    if (parent.TreeItemDoubleSelected)
        parent.TreeItemDoubleSelected();
}

FlatControl.prototype.OnClickHandler = function (event, target) {
    a = target;
    t = GetTpcAttribute(a);
    if (t != null)
        SetLastSelected(t, treeViewMode);
    if (target.tagName != "A" && target.tagName != "IMG")
        return;
    if (target.tagName != "A") {
        tr = target.parentNode.parentNode;
        for (var i = 0; i < tr.childNodes.length; i++) {
            k = tr.childNodes[i].childNodes[0];
            if (k.tagName == "A") {
                a = k;
                continue;
            }
        }
    }
    if (treeViewMode == "FILTERED") {
        modeDescF.lastSelectedFlat.className = "";
    }
    else if (treeViewMode == "HEMI") {
        modeDescH.lastSelectedFlat.className = "";
    }
    else	// FILTEREDHEMI
    {
        modeDescFH.lastSelectedFlat.className = "";
    }
    a.className = "tselected";
    if (treeViewMode == "FILTERED") {
        modeDescF.lastSelectedFlat = a;
    }
    else if (treeViewMode == "HEMI") {
        modeDescH.lastSelectedFlat = a;
    }
    else	// FILTEREDHEMI
    {
        modeDescFH.lastSelectedFlat = a;
    }
    var tpc = a.getAttribute("tpc");
    if (parent.TreeItemSelected)
        parent.TreeItemSelected(tpc, treeViewMode);
}

function GetActualFlatView() {
    md = getModeDesc();
    return md.flatMode;
}

function GetActualFlatItemCounter() {
    md = getModeDesc();
    return md.actualFlatCounter;
}

function IsActualViewEmpty() {
    md = getModeDesc();
    return (md.filteredGuidList == 0);
}

//////////////////////////////////////////////////////////////////////////////////////////

function getActualIndex_Flat() {
    md = getModeDesc();
    if (md.flatMode == true) {
        for (var i = 0; i < md.flatControl.host.firstChild.firstChild.childNodes.length; i++) {
            if (md.flatControl.host.firstChild.firstChild.childNodes[i].firstChild.childNodes[1].firstChild.className == "tselected") {
                return i;
            }
        }
    }
    return "";
}

function getActualIndex_Tree(ls, md) {
    for (var i = 0; i < ls.length; i++) {
        if (ls[i].firstChild.childNodes[3].firstChild.className == "tselected") {
            return i;
        }
    }
    if (md.lastSelected != null) {
        _tpc = md.lastSelected.parentNode.parentNode.getAttribute("tpc");
        for (var i = 0; i < ls.length; i++) {
            if (ls[i].firstChild.getAttribute("tpc") == _tpc)
                return i;
        }
    }
    return "";
}

function getTargetForIndex_Flat(md, i) {
    return md.flatControl.host.firstChild.firstChild.childNodes[i].firstChild.firstChild.firstChild;
}

function getTargetForIndex_Tree(i) {
    return ls[i].firstChild.childNodes[3].firstChild;
}

function getActualImageObj_Tree(md) {
    return md.lastSelected.parentNode.parentNode.firstChild;
}

function getSpecifiedImageObj_Tree(ls, k) {
    return ls[k].firstChild.firstChild;
}

function getOwnerOfSelection() {
    var myid = md.lastSelected.parentNode.parentNode.parentNode.childNodes[0].getAttribute("tpc");
    var owner = md.filteredGuids[myid].parentguid;
    return owner;
}

function getOpenedStatus(obj) {
    /*
    s = obj.getAttribute("src");
    k = s.indexOf(".gif");
    c = s.substr(k - 1, 1);
    */
    s = obj.className;
    c = s.substr(s.length - 1, 1);
    return (c == "o");
}

function getFilteredStatus(guid) {
    var r = IsFiltered(guid, "ALL");
    return !r;
}

function _getLinearStructure_Recursive(o, a) {
    a[a.length] = o;
    _imgObj = o.firstChild.firstChild;
    if (getOpenedStatus(_imgObj) == true) {
        for (var i = 0; i < o.childNodes[1].firstChild.firstChild.childNodes[1].childNodes.length; i++) {
            _getLinearStructure_Recursive(o.childNodes[1].firstChild.firstChild.childNodes[1].childNodes[i], a);
        }
    }
}

function getRoot(o) {
    if (o.tagName == "DIV" && o.id.substr(0, 15) == "treeControlHost")
        return o.firstChild;
    return getRoot(o.parentNode);
}

function getLinearStructure_Tree(md) {
    var oArray = new Array();
    root = getRoot(md.lastSelected);
    //    root = treeControl.host.firstChild;
    for (var i = 0; i < root.childNodes.length; i++) {
        _getLinearStructure_Recursive(root.childNodes[i], oArray);
    }
    return oArray;
}

function EventKeyDown(event) {
    if (event == null)
        event = window.event;
    var code = event.which ? event.which : event.keyCode;
    if (code == 13) {
        if (parent.TreeItemDoubleSelected)
            parent.TreeItemDoubleSelected();
        return;
    }
    md = getModeDesc();
    if (md.flatMode == true) {
        index = getActualIndex_Flat();
        if (code == 38) {  // up
            if (index > 0) {
                t = getTargetForIndex_Flat(md, index - 1);
                md.flatControl.OnClickHandler(null, t);
            }
        }
        else if (code == 40) {  // down
            if (index < md.actualFlatCounter - 1) {
                t = getTargetForIndex_Flat(md, index + 1);
                md.flatControl.OnClickHandler(null, t);
            }
        }
    }
    else {
        imgObj = getActualImageObj_Tree(md);
        _isOpenable = (imgObj.openable ? imgObj.openable : imgObj.getAttribute("openable"));
        _isOpened = getOpenedStatus(imgObj);
        ls = getLinearStructure_Tree(md);
        index = getActualIndex_Tree(ls, md);
        if (code == 37) {  // left
            if (_isOpenable == true) {
                if (_isOpened == true) {
                    treeControl.OnClickHandler(null, imgObj);
                    return false;
                }
            }
        }
        else if (code == 38) {  // up
            if (index > 0) {
                t = getTargetForIndex_Tree(index - 1);
                treeControl.OnClickHandler(null, t);
            }
        }
        else if (code == 39) {  // right
            if (_isOpenable == true) {
                if (_isOpened == false) {
                    treeControl.OnClickHandler(null, imgObj);
                    return false;
                }
            }
        }
        else if (code == 40) {  // down
            if (index < ls.length - 1) {
                t = getTargetForIndex_Tree(index + 1);
                treeControl.OnClickHandler(null, t);
            }
        }
    }
}

function tree_SetFocus() {
    document.frames[0].document.childNodes[1].childNodes[1].focus();
}

function tree_Init() {
    document.onkeydown = EventKeyDown;
    if (parent.Init_treeloaded)
        parent.Init_treeloaded();
}

function clearTextSelection() {
    if (document.selection)
        document.selection.empty();
    if (window.getSelection)
        window.getSelection().removeAllRanges();
}

function GoToNext() {
    md = getModeDesc();
    if (md.flatMode == true) {
        index = getActualIndex_Flat();
        if (index < md.actualFlatCounter - 1) {
            t = getTargetForIndex_Flat(md, index + 1);
            md.flatControl.OnClickHandler(null, t);
        }
    }
    else {
        imgObj = getActualImageObj_Tree(md);
        _isOpenable = (imgObj.openable ? imgObj.openable : imgObj.getAttribute("openable"));
        _isOpened = getOpenedStatus(imgObj);
        ls = getLinearStructure_Tree(md);
        index = getActualIndex_Tree(ls, md);
        if (index < ls.length - 1) {
            t = getTargetForIndex_Tree(index + 1);
            treeControl.OnClickHandler(null, t);
        }
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////

var _go_next = false;
var _go_prev = false;
var _go_closed = false;

function Navigation_Up() {
    md = getModeDesc();
    if (md.flatMode == false) {
        ls = getLinearStructure_Tree(md);
        index = getActualIndex_Tree(ls, md);
        prevImgObj = getSpecifiedImageObj_Tree(ls, index - 1);
        _isOpenable = Bool(prevImgObj.openable != undefined ? prevImgObj.openable : prevImgObj.getAttribute("openable"));
        _isOpened = getOpenedStatus(prevImgObj);
        if (_isOpenable && !_isOpened) {
            _go_prev = true;
            treeControl.OnClickHandler(null, prevImgObj);
            return;
        }
    }

    var e = new Object();
    e.keyCode = 38;
    EventKeyDown(e);
}

function Navigation_Down() {
    md = getModeDesc();
    if (md.flatMode == false) {
        imgObj = getActualImageObj_Tree(md);
        _isOpenable = Bool(imgObj.openable != undefined ? imgObj.openable : imgObj.getAttribute("openable"));
        _isOpened = getOpenedStatus(imgObj);
        if (_isOpenable && !_isOpened) {
            _go_next = true;
            var e = new Object();
            e.keyCode = 39;
            EventKeyDown(e);
            return;
        }
    }
    var e = new Object();
    e.keyCode = 40;
    EventKeyDown(e);
}

function isFirstItem() {
    md = getModeDesc();
    if (md.flatMode == true) {
        index = getActualIndex_Flat();
    }
    else {
        if (md.lastSelected == null)
            return true;
        ls = getLinearStructure_Tree(md);
        index = getActualIndex_Tree(ls, md);
    }
    return (index == 0);
}

function isLastItem() {
    md = getModeDesc();
    if (md.flatMode == true) {
        return (index == md.filteredTopicCount - 1);
    }
    else {
        if (md.lastSelected == null)
            return false;
        ls = getLinearStructure_Tree(md);
        index = getActualIndex_Tree(ls, md);
        if (index == ls.length - 1) {
            imgObj = getActualImageObj_Tree(md);
            _isOpenable = imgObj.openable;
            return (_isOpenable == false);
        }
        return false;
    }
}

function _childNode_Loaded(node) {
    if (_go_next == true) {
        _go_next = false;
        Navigation_Down();
    }
    if (_go_prev == true) {
        md = getModeDesc();
        if (md.flatMode == false) {
            ls = getLinearStructure_Tree(md);
            index = getActualIndex_Tree(ls, md);
            prevImgObj = getSpecifiedImageObj_Tree(ls, index - 1);
            _isOpenable = Bool(prevImgObj.openable != undefined ? prevImgObj.openable : prevImgObj.getAttribute("openable"));
            _isOpened = getOpenedStatus(prevImgObj);
            if (_isOpenable && !_isOpened) {
                _go_prev = true;
                treeControl.OnClickHandler(null, prevImgObj);
                return;
            }
            else {
                _go_prev = false;
                Navigation_Up();
            }
        }
    }
    if (_go_closed == true) {
        _go_closed = false;
        md = getModeDesc();
        if (md.flatMode == false) {
            ls = getLinearStructure_Tree(md);
            index = getActualIndex_Tree(ls, md);
            if (index == "") {
                treeControl.OnClickHandler(null, node);
            }
        }
    }
}

function Bool(s) {
    if (typeof (s) == "boolean")
        return s;
    if (typeof (s) == "string") {
        if (s.toLowerCase() == "false")
            return false;
        if (s.toLowerCase() == "true")
            return true;
    }
    return null;
}

///////////////////////////////////////////////////////////////////////////////

var indexMap = new Array();
var treeIndex = new Array();

function AddToIndexMap(s) {
    if (bigsco == false)
        return;
    if (s.length <= 36)
        return;
    var guid = s.substr(0, 36);
    var index = s.substr(37);
    indexMap[index] = guid;
}

var _tocStates2 = null;
var _tocStates_initialized = false;

function InitTocStates() {
    if (_tocStates_initialized)
        return;
    _tocStates_initialized = true;
    if (bigsco == false)
        return;

    for (var i = 0; i < parentIndex.length; i++) {
        treeIndex[i] = new Array();
        treeIndex[i][0] = parentIndex[i];
    }
    for (var i = 0; i < parentIndex.length; i++) {
        var v = parentIndex[i];
        treeIndex[v][treeIndex[v].length] = i;
    }

    _tocStates2 = new Array();
    for (var i = 0; i < parent.lms_TOCState.NodeCounter; i++) {
        _tocStates2[i] = parent.lms_GetItemStatus(i);
    }
    InitOneItemState(childIndexLocal2Global(0));
    var a = parent.lms_GetItemStatus(0);
    var b = _tocStates2[0];
    if (a != b) {
        parent.lms_SetItemStatus(0, b);
    }
    updateTreeTrace()
}

// global index parameter
function InitOneItemState(k) {
    var ch = index_getChildList(k);
    for (var i = 0; i < ch.length; i++) {
        InitOneItemState(ch[i]);
    }
    var x = childIndexGlobal2Local(k);
    if (k != 0)
        _tocStates2[k] = BuildItemStatus(k, true);
}

function GetItemStatus(guid, init) {
    var g_index = guid.substr(37);
    var l_index = childIndexGlobal2Local(g_index);
    var s = BuildItemStatus(g_index, init);
    _tocStates2[l_index] = s;
    return s;
}

function _GetItemStatusFile(status) {
    var base = "";
    switch (status) {
        case "N": return base + "sco_notstarted";
        case "I": return base + "sco_incomplete";
        case "C": return base + "sco_completed";
        case "P": return base + "sco_passed";
        case "F": return base + "sco_failed";
    }
    return "";
}

function _GetItemStatusTitle(status) {
    switch (status) {
        case "N": return R_status_tree_notstarted;
        case "I": return R_status_tree_inprogress;
        case "C": return R_status_tree_complete;
        case "P": return R_status_tree_passed;
        case "F": return R_status_tree_failed;
    }
    return "";
}

// local index parameter
function UpdateItemStatus(index) {
    _tocStates2[index] = parent.lms_GetItemStatus(index);
    var i = childIndexLocal2Global(index);
    var guid = indexMap[i] + "_" + i;
    RefreshItemStatus(guid);
    BuildRootItemStatus();
    updateTreeTrace();
}

function RefreshItemStatus(guid) {
    if (bigsco == false)
        return;
    var md = getModeDesc(guid);

    var item = md.filteredGuids[guid];
    if (item == null)
        return;

    var stat = GetItemStatus(guid);
    item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("src", "../../img/empty.gif");
    _itemState = _GetItemStatusFile(stat);
    item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("class", _itemState); // for FF, Chrome, Safari
    item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("className", _itemState); // for IE
    item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("title", _GetItemStatusTitle(stat));
    item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("alt", _GetItemStatusTitle(stat));

    if (item.parentguid == null)
        return;
    RefreshParentItemStatus(item.parentguid);
}

function RefreshParentItemStatus(guid) {
    var g_index = guid.substr(37);
    var l_index = childIndexGlobal2Local(g_index);
    var st0 = _tocStates2[l_index];
    var st1 = BuildItemStatus(g_index);
    if (l_index == 0) {
        if (st1 == "N") {
            return;
        }
    }
    if (st1 != st0) {
        //        parent.lms_SetItemStatus(l_index, st1);
        _tocStates2[l_index] = st1;
        if (l_index == 0) {
            parent.lms_SetItemStatus(0, st1);
        }
        updateTreeTrace();
        var md = getModeDesc(guid);
        var item = md.filteredGuids[guid];
        if (item == null)
            return;
        item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("src", "../../img/empty.gif");
        _itemState = _GetItemStatusFile(st1);
        item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("class", _itemState); // for FF, Chrome, Safari
        item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("className", _itemState); // for IE
        item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("title", _GetItemStatusTitle(st1));
        item.treeitemdiv.parentNode.parentNode.childNodes[1].setAttribute("alt", _GetItemStatusTitle(st1));
        if (item.parentguid != null)
            RefreshParentItemStatus(item.parentguid);
    }
}

function getBaseIndex() {
    return parseInt(_rootData.substr(37));
}

function childIndexLocal2Global(x) {
    return (parseInt(x) + getBaseIndex());
}

function childIndexGlobal2Local(x) {
    return (x - getBaseIndex());
}

function index_getParent(x) {
    if (!index_checkIndex(x))
        return -1;
    return treeIndex[x][0];
}

function index_getChildList(x, f) {
    if (!index_checkIndex(x))
        return -1;
    var a0 = treeIndex[x];
    var a = new Array();
    for (var i = 1; i < a0.length; i++) {
        if (!f)
            a[i - 1] = a0[i];
        else if (f != a0[i])
            a[i - 1] = a0[i];
    }
    return a;
}

function index_hasChildren(x) {
    if (!index_checkIndex(x))
        return -1;
    var a0 = treeIndex[x];
    return (a0.length > 1);
}

function index_checkIndex(x) {
    if (x > treeIndex.length - 1)
        return false;
    return (treeIndex[x].length > 0);
}

// global index parameter
function BuildItemStatus(x, init) {
    var l_x = childIndexGlobal2Local(x);
    var s = BuildItemStatus2(x, l_x);
    return s;
}

function BuidStatus(s, haschild) {
    if (s.indexOf("I") >= 0)
        return "I";
    if (s.indexOf("N") >= 0) {
        if (s.indexOf("C") >= 0 || s.indexOf("F") >= 0 || s.indexOf("P") >= 0)
            return "I";
        else
            return "N";
    }
    if (s.indexOf("F") >= 0) {
        if (haschild == false)
            return "F";
        else
            return "C";
    }
    if (s.indexOf("P") >= 0) {
        if (haschild == false)
            return "P";
        else
            return "C";
    }
    return "C";
}

function BuildItemStatus2(x, l_x) {
    var ch = index_getChildList(x);
    var s = "";
    if (l_x != 0) {
        if (conceptIndex[x] > 0)
            s += parent.lms_GetItemStatus(l_x);
    }
    for (var i = 0; i < ch.length; i++) {
        s += _tocStates2[childIndexGlobal2Local(ch[i])];
    }
    var _stat = BuidStatus(s, ch.length > 0);
    return _stat;
}

function BuildRootItemStatus() {
    var x = childIndexLocal2Global(0);
    var ch = index_getChildList(x);
    var s = "";
    for (var i = 0; i < ch.length; i++) {
        s += _tocStates2[childIndexGlobal2Local(ch[i])];
    }
    var _stat = BuidStatus(s, ch.length > 0);
    _tocStates2[0] = _stat;
}

/************************************************************************************/

var treeTraceOn = false;
var treeTraceWnd = null;

function updateTreeTrace() {
    try {
        if (!treeTraceOn)
            return;
        if (treeTraceWnd == null)
            treeTraceWnd = window.open();
        treeTraceWnd.document.body.innerHTML = "";
        for (var i = 0; i < _tocStates2.length; i++) {
            treeTraceWnd.document.write(" " + i + ": " + _tocStates2[i] + " - " + parent.lms_GetItemStatus(i) + "<br/>");
        }
    }
    catch (e) { };
}/* relativelink.js */ 
﻿// Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.

// Split an URI into three main parts
function splitUri(uri) {
    // Split the URI into parts
    var parts = uri.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
    parts.shift();

    // Identidy tge different parts
    var scheme = parts[1], authority = parts[3], path = parts[4], querystring = parts[6], frag = parts[8];

    // Build the three main part of the URI: prefix, path, postfix
    parts = [scheme + "://" + authority, path, querystring + frag];

    // Return the three main parts as an array
    return parts;
}

// Combine base and relative URL into a resolved URL
function combine(baseUrl, relativeUrl) {

    // Remove the "odrel://" prefix if exists
    var relativePath = relativeUrl;
    if (relativePath.indexOf('odrel://') == 0)
        relativePath = relativePath.substr('odrel://'.length);

    // Empty relative path points to base path
    if (relativePath == "") relativePath = ".";

    // Split the base url into the main three parts
    var baseUrlparts = splitUri(baseUrl);
    var baseUrlPrefix = baseUrlparts[0]; var baseUrlPath = baseUrlparts[1];

    // Trim slashes
    if (baseUrlPath.charAt(0) == '/') baseUrlPath = baseUrlPath.substr(1);
    if (baseUrlPath.charAt(baseUrlPath.length - 1) == '/') baseUrlPath = baseUrlPath.substr(0, baseUrlPath.length - 1);
    if (relativePath.charAt(relativePath.length - 1) == '/') relativePath = relativePath.substr(0, relativePath.length - 1);

    // Split the paths into segments
    var baseUrlPathSegments = baseUrlPath.split('/');
    var relativePathSegments = relativePath.split('/');

    if ((relativePathSegments.length > 2) && (relativePathSegments[0] == '') && (relativePathSegments[1] == '')) {
        var path = baseUrlPrefix.split(':')[0] + ":/";
        for (var i = 2; i < relativePathSegments.length; i++)
            path += "/" + relativePathSegments[i];

        return path;
    }

    // Initialize the segments of the resolved path
    var resolvedPathSegments = new Array();
    for (var i = 0; i < baseUrlPathSegments.length; i++)
        resolvedPathSegments[i] = baseUrlPathSegments[i];

    // Resolve the relative address
    for (var i = 0; i < relativePathSegments.length; i++) {
        if (relativePathSegments[i] == "..") {
            if (resolvedPathSegments.length > 0) {
                // Remove the last folder in the URI
                resolvedPathSegments = resolvedPathSegments.slice(0, resolvedPathSegments.length - 1);
            }
        }
        else if (relativePathSegments[i] == ".") {
            // Do nothing
        }
        else if (relativePathSegments[i] == "") {
            // Remove all segments from the base URL
            resolvedPathSegments = new Array();
        }
        else {
            // Add the segment to the end of the resolved address
            resolvedPathSegments[resolvedPathSegments.length] = relativePathSegments[i];
        }
    }

    // Build the resolved path
    var resolvedPath = '';
    for (var i = 0; i < resolvedPathSegments.length; i++)
        resolvedPath += '/' + resolvedPathSegments[i];
    var resolvedUrl = baseUrlPrefix + resolvedPath;

    // Return the resolved URI
    return resolvedUrl;
}

// Get the root URL of the player (folder of the index.html)
function getRootUrl() {

    // If the function is running in toc.html
    if (typeof (isTocHtml) != "undefined") {
        var url = document.location.href;
        return url.substr(0, url.lastIndexOf("/"));
    }

    // Split the URL of current document into parts
    var documentUrlParts = splitUri(document.location.href);
    var documentUrlPrefix = documentUrlParts[0];
    var documentUrlPath = documentUrlParts[1];

    // Trim the document path
    if (documentUrlPath.charAt(0) == '/') documentUrlPath = documentUrlPath.substr(1);

    // Split the document URL path into segments
    var documentPathSegments = documentUrlPath.split('/');

    // Find the tpc folder in the document path
    var i;
    for (i = documentPathSegments.length - 1; documentPathSegments[i] != 'tpc' && i >= 0; i--) { };

    if (i > 0) i = i - 1;

    // Build the path of the root URL
    var rootPath = "";
    for (var j = 0; j < i; j++)
        rootPath += "/" + documentPathSegments[j];

    // Build the root URL
    var rootUrl = documentUrlPrefix + rootPath;

    // Return the root URL
    return rootUrl;
}

function isRelative(uri) {
    // Split the URI into parts
    var parts = uri.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);

    // If there is no scheme in the uri, then it's relative
    return (parts[1] == '') || (parts[1] == undefined);
}

// Checks the url and resolves if it is relative
function resolveIfRelative(Url) {
    if (Url.indexOf("odrel://") == 0)
        return resolve(Url);
    else
        return Url;
}

// Resolve a relative URL based on the configured base address
function resolve(relativeUrl) {

    // If the base URL is relative
    if (isRelative(PlayerConfig.BaseUrl)) {
        // Get the URL of the player root
        var rootUrl = getRootUrl();
        // Get hte basolute base URL
        var absoluteBaseUrl = combine(rootUrl, PlayerConfig.BaseUrl);
        // Resolve the relative URL
        return combine(absoluteBaseUrl, relativeUrl);
    }
    // If the base URL is absolute
    else {
        // Resolve the relative URL
        return combine(PlayerConfig.BaseUrl, relativeUrl);
    }
}

// Resolve all link in a web page
function resolveLinksInWebPage() {
    // Get the links from the document
    var links = document.getElementsByTagName("a");

    // For each link
    for (var i = 0; i < links.length; i++)
    // If the link is relative        
        if (links[i].getAttribute("href").indexOf('odrel://') == 0) {
        // Resolve the URL
        links[i].href = resolve(links[i].getAttribute("href"));
    }
}/* lmsapplet.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

// the following code must exist for AICC
// Only add the java applet to the page when running a course through HACP.

var intPos = window.location.search.toLowerCase().indexOf("aicc_url");
var intPos2 = window.location.search.toLowerCase().indexOf("aicc_sid");
function getOnlyPath(s) {
    while (s.indexOf('\\') != -1)
        s = s.replace('\\', '/');
    return s.substr(0, s.lastIndexOf("/"));
}
if ((intPos>-1) && (intPos2>-1)) {
	//running in AICC mode
	if (LmsConfig.AiccAppletPath == "") {
		//using applet from package
        var currentPgPath = window.location.protocol + "//" + window.location.host + getOnlyPath(window.location.pathname);
		fullPath = currentPgPath + "/" + lms_path + "js";
	}
	else {
		//using applet from predeifned location
	    fullPath = LmsConfig.AiccAppletPath;
	}

	document.write("<div style='position: absolute;'><applet NAME='GetHTTPPostData' codebase='" + fullPath + "' code='GetHTTPPostData.class' width='1' height='1' MAYSCRIPT></applet></div>");
}
/* lmscomfactory.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

// This function is reposible for inserting
// the KPath API into the environment if
// the asset is running under KPath and 
// no API can currently be found. 
//
// This call inserts an invisible iframe and 
// sets its source to a HTML page that will 
// contains the KPATH Scorm API adaptor when
// the page is configured to run under Kpath UT.
//
// Since invisible iframe page will load asyncronously
// we have to tie the LmsCom creation with the 
// onload of the iframe.
function InsertRuntimeAPI(loadcallback) {

    /* If we are not running with Kpath we do not have
       to insert the API so just directly call the
       load callback. */ 
    if (Kpath_launch == false) {
        setTimeout(loadcallback, 1);
        return;
    }

    /* We are running under KPath, check to see if
    the frame hosting the low level KPath
    API adaptor has been loaded somewhere.
    If so, do nothing else but directly
    call the load call back.
       
    Else we have to asynchronously load the
    API frame into the environment */
    var apiframe = findKPathAPIFrame(window);

    if (apiframe == null) {
        apiframe = document.createElement("iframe");
        apiframe.id = "KPATH_API_FRAME";
        apiframe.style.display = 'none';

        document.body.appendChild(apiframe);

        if (loadcallback) {
            if (navigator.appName == "Microsoft Internet Explorer")
                apiframe.attachEvent("onload", loadcallback);
            else
                apiframe.onload = loadcallback;

        }

        apiframe.src = Kpath_Runtime_API;
    }
    else
        setTimeout(loadcallback, 1);
}

function findKPathAPIFrame(win) {
    var apiframe = null;
    var depth = 0;
    var w = win;

    try {
        while (w != null) {
            apiframe = w.document.getElementById("KPATH_API_FRAME");
    
            if (apiframe != null)
                return apiframe.contentWindow;
    
            depth++;
            // Note: 7 is an arbitrary number, but should
            // be more than sufficient
            if (depth > 7) {
                break;
            }
    
            if (w === w.parent) break;
            w = w.parent;
        }
    
        if (win.top.opener != null)
            return findKPathAPIFrame(win.top.opener);
    } catch (e) {
        return null;
    }


    return null;
}

var _GlobalLmsComFactory = null; 

function GetLmsComFactory() {

    if (_GlobalLmsComFactory == null)
        alert(R_initializelmscom_not_called);
        
    return _GlobalLmsComFactory;
}


function CheckForLMSAPI() {
    if (_lmsMode == "LMS" &&
            !(_GlobalLmsComFactory.api_type == "scorm2004" ||
              _GlobalLmsComFactory.api_type == "scorm12" ||
              _GlobalLmsComFactory.api_type == "aicc" ||
              (_GlobalLmsComFactory.api_type == "kpath" && findKPathAPIFrame(window))
            )
        )
            alert(R_scorm_noapi);
    if (_lmsMode == "KPT" && !findKPathAPIFrame(window))
        alert(R_scorm_noapi);
}


function InitializeLmsCom() {
    _GlobalLmsComFactory = new LmsComFactory(window.location.search);
}

/* LmsComFactory uses environmental information like URL  parameters
   and runtime variables to determine which type of LmsCom object
   it should instantiated.  Note that code outside of the JS file 
   should use GetLmsCom instead since GetLmsCom has logic in it 
   that allows the parent page to provide the LmsCom object if 
   it wants to. */ 
function LmsComFactory(launcharg) {
    var fname = "LmsComFactory";

    this.api_type = "none";
    
    this.launch_arg = launcharg;
    this.aicc_url = "";
    this.aicc_sid = "";

    //maintain the api pointer if found so that lmscomscorm constructors can use it
    this.scorm_api_12 = null;
    this.scorm_api_2004 = null; 

    if (launcharg == null)
        launcharg = "";
        
    var strArgs = this.launch_arg.substring(1).split("&");

    lmslog.addEntry(0, fname, "strArgs", strArgs);
    for (var i = 0; i < strArgs.length; i++) {
        strArg = strArgs[i];

        var val;

        val = this.CheckParam(strArg, "aicc_url=");
        if (val != "") {
            // this is aicc Hacp, set flag to indicate this
            if (val.substr(0, 4).toLowerCase() != "http") {
                this.aicc_url = LmsConfig.AiccUrlProtocol + val;
            }
            else
                this.aicc_url = val;

            continue;
        } 
        
        val = this.CheckParam(strArg, "aicc_sid=");
        if (val != "") {
            this.aicc_sid = val;
            continue;
        }
    }

    //maintain the api pointer if found so that lmscomscorm constructors can use it
    if (LmsConfig.ScormVersion !== "1.2")
        this.scorm_api_2004 = this.FindScorm2004API();
    if (this.scorm_api_2004 == null && LmsConfig.ScormVersion !== "2004")
        this.scorm_api_12 = this.FindScorm12API();

    if ((this.aicc_url != "") && (this.aicc_sid != "")) {
        this.api_type = "aicc";
    }
    else if (Kpath_launch == true) {
        this.api_type = "kpath"; 
    }
    else if (this.scorm_api_2004 != null) {
        this.api_type = "scorm2004";
    }
    else if (this.scorm_api_12 != null) {
        this.api_type = "scorm12";
    }
}


/* The factory method for LmsCom. */
// LZ: LmsComKPath added
LmsComFactory.prototype.CreateLmsCom = function() {

    if (this.api_type == "aicc") {
        return new LmsComAICC(this.aicc_url, this.aicc_sid);
    }
    else if (this.api_type == "scorm2004") {
        return new LmsComScorm2004();
    }
    // If portal launch, there will be an adapter to be found and top level SCO
    // should use it rather than calling LoadRuntime.
    else if (this.api_type == "kpath") {
        var lmscom = new LmsComKPath();
        lmscom.API = this.scorm_api_2004;
        return lmscom;
    }
    else if (this.api_type == "scorm12") {
        return new LmsComScorm12();
    }

    if (PlayerConfig.EnableCookies)
        return new LmsComCookie();
    else
        return new LmsComBase(); 
}

LmsComFactory.prototype.FindScorm12API = function () {
    try {
        var theAPI = this.FindWindowScorm12API(window);
    
        if ((theAPI == null) && (top.window.opener != null) && (!top.window.opener.closed)) {
            theAPI = this.FindWindowScorm12API(top.window.opener);
        }
    
        return theAPI;
    } catch (e) {
        return null;
    }
}

LmsComFactory.prototype.FindWindowScorm12API = function(win) {
   var findAPITries = 0;
   while ((win.API == null) && (win.parent != null) && (win.parent != win))
   {
      findAPITries++;
      // Note: 500 is an arbitrary number, but should be more than sufficient
      if (findAPITries > 500) 
      {
        lmslog.addEntry(0, "FindScorm12API", "", R_scorm_apideep);
        return null;
      }
      
      win = win.parent;
  }
   
   return win.API;
}

LmsComFactory.prototype.FindScorm2004API = function() {
    try {
        var theAPI = this.FindWindowScorm2004API(window);

        if ((theAPI == null) && (top.window.opener != null) && (!top.window.opener.closed)) {
            theAPI = this.FindWindowScorm2004API(top.window.opener);
        }

        return theAPI;
    } catch (e) {
        return null;
    }
}

LmsComFactory.prototype.FindWindowScorm2004API = function(win) {
    var findAPITries = 0;
 
    while ((win.API_1484_11 == null) && (win.parent != null) && (win.parent != win)) {
        findAPITries++;

        if (findAPITries > 500) {
            lmslog.addEntry(0, "FindScorm2004API", "", R_scorm_apideep);
            return null;
        }
        win = win.parent;
    }

    return win.API_1484_11;
}

LmsComFactory.prototype.CheckParam = function(strArg, param) {
    var len = param.length;
    var val = "";

    if (strArg.substr(0, len).toLowerCase() == param) {
        val = strArg.substring(len);
    }

    return val;
}

/* lmscom.js */ 
/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

/* Constant for the different statuses that a coarse may have.  
   These ID corresponsed to the values used by both SCORM and 
   AICC. */ 
var LMS_PASSED = "passed";
var LMS_FAILED = "failed";
var LMS_COMPLETED = "completed";
var LMS_INCOMPLETE = "incomplete";
var LMS_NOT_ATTEMPTED = "not attempted";

/* Extend internal Date object to format for SCORM 2004 */
Date.prototype.toSCORM = function() {
    return this.getFullYear() + "-" + ("0"+(this.getMonth()+1)).slice(-2) + "-" + ("0"+this.getDate()).slice(-2)
        + "T" + ("0"+this.getHours()).slice(-2) + ":" + ("0"+this.getMinutes()).slice(-2) + ":" + ("0"+this.getSeconds()).slice(-2);
}

///////////////////////////////////////
//
// LmsCom object defintions
//
///////////////////////////////////////

///////////////////////////////////////
// Base LmsCom object defintion
///////////////////////////////////////
function LmsComBase(parent) {
    this.status_obj = null;
    this.ordinal_number = 0; 
    
    this.start_date = "";
    this.end_date = "";
    this.student_id = "";
    this.student_name = "";
    this.credit = "";
    this.lesson_status = LMS_NOT_ATTEMPTED;
    this.lesson_flag = "";
    this.lesson_location = "";
    this.lesson_data = "";
    this.original_lesson_data = "";
    this.core_vendor = "";
    this.score = "";
    this.time = "";
    this.idle_time = 0; // idle time only computed for lmscomkpath
    
    this.owner = null;  // owner window of this lmscom
    this.guid = null;   // guid of associated asset

    this.session_active = false;
    this.bigsco = false;    // executing in a big sco, so asset status stored differently

    if (parent != null) {
        this.Copy(parent);
        this.ParentLmsCom = parent; 
    } 

    this.object_type_name = "LmsComBase";
}

LmsComBase.prototype.GetOrdinalNumber = function() {
    return this.ordinal_number;
}

LmsComBase.prototype.SetOrdinalNumber = function(ordnum) {
    this.ordinal_number = ordnum;
}

/* Copies just that invarient information.  Allows child 
   pages to report on student info if they need to. */ 
LmsComBase.prototype.Copy = function(from) {

    this.student_id = from.student_id;
    this.student_name = from.student_name;
    this.credit = from.credit;
    this.lesson_status = from.lesson_status;
    this.bigsco = from.bigsco;
    this.lesson_data = from.lesson_data;
    this.lesson_location = from.lesson_location;
}

/* Starts a session.  For LmsComBase, all this does is
   records the start time. */ 
LmsComBase.prototype.Begin = function() {
    this.start_date = new Date().getTime();

    if (this.session_active)
        alert(R_lmscom_already_active);

    this.session_active = true; 
       
    return true;
}

/* Ends a session.  For LmsComBase, all this does is
   records the end time. */ 
LmsComBase.prototype.End = function() {

    if (!this.session_active)
        alert(R_lmscom_inactive);

    this.end_date = new Date().getTime();
    this.session_active = false;
 
    return true;
}

/* Load the SCORM API adapter if needed and save reference to it. */
LmsComBase.prototype.LoadAPIAdapter = function (callback) {
    //setTimeout(callback,1);
    // Above timeout caused mode launches to hang on ipad. Apparently it isn't cross-tab
    // execution that is blocked, but only the timer thread in inactive tabs.
    callback();
}

/* Sends completion status to the LMS. This is factored out of LmsCom.End() so
    that completion information may be sent immediately to allow the LMS to
    update any visual feedback. */
LmsComBase.prototype.SendCompletionInfo = function() {}

/* Notifies parent lmscom to roll up the status of this lmscom */
LmsComBase.prototype.NotifyParent = function() {
    var parentlmscom = this.ParentLmsCom;
    if (parentlmscom && !parentlmscom.owner.closed && parentlmscom.owner.ListenChildClose)
        parentlmscom.owner.ListenChildClose();
}

LmsComBase.prototype.getReportedLessonStatus = function() {
    if (this.lesson_status === LMS_PASSED)
        return LmsConfig.ReportOnPass;
    else if (this.lesson_status === LMS_FAILED)
        return LmsConfig.ReportOnFail;
    else
        return this.lesson_status;
}
/* Internal helper method that computes elapse time in 
   seconds. */
LmsComBase.prototype.computeTime = function(bdate, edate) {
    var elapsedSeconds = ((edate - bdate - this.idle_time) / 1000);
    return this.convertTotalSeconds(elapsedSeconds);
}

/* Internal helper method that converts date/time into
   seconds. */
LmsComBase.prototype.convertTotalSeconds = function(ts) {
    var sec = (ts % 60);
    ts -= sec;
    var tmp = (ts % 3600);  //# of seconds in the total # of minutes
    ts -= tmp;              //# of seconds in the total # of hours
    // convert seconds to conform to CMITimespan type (e.g. SS.00)
    sec = Math.round(sec * 100) / 100;
    var strSec = new String(sec);
    var strWholeSec = strSec;
    var strFractionSec = "";
    if (strSec.indexOf(".") != -1) {
        strWholeSec = strSec.substring(0, strSec.indexOf("."));
        strFractionSec = strSec.substring(strSec.indexOf(".") + 1, strSec.length);
    }
    if (strWholeSec.length < 2) {
        strWholeSec = "0" + strWholeSec;
    }
    strSec = strWholeSec;
    if ((ts % 3600) != 0)
        var hour = 0;
    else var hour = (ts / 3600);
    if ((tmp % 60) != 0)
        var min = 0;
    else var min = (tmp / 60);
    if ((new String(hour)).length < 2)
        hour = "0" + hour;
    if ((new String(min)).length < 2)
        min = "0" + min;
    var rtnVal = hour + ":" + min + ":" + strSec;
    return rtnVal;
}

// Get current bookmark. This is only needed for a TOC that is called via lmstart
// but not from an LMS. If you open a Big SCO's concept from kp.html and launch
// it, the Big SCO toc will get an lmscombase from the lmstart, but the lmstart
// page doesn't have the toc_hash, so it can't get the bookmark.
// Note that "view outline" from a normal concept does not need this. It replaces
// the lmstart page with the toc, so the toc will end up with an lmscomcookie of
// its own.
LmsComBase.prototype.GetBookmark = function(toc_hash) {
    if (this.ParentLmsCom)
        return this.ParentLmsCom.GetBookmark(toc_hash);
    return 0;
}

// Support for UPK specific functionality. Delegate to parent until an lmscomkpath is found
LmsComBase.prototype.doGetUPKValue = function(name) {
    if (this.ParentLmsCom)
        return this.ParentLmsCom.doGetUPKValue(name);
    return "";
}

LmsComBase.prototype.doSetUPKValue = function(name, value) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.doSetUPKValue(name, value);
}

LmsComBase.prototype.doUPKCommit = function() {
    if (this.ParentLmsCom)
        this.ParentLmsCom.doUPKCommit();
}

/* Record an interaction completion. Only an lmscomkpath will actually do this, so
   a question in the outline will delegate to its parent lmscom (from lmstart). */
LmsComBase.prototype.setInteraction = function(index,qlmscom) {
    if (this.ParentLmsCom)
        return this.ParentLmsCom.setInteraction(index,qlmscom);
}
LmsComBase.prototype.getAnsweredQuestions = function() {
    if (this.ParentLmsCom)
        return this.ParentLmsCom.getAnsweredQuestions();
    return {};
}

LmsComBase.prototype.setObjective = function(index, objective) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.setObjective(index, objective);
}

// sequencing at end of pre/post assessment
LmsComBase.prototype.requestContinue = function() {
    if (this.ParentLmsCom)
        this.ParentLmsCom.requestContinue();
}

/* Indicate if LMS connection is live */
LmsComBase.prototype.IsConnected = function() {
    if (this.ParentLmsCom)
        return this.ParentLmsCom.IsConnected();
    return false;
}

/* This method reads persisted data from LmsCom 
  (primary from lesson_data) and creates a LmsBasicStatus
  object from that. */ 
LmsComBase.prototype.OpenBasicStatus = function() {
    this.status_obj = new LmsBasicStatus();
    this.status_obj.status = this.lesson_status;

    return this.status_obj;
}

/* This method reads persisted data from LmsCom 
   (primary from lesson_data) and creates a LmsTopicStatus
   object from that. */ 
LmsComBase.prototype.OpenTopicStatus = function(lmsModes, playerModes) {
    var fname = "OpenTopicStatus";
    this.status_obj = new LmsTopicStatus();
    this.status_obj.setRequiredMode(lmsModes, playerModes);
    lmslog.addEntry(0,fname,"RequiredMode",this.status_obj.requiredMode);
    this.status_obj.isScored = !!lmsModes["K"];
    
    var availableModes;
    if (GetTopLevelLmsMode() == "LMS")
        availableModes = lmsModes;
    else
        availableModes = playerModes;
    this.status_obj.setModeavail("S", availableModes["S"]);
    this.status_obj.setModeavail("T", availableModes["T"]);
    this.status_obj.setModeavail("K", availableModes["K"]);
    this.status_obj.setModeavail("D", availableModes["D"]);
    this.status_obj.setModeavail("P", availableModes["P"]);
    this.status_obj.setModeavail("E", availableModes["E"]);
    lmslog.addEntry(0, fname, "SeeIt", this.status_obj.getModeavail("S"));
    lmslog.addEntry(0, fname, "TryIt", this.status_obj.getModeavail("T"));
    lmslog.addEntry(0, fname, "KnowIt", this.status_obj.getModeavail("K"));
    lmslog.addEntry(0, fname, "DoIt", this.status_obj.getModeavail("D"));
    lmslog.addEntry(0, fname, "PrintIt", this.status_obj.getModeavail("P"));
    lmslog.addEntry(0, fname, "TestIt", this.status_obj.getModeavail("E"));

    if (this.bigsco) {
        this.status_obj.savedStatus = this.lesson_data.charAt(0);
        this.lesson_data = this.lesson_data.substring(1);
    }
    this.status_obj.initTopicstat(this.lesson_data);
        
    return this.status_obj;
}

// duplicates code for TopicStatus, except available modes are stored differently in
// topic.html than in lmstart.html
LmsComBase.prototype.OpenTopicLaunchStatus = function(mode, lmsModes, playerModes) {
    var fname = "OpenTopicLaunchStatus";

    this.status_obj = new LmsTopicLaunchStatus(mode);
    this.status_obj.setRequiredMode(lmsModes, playerModes);
    lmslog.addEntry(0,fname,"RequiredMode",this.status_obj.requiredMode);
    this.status_obj.isScored = lmsModes.indexOf("K")!=-1;

    var availableModes;
    if (GetTopLevelLmsMode() == "LMS")
        availableModes = lmsModes;
    else
        availableModes = playerModes;
    this.status_obj.setModeavail("S", availableModes.indexOf("S")!=-1);
    this.status_obj.setModeavail("T", availableModes.indexOf("T")!=-1);
    this.status_obj.setModeavail("K", availableModes.indexOf("K")!=-1);
    this.status_obj.setModeavail("D", availableModes.indexOf("D")!=-1);
    this.status_obj.setModeavail("P", availableModes.indexOf("P")!=-1);
    this.status_obj.setModeavail("E", availableModes.indexOf("E")!=-1);
    lmslog.addEntry(0, fname, "SeeIt", this.status_obj.getModeavail("S"));
    lmslog.addEntry(0, fname, "TryIt", this.status_obj.getModeavail("T"));
    lmslog.addEntry(0, fname, "KnowIt", this.status_obj.getModeavail("K"));
    lmslog.addEntry(0, fname, "DoIt", this.status_obj.getModeavail("D"));
    lmslog.addEntry(0, fname, "PrintIt", this.status_obj.getModeavail("P"));
    lmslog.addEntry(0, fname, "TestIt", this.status_obj.getModeavail("E"));

    this.status_obj.initTopicstat(this.lesson_data);
        
    return this.status_obj;
}

/* This method reads persisted data from LmsCom 
   (primary from lesson_data) and creates a 
   LmsQuestionStatus object from that. */ 
LmsComBase.prototype.OpenQuestionStatus = function() {
    this.status_obj = new LmsQuestionStatus();
    this.status_obj.status = LMS_NOT_ATTEMPTED;
    this.status_obj.savedStatus = this.lesson_data ? Stat2Lms(this.lesson_data) : LMS_NOT_ATTEMPTED;
    
    return this.status_obj;
}

/* This method reads persisted data from LmsCom 
   (primary from lesson_data) and creates a 
   LmsAssessmentStatus object from that. */
LmsComBase.prototype.OpenAssessmentStatus = function(itemCount, hash) {
    this.status_obj = new LmsAssessmentStatus();
    this.status_obj.hash = hash;    // save hash for when saving

    var str = this.lesson_data;
    var count;
    var savedhash = null;
    
    if (str) {
        if (!this.bigsco) {
            var index = str.indexOf("@");
            if (index > 0) {
                count = parseInt(str.substring(0, index));
                // if aicc lms (moodle) replaced "+" in hash with " ", put "+" back
                savedhash = str.substring(index+1, index+count+1).replace(/ /g,"+");
                str = str.substring(index+count+1);
            }
        } else
            savedhash = hash;   // to satisfy test below
    }
    
    if (hash === savedhash && str.length === itemCount+1) {         
        this.status_obj.savedStatus = str.charAt(0);
        this.status_obj.status = str.charAt(0) === "I" ? LMS_INCOMPLETE : LMS_NOT_ATTEMPTED;
        for (var i=0; i<itemCount; i++)
            this.status_obj.questionstatus[i] = str.charAt(i+1);
    } else {
        if (str && !this.bigsco) {  // there was data but we need to invalidate
            this.status_obj.stateDiscarded = true;
            this.status_obj.savedStatus = str.charAt(0);
        } else
            this.status_obj.savedStatus = "N";
        this.status_obj.status = LMS_NOT_ATTEMPTED;
        for (var i=0; i<itemCount; i++)
            this.status_obj.questionstatus[i] = "N";
    }    

    return this.status_obj;
}

/* This method reads persisted data from LmsCom 
  (primary from lesson_data) and creates a 
  LmsTOCStatus object from that. */
LmsComBase.prototype.OpenTOCStatus = function(nodecount, tocversion) {
    var tc = new LmsTOCStatus();
    this.status_obj = tc;

    var tocstate = new TOCState(nodecount, tocversion);
    tc.setTocState(tocstate);

    if (this.lesson_data != null && this.lesson_data.length > 0)
        tocstate.DeserializeTOC(this.lesson_data);
    return tc;
}

LmsComBase.prototype.SaveStatus = function() {
    if (this.status_obj)
        this.status_obj.Save(this);
}

// Add methods for communicating to UT (Kpath lite)
LmsComBase.prototype.utGetModeIndex = function() {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utGetModeIndex();
}
LmsComBase.prototype.utPushModeIndex = function() {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utPushModeIndex();
}
LmsComBase.prototype.utPopModeIndex = function() {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utPopModeIndex();
}
LmsComBase.prototype.utRecordType = function(type) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utRecordType(type);
}
LmsComBase.prototype.utRecordStartTime = function(time) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utRecordStartTime(time);
}
LmsComBase.prototype.utRecordEndTime = function(time) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utRecordEndTime(time);
}
LmsComBase.prototype.utRecordCompletionStatus = function(status) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utRecordCompletionStatus(status);
}
LmsComBase.prototype.utRecordSuccessStatus = function(status) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utRecordSuccessStatus(status);
}
LmsComBase.prototype.utRecordScoreScaled = function(score) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utRecordScoreScaled(score);
}
LmsComBase.prototype.utRecordFrameViewed = function(frame) {
    if (this.ParentLmsCom)
        this.ParentLmsCom.utRecordFrameViewed(frame);
}

///////////////////////////////////////
// SCORM 1.2 LmsCom object defintion
///////////////////////////////////////
function LmsComScorm12() {
    this.allow_launch = false;

    this.object_type_name = "LmsComScorm12";
}

LmsComScorm12.prototype = new LmsComBase(); 
LmsComScorm12.prototype.constructor = LmsComScorm12;
LmsComScorm12.prototype.BaseClass = LmsComBase.prototype;

LmsComScorm12.prototype.Begin = function() {
    LmsComScorm12.prototype.BaseClass.Begin.call(this);

    //Initalizes communication with the LMS.
    var fname = "LmsComScorm12.Begin"
    lmslog.addEntry(0, fname, "", "Start");

    //SCORM - Gets all startup parameters from the LMS
    if (this.API == null) {
        this.allow_launch = true;
        return false;
    }
    
    if (this.API.LMSInitialize("") == "false"){
        var err = this.API.LMSGetLastError();
        var errDesc = this.API.LMSGetErrorString(err) + "\n" + this.API.LMSGetDiagnostic("");
        this.API = null;   // flag as disconnected
        lms_ConnectionLost(err + " " + errDesc);
        lmslog.addEntry(0, fname, "", errDesc);
        return false;        
    }

    this.lesson_status = this.original_lesson_status = this.doLMSGetValue("cmi.core.lesson_status");
    this.lesson_data = this.doLMSGetValue("cmi.suspend_data");
    this.lesson_location = this.doLMSGetValue("cmi.core.lesson_location");
    this.student_id = this.doLMSGetValue("cmi.core.student_id");
    this.student_name = this.doLMSGetValue("cmi.core.student_name");
    this.allow_launch = true;

    lmslog.addEntry(0, fname, "", "LMS session started");

    return true;
}

LmsComScorm12.prototype.End = function() {
    LmsComScorm12.prototype.BaseClass.End.call(this);

    //SCORM - Calls LMS to indicate that course session has ended
    var fname = "LmsComScorm12.End";
    lmslog.addEntry(0, fname, "", "Start");

    if (!this.allow_launch)
        return false;

    this.allow_launch = false;
    
    if (this.API == null) {
        return false;
    }

    if (this.lesson_status == LMS_INCOMPLETE)
        this.doLMSSetValue("cmi.core.exit", "suspend");
    else
        this.doLMSSetValue("cmi.core.exit", "");    // GS set this to suspend, too
        
    var sesstime = this.computeTime(this.start_date, this.end_date);
    this.doLMSSetValue("cmi.core.session_time", sesstime);
    // SCORM compliance suite dies if you send it an empty string (like, say, if you
    // wanted to clear out the value)
    if (this.lesson_data)
        this.doLMSSetValue("cmi.suspend_data", this.lesson_data);
    if (this.lesson_location)
        this.doLMSSetValue("cmi.core.lesson_location", this.lesson_location);

    this.SendCompletionInfo(true);
        
    if (this.API && this.API.LMSFinish("") == "false") {
        var err = this.API.LMSGetLastError();
        var errDesc = this.API.LMSGetErrorString(err) + "\n" + this.API.LMSGetDiagnostic("");
        this.API = null;   // flag as disconnected
        lms_ConnectionLost(err + " " + errDesc);
        lmslog.addEntry(0, fname, "", errDesc);
        return false;        
    }
    
    this.API = null;  // 13102364 - prevents errors from get/set if window close occurs before page callback
    
    lmslog.addEntry(0, fname, "", "LMS session terminated");

    return true;
}

/* Sends completion status to the LMS. This is factored out of LmsCom.End() so
    that completion information may be sent immediately to allow the LMS to
    update any visual feedback. "not attempted" is sent as "incomplete" because
    the SCORM1.2 spec can be interpreted to make "not attempted" an illegal value
    to set */
LmsComScorm12.prototype.SendCompletionInfo = function(isEnding) {
    if (this.lesson_status === LMS_NOT_ATTEMPTED) {
        if (this.original_lesson_status === LMS_NOT_ATTEMPTED)
            this.doLMSSetValue("cmi.core.lesson_status", LMS_INCOMPLETE);
        else
            this.doLMSSetValue("cmi.core.lesson_status", this.original_lesson_status);
    } else
        this.doLMSSetValue("cmi.core.lesson_status", this.getReportedLessonStatus());
    
    if (this.score !== "") {
        this.doLMSSetValue("cmi.core.score.raw", this.score);
        this.doLMSSetValue("cmi.core.score.min", "0");
        this.doLMSSetValue("cmi.core.score.max", "100");
    }
    if (!isEnding)
        this.doLMSCommit();
}

/* Load the SCORM API adapter if needed and save reference to it. */
LmsComScorm12.prototype.LoadAPIAdapter = function(callback) {
    this.API = null
    if (GetLmsComFactory())
        this.API = GetLmsComFactory().scorm_api_12;
    callback();
}

/* Indicate if LMS connection is live */
LmsComScorm12.prototype.IsConnected = function() {
    return this.API != null;
}

// SCORM adapter definitions

LmsComScorm12.prototype.ErrorCodes = {
        NoError : 0,
        GeneralException : 101,
        ElementCannotHaveChildren : 202,
        ElementNotAnArray : 203,
        NotInitialized : 301,
        NotImplemented : 401,
        InvalidSetValue : 402,
        ElementIsReadOnly : 403,
        ElementIsWriteOnly : 404,
        IncorrectDataType : 405
    };

LmsComScorm12.prototype.doLMSGetValue = function(name) {
    var fname = "doLMSGetValue";
    if (this.API == null) {
        return "";
    }
    
    var value = this.API.LMSGetValue(name);
    var err = this.API.LMSGetLastError();
    if (err != this.ErrorCodes.NoError) {
        var errDesc = this.API.LMSGetErrorString(err);
        lms_ConnectionLost(err + " " + errDesc + ", " + name);
        lmslog.addEntry(0,fname,"",R_scorm_getvalfail + name + " " + errDesc);
        return "";
    }
    
    lmslog.addEntry(1,fname,name,value);
    return value;
}

LmsComScorm12.prototype.doLMSSetValue = function(name, value) {
    var fname = "doLMSSetValue";
    if (this.API == null) {
        return "false";
    }
    
    if (this.API.LMSSetValue(name, value) == "false") {
        var err = this.API.LMSGetLastError();
        if (err != this.ErrorCodes.NoError && err != this.ErrorCodes.NotImplemented) {
            var errDesc = this.API.LMSGetErrorString(err);
            lms_ConnectionLost(err + " " + errDesc + ", " + name + ", " + value);
            lmslog.addEntry(0,fname,"",R_scorm_setvalfail + name + ":" + value + " " + errDesc);
            return "false";
        }
    }
    
    lmslog.addEntry(1,fname,name,value);
    return "true";
}

LmsComScorm12.prototype.doLMSCommit = function() {
    var fname = "doLMSCommit";
    if (this.API == null) {
        return "false";
    }
    
    if (this.API.LMSCommit("") == "false") {    // is commit failure a drop?
        var err = this.API.LMSGetLastError();
        var errDesc = this.API.LMSGetErrorString(err);
        lms_ConnectionLost(err + " " + errDesc);
        lmslog.addEntry(0, fname, "", errDesc);
        this.API = null;
        return "false";        
    }
    
    lmslog.addEntry(1,fname,"","");
    return "true";
}

///////////////////////////////////////
// SCORM 1.3 (SCORM2004) LmsCom object defintion
///////////////////////////////////////
function LmsComScorm2004() {
    this.allow_launch = false;
    this.object_type_name = "LmsComScorm2004";
    this.lesson_data_location = "cmi.suspend_data"; 
}

LmsComScorm2004.prototype = new LmsComBase();
LmsComScorm2004.prototype.constructor = LmsComScorm2004;
LmsComScorm2004.prototype.BaseClass = LmsComBase.prototype;

LmsComScorm2004.prototype.Begin = function() {
    LmsComScorm2004.prototype.BaseClass.Begin.call(this);

    //Initalizes communication with the LMS.
    var fname = "LmsComScorm2004.Begin"
    lmslog.addEntry(0, fname, "", "Start");

    //SCORM - Gets all startup parameters from the LMS
    if (this.API == null) {
        this.allow_launch = true;
        return false;
    }
    
    if (this.API.Initialize("") == "false"){
        var err = this.API.GetLastError();
        var errDesc = this.API.GetErrorString(err) + "\n" + this.API.GetDiagnostic("");
        this.API = null;   // flag as disconnected
        lms_ConnectionLost(err + " " + errDesc);
        lmslog.addEntry(0, fname, "", errDesc);
        return false;        
    }

    this.lesson_status = this.doGetValue("cmi.completion_status");
    if (this.lesson_status === "unknown") {
        this.lesson_status = LMS_NOT_ATTEMPTED;
    } else if (this.lesson_status === LMS_COMPLETED) {
        var success_status = this.doGetValue("cmi.success_status");
        if (success_status === LMS_PASSED || success_status === LMS_FAILED)
            this.lesson_status = success_status;
    }
    this.original_lesson_status = this.lesson_status;
    this.lesson_data = this.doGetValue(this.lesson_data_location);
    this.lesson_location = this.doGetValue("cmi.location");
    this.student_id = this.doGetValue("cmi.learner_id");
    this.student_name = this.doGetValue("cmi.learner_name");
    this.allow_launch = true;

    lmslog.addEntry(0, fname, "", "LMS session started");

    return true;
}

LmsComScorm2004.prototype.End = function() {
    LmsComScorm2004.prototype.BaseClass.End.call(this);

    //SCORM - Calls LMS to indicate that course session has ended
    var fname = "LmsComScorm2004.End";
    lmslog.addEntry(0, fname, "", "Start");

    if (!this.allow_launch)
        return false;

    this.allow_launch = false;

    if (this.API == null) {
        return false;
    }
    
    if (this.lesson_status == LMS_INCOMPLETE)
        this.doSetValue("cmi.exit", "suspend");
    else
        this.doSetValue("cmi.exit", "normal");

    var sesstime = this.computeTime(this.start_date, this.end_date);
    this.doSetValue("cmi.session_time", sesstime);
    // SCORM compliance suite dies if you send it an empty string (like, say, if you
    // wanted to clear out the value)
    if (this.lesson_data)
        this.doSetValue(this.lesson_data_location, this.lesson_data);
    if (this.lesson_location)
        this.doSetValue("cmi.location", this.lesson_location);

    this.SendCompletionInfo(true);
     
    if (this.API && this.API.Terminate("") == "false") {
        var err = this.API.GetLastError();
        var errDesc = this.API.GetErrorString(err) + "\n" + this.API.GetDiagnostic("");
        this.API = null;   // flag as disconnected
        lms_ConnectionLost(err + " " + errDesc);
        lmslog.addEntry(0, fname, "", errDesc);
        return false;        
    }
    
    this.API = null;  // 13102364 - prevents errors from get/set if window close occurs before page callback
    
    lmslog.addEntry(0, fname, "", "LMS session terminated");

    return true;
}

/* Load the SCORM API adapter if needed and save reference to it. */
LmsComScorm2004.prototype.LoadAPIAdapter = function(callback) {
    this.API = null
    if (GetLmsComFactory())
        this.API = GetLmsComFactory().scorm_api_2004;
    callback();
}

/* Sends completion status to the LMS. This is factored out of LmsCom.End() so
    that completion information may be sent immediately to allow the LMS to
    update any visual feedback. */
LmsComScorm2004.prototype.SendCompletionInfo = function(isEnding) {
    var lesson_status = this.getReportedLessonStatus();
    if (lesson_status === LMS_NOT_ATTEMPTED)
        lesson_status = this.original_lesson_status;
    // split scorm1.2/aicc completion into scorm2004 values
    // maybe it would be better to hold them in the scorm2004 manner and join
    // for aicc/scorm1.2
    if (lesson_status == LMS_PASSED || lesson_status == LMS_FAILED) {
        this.doSetValue("cmi.success_status", lesson_status);
        this.doSetValue("cmi.completion_status", LMS_COMPLETED);
    } else
        this.doSetValue("cmi.completion_status", lesson_status);

    if (this.score !== "") {
        this.doSetValue("cmi.score.raw", this.score);
        this.doSetValue("cmi.score.scaled", this.score / 100);
        this.doSetValue("cmi.score.min", "0");
        this.doSetValue("cmi.score.max", "100");
    }
    if (!isEnding)
        this.doCommit();
}

/* Internal helper method that converts date/time into
   seconds. This version generates a 1.3 compliant (second,10,2) result */
LmsComScorm2004.prototype.convertTotalSeconds = function(ts) {
    var sec = (ts % 60);
    ts -= sec;
    var tmp = (ts % 3600);  //# of seconds in the total # of minutes
    ts -= tmp;              //# of seconds in the total # of hours
    // convert seconds to conform to CMITimespan type (e.g. SS.00)
    sec = Math.round(sec * 100) / 100;
    var strSec = new String(sec);
    var strWholeSec = strSec;
    var strFractionSec = "";
    if (strSec.indexOf(".") != -1) {
        strWholeSec = strSec.substring(0, strSec.indexOf("."));
        strFractionSec = strSec.substring(strSec.indexOf(".") + 1, strSec.length);
    }
    if (strWholeSec.length < 2) {
        strWholeSec = "0" + strWholeSec;
    }
    strSec = strWholeSec;
    if ((ts % 3600) != 0)
        var hour = 0;
    else var hour = (ts / 3600);
    if ((tmp % 60) != 0)
        var min = 0;
    else var min = (tmp / 60);
    if ((new String(hour)).length < 2)
        hour = "0" + hour;
    if ((new String(min)).length < 2)
        min = "0" + min;
    var rtnVal = "PT" + hour + "H" + min + "M" + strSec + "S";
    return rtnVal;
}

/* Indicate if LMS connection is live */
LmsComScorm2004.prototype.IsConnected = function() {
    return this.API != null;
}

// SCORM adapter definitions

LmsComScorm2004.prototype.ErrorCodes = {
        NoError : 0,
        GeneralException : 101,
        GeneralInitializationFailure : 102,
        AlreadyInitialized : 103,
        ContentInstanceTerminated : 104,
        GeneralTerminationFailure : 111,
        TerminationBeforeInitialization : 112,
        TerminationAfterTermination : 113,
        RetrieveDataBeforeInitialization : 122,
        RetrieveDataAfterTermination : 123,
        StoreDataBeforeInitialization : 132,
        StoreDataAfterTermination : 133,
        CommitBeforeInitialization : 142,
        CommitAfterTermination : 143,
        GeneralArgumentError : 201,
        GeneralGetFailure : 301,
        GeneralSetFailure : 351,
        GeneralCommitFailure : 391,
        UndefinedDataModelElement : 401,
        UnimplementedDataModelElement : 402,
        DataModelElementValueNotInitialized : 403,
        DataModelElementIsReadOnly : 404,
        DataModelElementIsWriteOnly : 405,
        DataModelElementTypeMismatch : 406,
        DataModelElementValueOutOfRange : 407,
        DataModelDependencyNotEstablished : 408,
        
        KPathTimeout : 1501
    };

LmsComScorm2004.prototype.doGetValue = function(name) {
    var fname = "doGetValue";
    if (this.API == null) {
        return "";
    }
    
    var value = this.API.GetValue(name);
    var err = this.API.GetLastError();
    if (err != this.ErrorCodes.NoError && err != this.ErrorCodes.DataModelElementValueNotInitialized) {
        if (err == this.ErrorCodes.KPathTimeout && this.object_type_name == "LmsComKPath") {
            lmslog.addEntry(0,fname,"","KCenter timeout");
            var idle = this.API.GetValue("upk.idle_time");
            lmslog.addEntry(0,fname,"upk.idle_time",idle);
            this.idle_time += idle;
            lmslog.addEntry(0,fname,"idle_time",this.idle_time);
            return this.doGetValue(name);  // redo the call
        } else {            
            var errDesc = this.API.GetErrorString(err);
            lms_ConnectionLost(err + " " + errDesc + ", " + name);
            lmslog.addEntry(0,fname,"",R_scorm_getvalfail + name + " " + errDesc);
            return "";
        }
    }
    
    lmslog.addEntry(1,fname,name,value);
    return value;
}

LmsComScorm2004.prototype.doSetValue = function(name, value) {
    var fname = "doSetValue";
    if (this.API == null) {
        return "false";
    }
    
    if (this.API.SetValue(name, value) == "false") {
        var err = this.API.GetLastError();
        if (err != this.ErrorCodes.NoError && err != this.ErrorCodes.UnimplementedDataModelElement) {
            if (err == this.ErrorCodes.KPathTimeout && this.object_type_name == "LmsComKPath") {
                lmslog.addEntry(0,fname,"","KCenter timeout");
                var idle = this.API.GetValue("upk.idle_time");
                lmslog.addEntry(0,fname,"upk.idle_time",idle);
                this.idle_time += idle;
                lmslog.addEntry(0,fname,"idle_time",this.idle_time);
                return this.doSetValue(name, value);
            } else {          
                var errDesc = this.API.GetErrorString(err);
                lms_ConnectionLost(err + " " + errDesc + ", " + name + ", " + value);
                lmslog.addEntry(0,fname,"",R_scorm_setvalfail + name + ":" + value + " " + errDesc);
                return "false";
            }
        }
    }
//alert(fname+":"+name+":"+value);
    lmslog.addEntry(1,fname,name,value);
    return "true";
}

LmsComScorm2004.prototype.doCommit = function() {
    var fname = "doCommit";
    if (this.API == null) {
        return "false";
    }
    
    if (this.API.Commit("") == "false") {
        var err = this.API.GetLastError();
        var errDesc = this.API.GetErrorString(err);
        if (err == this.ErrorCodes.KPathTimeout && this.object_type_name == "LmsComKPath") {
            lmslog.addEntry(0,fname,"","KCenter timeout");
            var idle = this.API.GetValue("upk.idle_time");
            lmslog.addEntry(0,fname,"upk.idle_time",idle);
            this.idle_time += idle;
            lmslog.addEntry(0,fname,"idle_time",this.idle_time);
            return this.doCommit();
        } else {
            this.API = null;   // flag as disconnected
            lms_ConnectionLost(err + " " + errDesc);
            lmslog.addEntry(0, fname, "", errDesc);
            return "false";
        }        
    }
    
    lmslog.addEntry(1,fname,"","");
    return "true";
}


///////////////////////////////////////
// Knowledge Pathways LmsCom object defintion
///////////////////////////////////////
function LmsComKPath(parent) {
    this.allow_launch = false;

    if (parent != null) {
        this.Copy(parent);
        this.ParentLmsCom = parent; 
    } 

    this.object_type_name = "LmsComKPath";
    this.lesson_data_location = "upk.sco_data"; 
}

LmsComKPath.prototype = new LmsComScorm2004();
LmsComKPath.prototype.constructor = LmsComKPath;
LmsComKPath.prototype.BaseClass = LmsComScorm2004.prototype;

LmsComKPath.prototype.Begin = function() {
    var fname = "LmsComKPath.Begin"
    lmslog.addEntry(0, fname, "", "Start");
    var result = LmsComKPath.prototype.BaseClass.Begin.call(this);
    this.doSetValue("upk.launch_from", GetTopLevelLmsMode());
    lmslog.addEntry(0, fname, "", "LMS session started");
    return result;
}

/* Sends completion status to the LMS. This is factored out of LmsCom.End() so
    that completion information may be sent immediately to allow the LMS to
    update any visual feedback. Unlike the other lmscom types, we want to send
    LMS_NOT_ATTEMPTED to kpath if no new attempt is made */
LmsComKPath.prototype.SendCompletionInfo = function(isEnding) {
    var lesson_status = this.getReportedLessonStatus();
    if (lesson_status === LMS_NOT_ATTEMPTED) {
        this.doSetValue("cmi.completion_status", LMS_NOT_ATTEMPTED);
        return;
    }
    // split scorm1.2/aicc completion into scorm2004 values
    // maybe it would be better to hold them in the scorm2004 manner and join
    // for aicc/scorm1.2
    if (lesson_status == LMS_PASSED || lesson_status == LMS_FAILED) {
        this.doSetValue("cmi.success_status", lesson_status);
        this.doSetValue("cmi.completion_status", LMS_COMPLETED);
    } else
        this.doSetValue("cmi.completion_status", lesson_status);

    if (this.score !== "") {
        this.doSetValue("cmi.score.raw", this.score);
        this.doSetValue("cmi.score.scaled", this.score / 100);
        this.doSetValue("cmi.score.min", "0");
        this.doSetValue("cmi.score.max", "100");
    }
    if (!isEnding)
        this.doCommit();
}

/* Load the SCORM API adapter if needed and save reference to it. */
LmsComKPath.prototype.LoadAPIAdapter = function(callback) {
    if (!this.API) {    // don't overwrite previously set adapter
        var apiframe = findKPathAPIFrame(window);
        if (apiframe && apiframe.LoadRuntime && this.guid) {
            this.deferred_callback = callback;
            var that = this;
            apiframe.LoadRuntime(this.guid, 0, 0, 0, function(s,g,a,e){that.LoadAPIAdapterCallback(s,g,a,e)});
        } else {
            callback();
        }
    } else
        callback();
}

LmsComKPath.prototype.LoadAPIAdapterCallback = function(succeeded, guid, APIControl, ErrorMessage) {
    if (succeeded == "succeeded" && guid == this.guid) {
        this.API = APIControl.GetAPI();
        lmslog.addEntry(0, "LoadAPIAdapterCallback", "", "KPath adapter bound");
        try {
            this.deferred_callback();
        } catch (e) { } // catch case where we cycle quickly through the toc & lmscom page closed before API callback runs
    } else if (succeeded == "no SCO") {
        this.API = null;    // fall back to lmscombase functionality
        lmslog.addEntry(0,"LoadAPIAdapterCallback","",ErrorMessage);
        this.deferred_callback();
    } else {
        alert(R_scorm_noapi + " " + ErrorMessage);
        lmslog.addEntry(0,"LoadAPIAdapterCallback","",ErrorMessage);
        this.deferred_callback();
    }
}

LmsComKPath.prototype.doGetUPKValue = function(name) {
    var ret = this.doGetValue(name);
    if (ret === "")
        ret = -1;
    return ret;
}

LmsComKPath.prototype.doSetUPKValue = function(name, value) {
    this.doSetValue(name, value);
}

LmsComKPath.prototype.doUPKCommit = function() {
    this.doCommit();
}

// Record an interaction completion.
LmsComKPath.prototype.setInteraction = function(index,qlmscom) {
    if (!this.API)  // if running in "lmscombase mode"
        return;
        
    var statobj = qlmscom.status_obj;
    var count = this.doGetValue("cmi.interactions._count");
    if (index == -1) index = count;
    if (index >= count)
        this.doSetValue("cmi.interactions."+index+".id",qlmscom.guid);
    this.doSetValue("cmi.interactions."+index+".type",statobj.getQuestionType());
    this.doSetValue("cmi.interactions."+index+".timestamp",(new Date()).toSCORM());
    this.doSetValue("cmi.interactions."+index+".weighting","1");
    if (statobj.getResult()) {
        this.doSetValue("cmi.interactions."+index+".learner_response",statobj.getLearnerResponse());
        this.doSetValue("cmi.interactions."+index+".result",statobj.getResult());
    }
    this.doCommit();
    return index;
}

LmsComKPath.prototype.getAnsweredQuestions = function() {
    var answeredQuestions = {};
    if (!this.API)
        return answeredQuestions;
        
    var count = this.doGetValue("cmi.interactions._count");
    for (var i=0; i<count; i++) {
        var id = this.doGetValue("cmi.interactions." + i + ".id");
        answeredQuestions[id] = { index: i };
        answeredQuestions[id].weighting = this.doGetValue("cmi.interactions." + i + ".weighting");
        answeredQuestions[id].result = this.doGetValue("cmi.interactions." + i + ".result");
    }
    return answeredQuestions;
}

LmsComKPath.prototype.setObjective = function(index, objective) {
    if (this.API) {
        var objectiveID = objective.objectiveGuid == "PRIMARYOBJ" ? "PRIMARYOBJ" : "OBJ_" + objective.objectiveGuid; 
        this.doSetValue("cmi.objectives."+index+".id", objectiveID);
        this.doSetValue("cmi.objectives."+index+".score.scaled", objective.score/100);
        this.doSetValue("cmi.objectives."+index+".completion_status", objective.completed ? "completed" : "incomplete");
        this.doSetValue("cmi.objectives."+index+".success_status", objective.completed ? "passed" : "failed");
    }
}

// sequencing at end of pre/post assessment
LmsComKPath.prototype.requestContinue = function() {
    this.doSetValue("adl.nav.request","continue");
}

// Add methods for communicating to UT (Kpath lite)
LmsComKPath.prototype.utGetModeIndex = function() {
    this.mode_index = this.doGetValue("upk.modes._count");
}
// single entry stack for ut tracking seeit/tryit/printit from doit
LmsComKPath.prototype.utPushModeIndex = function() {
    this.saved_mode_index = this.mode_index;
    this.utGetModeIndex();
}
LmsComKPath.prototype.utPopModeIndex = function() {
    this.mode_index = this.saved_mode_index;
    delete this.saved_mode_index;
}
LmsComKPath.prototype.utRecordType = function(type) {
    this.doSetValue("upk.modes." + this.mode_index + ".type", type);
}
LmsComKPath.prototype.utRecordStartTime = function(time) {
    this.doSetValue("upk.modes." + this.mode_index + ".start_time",time.toSCORM());
}
LmsComKPath.prototype.utRecordEndTime = function(time) {
    this.doSetValue("upk.modes." + this.mode_index + ".end_time",time.toSCORM());
}
LmsComKPath.prototype.utRecordCompletionStatus = function(status) {
    this.doSetValue("upk.modes." + this.mode_index + ".completion_status",status);
}
LmsComKPath.prototype.utRecordSuccessStatus = function(status) {
    this.doSetValue("upk.modes." + this.mode_index + ".success_status",status);
}
LmsComKPath.prototype.utRecordScoreScaled = function(score) {
    this.doSetValue("upk.modes." + this.mode_index + ".score.scaled",score);
}
LmsComKPath.prototype.utRecordFrameViewed = function(frame) {
    this.doSetValue("upk.modes." + this.mode_index + ".frame_viewed",frame);
    var sesstime = this.computeTime(this.start_date, new Date().getTime());
    this.doSetValue("cmi.session_time", sesstime);
    this.doCommit();
}

///////////////////////////////////////
// AICC LmsCom object defintion
///////////////////////////////////////
function LmsComAICC(aicc_url,aicc_sid) {
    this.allow_launch = false;

    this.aicc_url = aicc_url;
    this.aicc_sid = aicc_sid;
    this.app = document.applets.GetHTTPPostData;
    
    this.object_type_name = "LmsComAICC";
}

LmsComAICC.prototype = new LmsComBase(); 
LmsComAICC.prototype.constructor = LmsComScorm12;
LmsComAICC.prototype.BaseClass = LmsComBase.prototype;

LmsComAICC.prototype.Begin = function() {
    LmsComAICC.prototype.BaseClass.Begin.call(this);

    //Initalizes communication with the LMS.
    var fname = "LmsComAICC.Begin"
    lmslog.addEntry(0, fname, "", "Start");

    this.hacpGetparam();
    
    lmslog.addEntry(0, fname, "", "about to log paramvalues");
}

LmsComAICC.prototype.End = function() {
    LmsComAICC.prototype.BaseClass.End.call(this);

    var fname = "LmsComAICC.End";
    lmslog.addEntry(0, fname, "", "Start");

    if (!this.allow_launch)
        return false;

    this.allow_launch = false;
    
	var NewAiccData = this.hacpGetpostdata();
	var params = "command=putparam&version=" + LmsConfig.AiccVersion + "&session_id=" + this.aicc_sid + "&aicc_data=" + escape(NewAiccData) + "&";
	lmslog.addEntry(0,fname,"params",params);
	var strData = this.app.GetData(unescape(this.aicc_url),params)
	lmslog.addEntry(0,fname,"strData",strData);
	params = "version=" + LmsConfig.AiccVersion + "&command=ExitAU&session_id=" + this.aicc_sid + "&";
	lmslog.addEntry(0,fname,"params",params);
	strData = this.app.GetData(unescape(this.aicc_url),params)
	lmslog.addEntry(0,fname,"strData",strData);
}

// stolen from lmsfunctions.js
var closingAmp = true;  // huh?

LmsComAICC.prototype.hacpGetparam = function() {
	//AICC - Gets startup parameters from the LMS
	var fname="hacpGetparam";
	lmslog.addEntry(0,fname,"","Start");
	var strData="";
	var params;
	params = "version=" + LmsConfig.AiccVersion + "&command=GetParam&session_id=" + this.aicc_sid;
	if (closingAmp)
		params = params + "&";
	lmslog.addEntry(0,fname,"params",params);
	strData = this.app.GetData(unescape(this.aicc_url),params)
	lmslog.addEntry(0,fname,"strData",strData);
	var lessonStatus;
	var lessonFlag;
	var ErrorNum;
	var ErrorText;
	var IsValid = false;
	strData += " ";
	var strArgs = strData.split("\r");
	for (var i=0; i<strArgs.length; i++) {
		var strArg = strArgs[i];
		var tag = trimValue(strArg.substring( 0, strArg.indexOf( "=" ) ));
        var val = trimValue(strArg.substring( strArg.indexOf( "=" ) + 1 ));
		if (tag.toLowerCase() == "error") {
			ErrorNum = val;
			IsValid = true;
		}
		if (tag.toLowerCase() == "error_text") {
			ErrorText = val;
		}
		if (tag.toLowerCase() == "aicc_data") {
			this.aicc_data = strData.substring(strData.indexOf(strArg.substring( 0, strArg.indexOf( "=" ) )) + strArg.substring( 0, strArg.indexOf( "=" ) ).length + 1);
			IsValid = true;
		}
	}
	if (IsValid) {
		if (ErrorNum == 0) {
			// successful
			var CoreData;
			CoreData = get_group_content("core", this.aicc_data);
			var strArgs = CoreData.split("\r");
			for (var i=0; i<strArgs.length; i++) {
				var strArg = strArgs[i];
				var tag = trimValue(strArg.substring( 0, strArg.indexOf( "=" ) ));
	            var val = trimValue(strArg.substring( strArg.indexOf( "=" ) + 1 ));
				if (tag.toLowerCase() == "student_id") {
					this.student_id = val;
				}
				if (tag.toLowerCase() == "student_name") {
					this.student_name = val;
//					this.splitStudentname(val);				
				}
				if (tag.toLowerCase() == "lesson_status") {
					this.lesson_status = val.toLowerCase().charAt(0);
					if (val.indexOf(",")!=-1)
						this.lesson_flag = trimValue(val.substring( val.indexOf( "," ) + 1 )).toLowerCase();
					//map abreviated flags
					if (this.lesson_status == "p")
						this.lesson_status = LMS_PASSED;
					if (this.lesson_status == "c")
						this.lesson_status = LMS_COMPLETED;
					if (this.lesson_status == "f")
						this.lesson_status = LMS_FAILED;
					if (this.lesson_status == "i")
						this.lesson_status = LMS_INCOMPLETE;
					if (this.lesson_status == "n")
						this.lesson_status = LMS_NOT_ATTEMPTED;
					this.original_lesson_status = this.lesson_status;
				}
				if (tag.toLowerCase() == "lesson_location") {
					this.lesson_location = val;
				}
				if (tag.toLowerCase() == "credit") {
					this.credit = val;
				}
				if (tag.toLowerCase() == "score") {
					this.score = val;
				}
				if (tag.toLowerCase() == "time") {
					this.time = val;
				}
			}
			if (this.lesson_status == LMS_INCOMPLETE || 
			    this.lesson_status == LMS_COMPLETED || 
			    this.lesson_status == LMS_PASSED || 
			    this.lesson_status == LMS_FAILED
			    ) {
				this.lesson_data = trimValue(get_group_content("core_lesson", this.aicc_data));
			}
			else {
				this.lesson_data = "";
			}
			this.core_vendor = trimValue(get_group_content("core_vendor", this.aicc_data));
			//startTimer();
			this.allow_launch = true;
		}
		else {
			// unsuccessful, display error and do not launch
			alert(R_error_unexp + ErrorText);
			lmslog.addEntry(0,fname,"","Unable to continue because of the following error: " + ErrorText);
		}
	}
	else {
		alert(R_error_svr + unescape(this.aicc_url) + "\r\r - " + strData);
		lmslog.addEntry(0,fname,"","Unable to post to server " + unescape(this.aicc_url) + " - " + strData);
	}
}

LmsComAICC.prototype.hacpGetpostdata = function() {
	//AICC - Builds the AICC message string for passing to the LMS
	var fname = "hacpGetpostdata";
	lmslog.addEntry(0,fname,"","Start");
	var NewAiccData="";
	NewAiccData = "[CORE]\r\n";
	NewAiccData += "Lesson_Location=" + "\r\n";
	var lesson_status = this.getReportedLessonStatus();
	if (lesson_status === LMS_NOT_ATTEMPTED)
        lesson_status = this.original_lesson_status;
	if (this.lesson_status === LMS_INCOMPLETE) {
		NewAiccData += "Lesson_Status=" + lesson_status + ", suspend\r\n";
	}
	else {
		NewAiccData += "Lesson_Status=" + lesson_status + "\r\n";
	}
	lmslog.addEntry(0,fname,"is_assess",this.is_assess);
	if (this.score !== "") {
		NewAiccData += "Score=" + this.score + "\r\n";
	} else {
		NewAiccData += "Score=\r\n";
	}
	NewAiccData += "Time=" + this.computeTime(this.start_date, this.end_date) + "\r\n";
	NewAiccData += "[CORE_LESSON]\r\n";
	NewAiccData += this.lesson_data + "\r\n";
	lmslog.addEntry(0,fname,"NewAiccData",NewAiccData);
	return NewAiccData;
}

function get_group_content(section, buffer) {
	var contents = "";
	var strArgs = buffer.split("\r");
	var foundSection = false;
	for (var i=0; i<strArgs.length; i++) {
		var line = trimValue(strArgs[i]);
		if (line.substr(0,1) == "[") {
			if (line.toLowerCase().indexOf("[" + section.toLowerCase() + "]") >= 0) {
				foundSection = true;
			}
			else {
				foundSection = false;
			}
		}
		else {
			if (foundSection) {
				contents += line + "\r\n";
			}
		}
	}
	return contents;
}

function trimValue(Val) {
	var strval;
	var startPos = 0;
	var endPos = Val.length;
    for (var i=0; i<Val.length; i++) {
		// space, tab, lf, cr
	   if ((Val.substr(i,1) != " ") && (Val.substr(i,1) != "\u0009") && (Val.substr(i,1) != "\u000A") && (Val.substr(i,1) != "\u000D")) {
	   	startPos = i;
		break;
	   }
	}
	if (i == Val.length)
	   return "";
    for (var i=Val.length-1; i>0; i--) {
		// space, tab, lf, cr
	   if ((Val.substr(i,1) != " ") && (Val.substr(i,1) != "\u0009") && (Val.substr(i,1) != "\u000A") && (Val.substr(i,1) != "\u000D")) {
	   	endPos = i;
		break;
	   }
	}
	if (i == 0)
	   endPos = 0;
	return Val.substring(startPos, endPos + 1);
}

/* Indicate if LMS connection is live */
LmsComAICC.prototype.IsConnected = function() {
    return true;    // what does it mean to be disconnected from an AICC LMS?
}

///////////////////////////////////////
// Cookie based LmsCom object defintion
///////////////////////////////////////
function LmsComCookie() {
    this.allow_launch = false;

    this.object_type_name = "LmsComCookie";
}

LmsComCookie.prototype = new LmsComBase();
LmsComCookie.prototype.constructor = LmsComCookie;
LmsComCookie.prototype.BaseClass = LmsComBase.prototype;

LmsComCookie.prototype.Begin = function() {
    LmsComCookie.prototype.BaseClass.Begin.call(this);
    if (this.toc_hash = window.toc_hash) {  // assignment intended
    	var c = new Cookie(document, "Bookmark_" + this.toc_hash, 30);
    	c.Load();
    	this.lesson_location = c.Location;
	}
}

LmsComCookie.prototype.End = function() {
    LmsComCookie.prototype.BaseClass.End.call(this);
    if (this.toc_hash) {
    	var c = new Cookie(document, "Bookmark_" + this.toc_hash, 30);
    	c.Load();
    	c.Location = this.lesson_location;
    	c.Store();
	}
}

// Get current bookmark. This is only needed for a TOC that is called via lmstart
// but not from an LMS. If you open a Big SCO's concept from kp.html and launch
// it, the Big SCO toc will get an lmscombase from the lmstart, but the lmstart
// page doesn't have the toc_hash, so it can't get the bookmark.
// Note that "view outline" from a normal concept does not need this. It replaces
// the lmstart page with the toc, so the toc will end up with an lmscomcookie of
// its own.
LmsComCookie.prototype.GetBookmark = function(toc_hash) { 
    if (this.toc_hash = toc_hash) { // assignment intended
    	var c = new Cookie(document, "Bookmark_" + this.toc_hash, 30);
    	c.Load();
    	this.lesson_location = c.Location;
	}
    return parseInt(this.lesson_location, 10);
}

///////////////////////////////////////
//
// LmsStatus object defintions
//
///////////////////////////////////////

/* The following are a seriers of objects 
   used to communicate the learning
   asset runtime state with the peristence
   structure used by the LmsCom object */

///////////////////////////////////////
// Basic status
///////////////////////////////////////

/* Really basic status - use by documents
   like concepts in the TOC */ 
function LmsBasicStatus() {
    this.status = LMS_NOT_ATTEMPTED;  
}

LmsBasicStatus.prototype.getStatus = function() {
    return this.status;
}

LmsBasicStatus.prototype.setStatus = function(status) {
    this.status = status;
}

LmsBasicStatus.prototype.Save = function(lmscom) {
    lmscom.lesson_status = this.status;
}

///////////////////////////////////////
// Topic status
///////////////////////////////////////
LmsTopicStatus.prototype = new LmsBasicStatus();
LmsTopicStatus.prototype.constructor = LmsTopicStatus;
LmsTopicStatus.prototype.BaseClass = LmsBasicStatus.prototype;

function LmsTopicStatus() {
    this.score = "";
    this.passed = false;
    this.modes = new Array();
    this.modes["S"] = new Mode("S");
    this.modes["T"] = new Mode("T");
    this.modes["K"] = new Mode("K");
    this.modes["D"] = new Mode("D");
    this.modes["P"] = new Mode("P");
    this.modes["E"] = new Mode("E");
    
    this.anylaunched = false;  // any mode launched this attempt?
}

LmsTopicStatus.prototype.Save = function(lmscom) {
    var fname = "SaveTopicStatus";

    lmscom.lesson_data = lmscom.bigsco ? "" : this.getStatusstring();
    lmscom.lesson_status = this.getLMSStatus();
    lmscom.score = this.getScore();
}

LmsTopicStatus.prototype.setModeavail = function(m, a) {
    this.modes[m].avail = a;
}

LmsTopicStatus.prototype.getModeavail = function(m) {
    return this.modes[m].avail;
}

LmsTopicStatus.prototype.setModestatus = function(m, s) {
    if (this.modes[m].avail)
        this.modes[m].complete = s;
    else
        lmslog.addEntry(0, "setModestatus", "", "Invalid call of setModestatus");
}

LmsTopicStatus.prototype.getModestatus = function(m) {
    return this.modes[m].complete;
}

LmsTopicStatus.prototype.setRequiredMode = function(lmsModes, playerModes) {
    if (GetTopLevelLmsMode() == "LMS")
        this.requiredMode = this._getRequiredMode(lmsModes);
    else
        this.requiredMode = this._getRequiredMode(playerModes);
}

LmsTopicStatus.prototype._getRequiredMode = function(modes) {
    var modeorder = "EKTSPD";
    for (var i=0; i<modeorder.length; i++) {
        if (modes[modeorder.charAt(i)])
            return modeorder.charAt(i);
    }
    return "None"
}

LmsTopicStatus.prototype.GetRequiredMode = function() {
    return this.requiredMode;
}

LmsTopicStatus.prototype.initTopicstat = function(s) {
    var loopVar;
    var fname = "initTopicstat";
    lmslog.addEntry(0, fname, "", "Start");
    lmslog.addEntry(0, fname, "s string", s);

    lmslog.addEntry(0, fname, "s.length", s.length);
    if (s.length != 0) {
        //split the tracking string
        var f = s.split(",");
        for (loopVar = 0; loopVar <= f.length - 1; loopVar++) {
            lmslog.addEntry(0, fname, "f[" + loopVar + "]", f[loopVar]);
            if (f[loopVar].charAt(1) == "=") {
                this.modes[f[loopVar].charAt(0)].complete = this.modeIscomplete(f[loopVar].substr(2, 1));
            }
            else if (f[loopVar].substr(0, 5) == "PASS=") {
                var flag = f[loopVar].substr(5, 1);
                if (flag == "0")
                    this.passed = false;
                else
                    this.passed = true;
            }
            else if (f[loopVar].substr(0, 6) == "SCORE=") {
                this.score = f[loopVar].substr(6);
            }
        }
    }
}

LmsTopicStatus.prototype.clearTopicstat = function() {
    this.score = "";
    this.passed = false;
    for (var m in this.modes)
        this.modes[m].complete = false;
}

LmsTopicStatus.prototype.getStatusstring = function() {
    var fname = "get_statusstring";
    lmslog.addEntry(0, fname, "", "Start");
    var dataString = "";
    for (x in this.modes) {
        if (dataString.length != 0)
            dataString += ",";
        dataString += this.modes[x].id + "=" + (this.modes[x].complete ? "C" : "I");
    }
    /*if (this.modes["E"].complete) {
        dataString += ",PASS=" + (this.passed ? "1" : "0");
    } else*/ if (this.modes["K"].complete && this.isScored) {
        dataString += ",PASS=" + (this.passed ? "1" : "0") + ",SCORE=" + this.score;
    }
    lmslog.addEntry(0, fname, "dataString", dataString);
    return dataString;
}

LmsTopicStatus.prototype.getStatus = function() {
    var itemstatus = "";
    if (this.isComplete()) {
        //topic is complete
        // NB: Test for avail is still correct here. We want to return "C" to 
        // lmsui if knowit unavailable, even if topic was passed when launched in
        // UT mode.
        if (/*this.modes["E"].avail ||*/ (this.modes["K"].avail && this.isScored)) {
            if (this.passed) {
                itemstatus = LMS_PASSED;
            }
            else {
                itemstatus = LMS_FAILED;
            }
        } else {
            itemstatus = LMS_COMPLETED;
            if (this.savedStatus == "P" || this.savedStatus == "F")
                itemstatus = this.savedStatus;
        }
    } else {
        //topic is not complete
        itemstatus = LMS_INCOMPLETE;
        if (this.savedStatus == "P" || this.savedStatus == "F" || this.savedStatus == "C")
            itemstatus = Stat2Lms(this.savedStatus);
    }
    return itemstatus;
}

// Reports Not Attempted for a completed topic where no mode has been launched.
// This keep us from reporting an attempt if the user is just browsing
// the tree and doesn't do anything.
LmsTopicStatus.prototype.getLMSStatus = function() {
    if (this.isComplete() && !this.anylaunched)
        return LMS_NOT_ATTEMPTED;
    return this.getStatus();
}

LmsTopicStatus.prototype.getScore = function() {
    return this.score;
}

// Is considered complete if either the required
// mode is taken or a mode that allows the users
// to demonstrate more knowledge than the required mode
// has been taken.
// From "Play Mode Filtering in LMS"
LmsTopicStatus.prototype.isComplete = function() {
    var fname = "is_complete";
    lmslog.addEntry(0, fname, "", "Start");
    var iscomp = false;
    
    // Topic has no modes hance no required mode,
    // is considered complete just by visiting it.
    if (this.requiredMode === "None") {
        iscomp = true;
    } else {
        var modeorder = ["E", "K", "T", "S", "P", "D"];
        for (i=0; i<modeorder.length; i++) {
            if (this.modes[modeorder[i]].complete) iscomp = true;
            if (modeorder[i] === this.requiredMode)
                break
        }
    }
    lmslog.addEntry(0, fname, "iscomp", iscomp);
    return iscomp;
}

LmsTopicStatus.prototype.modeIscomplete = function(f) {
    var ret = false;
    var fname = "modeIscomplete";
    lmslog.addEntry(0, fname, "", "Start");
    if (f == "C")
        ret = true;
    else if (f == "I")
        ret = false;
    lmslog.addEntry(0, fname, "ret", ret);
    return ret;
}

LmsTopicStatus.prototype.isRequired = function(m) {
    return this.requiredMode === m;
}
                
// holds the status of a single mode launch of a topic
// pretty much duplicates the code in TopicStatus so if topic mode launched
// standalone (UT mode) it can write back to kpath coordinated with a kpath
// launch of the topic
LmsTopicLaunchStatus.prototype = new LmsTopicStatus();
LmsTopicLaunchStatus.prototype.constructor = LmsTopicStatus;
LmsTopicLaunchStatus.prototype.BaseClass = LmsTopicStatus.prototype;

function LmsTopicLaunchStatus(mode) {
    this.mode = this.modes[mode];
    this.score = "";
    this.passed = false;
    
    this.anylaunched = true;
}

LmsTopicLaunchStatus.prototype.Save = function(lmscom) {
    var fname = "SaveTopicLaunchStatus";

    // serialize state to report back to kpath in UT mode; LMS mode will ignore
    // this and use the mode completion flag for roll-up    
    this.BaseClass.Save.call(this,lmscom);
}

LmsTopicLaunchStatus.prototype._getRequiredMode = function(modes) {
    var modeorder = "EKTSPD";
    for (var i=0; i<modeorder.length; i++) {
        if (modes.indexOf(modeorder.charAt(i)) != -1)
            return modeorder.charAt(i);
    }
    return "None"
}

// returns result when topic is used in an assessment
LmsTopicLaunchStatus.prototype.getResult = function() {
    return this.passed ? "correct" : "incorrect";
}
LmsTopicLaunchStatus.prototype.getQuestionType = function() {
    return "other";
}
LmsTopicLaunchStatus.prototype.getLearnerResponse = function() {
    return "";
}

//////////////////////////////////////////
// Mode object definition
function Mode(mid) {
    this.avail = false;
    this.complete = false;
    this.id = mid;
}

///////////////////////////////////////
// Question status
///////////////////////////////////////
LmsQuestionStatus.prototype = new LmsBasicStatus();
LmsQuestionStatus.prototype.constructor = LmsQuestionStatus;
LmsQuestionStatus.prototype.BaseClass = LmsBasicStatus.prototype;

function LmsQuestionStatus() {
    this.question_type = null;
    this.learner_response = null;
    this.result = null;
}

LmsQuestionStatus.prototype.Save = function(lmscom) {
    lmscom.lesson_status = this.status;
    lmscom.lesson_data = Lms2Stat(this.getStatus());
}

LmsQuestionStatus.prototype.getStatus = function() {
    return this.status === LMS_NOT_ATTEMPTED ? this.savedStatus : this.status;
}

/* get/set question type */
LmsQuestionStatus.prototype.getQuestionType = function() {
    return this.question_type;
}

LmsQuestionStatus.prototype.setQuestionType = function(qtype) {
    return this.question_type = qtype;
}

/* get/set Learner Response */
LmsQuestionStatus.prototype.getLearnerResponse = function() {
    return this.learner_response;
}

LmsQuestionStatus.prototype.setLearnerResponse = function(lresp) {
    return this.learner_response = lresp;
}

LmsQuestionStatus.prototype.getResult = function() {
    return this.result;
}

LmsQuestionStatus.prototype.setResult = function(result) {
    return this.result = result;
}

///////////////////////////////////////
// Assessment status
///////////////////////////////////////
LmsAssessmentStatus.prototype = new LmsBasicStatus();
LmsAssessmentStatus.prototype.constructor = LmsAssessmentStatus;
LmsAssessmentStatus.prototype.BaseClass = LmsBasicStatus.prototype;

function LmsAssessmentStatus() {
    this.score = "";
    this.questionstatus = new Array();
    this.stateDiscarded = false;    // saved state was discarded due to change in assessment
}

LmsAssessmentStatus.prototype.Save = function(lmscom) {
    lmscom.lesson_status = this.status;

    if (this.status != LMS_INCOMPLETE &&
        this.status != LMS_NOT_ATTEMPTED)
        lmscom.score = this.score;
    else
        lmscom.score = "";

    var str = "";
    if (!lmscom.bigsco)
        str = this.hash.length + "@" + this.hash;
    // if a new attempt and we didn't do anything, keep old saved status    
    str += this.status == LMS_NOT_ATTEMPTED ? this.savedStatus : Lms2Stat(this.status);
    for (var i=0; i<this.questionstatus.length; i++)
        str += this.questionstatus[i];
    lmscom.lesson_data = str;
}

LmsAssessmentStatus.prototype.getStatus = function() {
    return this.status === LMS_NOT_ATTEMPTED ? Stat2Lms(this.savedStatus) : this.status;
}

LmsAssessmentStatus.prototype.getLMSStatus = function() {
    return this.status;
}
/* get/set Learner Response */
LmsAssessmentStatus.prototype.getScore = function() {
    return this.score;
}

LmsAssessmentStatus.prototype.setScore = function(score) {
    return this.score = score;
}

///////////////////////////////////////
// TOC status
///////////////////////////////////////
LmsTOCStatus.prototype = new LmsBasicStatus();
LmsTOCStatus.prototype.constructor = LmsTOCStatus;
LmsTOCStatus.prototype.BaseClass = LmsBasicStatus.prototype;

function LmsTOCStatus() {
}

LmsTOCStatus.prototype.getStatus = function() {
    return Stat2Lms(this.getTocState().GetStatus(0));
}

LmsTOCStatus.prototype.Save = function(lmscom) {
    lmscom.lesson_status = this.getStatus();

    var tocstat = this.getTocState();
    lmscom.lesson_data = tocstat.SerializeTOC();
}

/* get/set the state structure for the entire
   TOC */
LmsTOCStatus.prototype.getTocState = function() {
    return this.tocstate;
}

LmsTOCStatus.prototype.setTocState = function(tocstate) {
    return this.tocstate = tocstate;
}

function NodeState() {
    this.Status = 'N';
    this.Score = null;
    this.ChildrenStatus = ""; 
}

/* class that holds the state of the tree */
function TOCState(count, tocversion)
{
    this.NodeCounter = count;
    this.TocVersion = tocversion;
    
    this.InitInLookupTable();
}

/* sets the status of the outline element based on its index */
TOCState.prototype.SetStatus = function(index, status) {
    if (!this.LookUpTable[index])
        this.LookUpTable[index] = new NodeState();
    this.LookUpTable[index].Status = status;
}

/* gets the status of the outline element based on its index */ 
TOCState.prototype.GetStatus = function(index) {
    return this.LookUpTable[index].Status;
}

/* sets the score of the outline element based on its index */
TOCState.prototype.SetScore = function(index, score) {
if (!this.LookUpTable[index])
    this.LookUpTable[index] = new NodeState();
    
    this.LookUpTable[index].Score = score;
}

/* gets the score of the outline element based on its index */ 
TOCState.prototype.GetScore = function(index) {
    return this.LookUpTable[index].Score;
}

/* sets the score of the outline element based on its index */
TOCState.prototype.SetChildren = function(index, ChildrenStatus) {
if (!this.LookUpTable[index])
    this.LookUpTable[index] = new NodeState();
    
    this.LookUpTable[index].ChildrenStatus = ChildrenStatus;
}

/* gets the score of the outline element based on its index */ 
TOCState.prototype.GetChildren = function(index) {
    return this.LookUpTable[index].ChildrenStatus;
}

/* Deserializes the persisted state (str) into the TOC XML
   outline structure */
TOCState.prototype.DeserializeTOC = function(str) {
    var count = 0;
    var version;

    var index = str.indexOf("@");
    var count;

    if (index > 0) {
        count = parseInt(str.substring(0, index));
        version = str.substring(index + 1, index + count + 1);
    }
    else
        return;

    /* if the TOC has changed since last 
    time data was persisted, throw away the 
    persisted data */
    if (version != this.TocVersion)
        return;

    var statusstr = str.substring(index + count + 2);

    index = statusstr.indexOf("@");
    if (index > 0) {
        count = parseInt(statusstr.substring(0, index));
        statusstr = statusstr.substring(index + 1, index + count + 1);

        /* if the status string isn't equal to the 
        count we stored for it,then the string got 
        truncated by the LMS because it was too big
        so throw away the data */
        if (statusstr.length != count)
            return;
    }
    else
        return;

    statusstr = this.RLESDecode(statusstr);
    str = this.DeserializeLookUpTable(statusstr);
}

/* Deserializes the persisted state (str) of just the tree portion 
   of the outline into the XML outline structure */
TOCState.prototype.DeserializeLookUpTable = function(str) {
    var count = 0;
    var score = "";

    for (var i = 0; i < str.length; i++) {
        var status = str.charAt(i);
        this.SetStatus(count, status); 
        
        score = "";
        while (i < str.length - 1 && str.charAt(i+1) >= "0" && str.charAt(i+1) <= "9") {
            i++;
            score += str.charAt(i);      
        }

        if (score.length > 0)
           this.SetScore(count, parseInt(score));
        
        if (i < str.length - 1 && str.charAt(i+1) == "{") {
            var j = str.indexOf("}",i+2);
            this.SetChildren(count, str.substring(i+2,j));
            i = j;
        }
        
        count++;
    }
}

//this.TocVersion.length
TOCState.prototype.SerializeTOC = function() {
    var statusstr = this.RLESEncode(this.SerializeLookupTable());
    return this.TocVersion.length + "@" + this.TocVersion + " " + statusstr.length + "@" + statusstr;
}

TOCState.prototype.SerializeLookupTable = function() {
    var str = '';

    for (var i = 0; i < this.NodeCounter; i++) {

        var status = this.LookUpTable[i].Status;
        var score = this.LookUpTable[i].Score;
        var childrenstatus = this.LookUpTable[i].ChildrenStatus;

        if (!status) status = "N";

        str += status;
//        if (score !== null)
//            str += score;
            
        if (childrenstatus)
            str += "{" + childrenstatus + "}";            
    }

    return str;
}

TOCState.prototype.InitInLookupTable = function() {
    this.LookUpTable = new Array();

    for (var i = 0; i < this.NodeCounter; i++) {
        this.LookUpTable[i] = new NodeState();
    }
    this.SetStatus(0, "I");
}

/* Run lenght encode (RLE) the string to compress the storage */
TOCState.prototype.RLESEncode = function(str) {
    var last = '';
    var run = 0;
    var outstr = '';

    last = str.charAt(0);
    run = 1;

    for (var i = 1; i < str.length; i++) {
        if (str.charAt(i) == last) {
            run++;
        }
        else {
            if (run > 2) {
                outstr += "#";
                outstr += run;
                outstr += last;
            }
            else {
                outstr += str.substring(i - run, i)
            }

            last = str.charAt(i);
            run = 1;
        }
    }

    if (run > 2) {
        outstr += "#";
        outstr += run;
        outstr += last;
    }
    else {
        outstr += str.substring(i - run, i)
    }

    return outstr;
}

/* Run lenght decode (RLE) the string */
TOCState.prototype.RLESDecode = function(str) {
    var outstr = '';
    var runcountstr = '';
    var runcount;

    for (var i = 0; i < str.length; i++) {
        if (str.charAt(i) == '#') {
            runcountstr = '';
            i++;
            while (str.charAt(i) >= "0" && str.charAt(i) <= "9") {
                runcountstr += str.charAt(i);
                i++;
            }

            runcount = parseInt(runcountstr);
            for (var j = 0; j < runcount; j++)
                outstr += str.charAt(i);
        }
        else
            outstr += str.charAt(i);
    }

    return outstr;
}

function Lms2Stat(lmsStatus) {
    return lmsStatus.charAt(0).toUpperCase();
}

function Stat2Lms(status) {
    return [LMS_PASSED, LMS_FAILED, LMS_COMPLETED, LMS_INCOMPLETE, LMS_NOT_ATTEMPTED]["PFCIN".indexOf(status)];
}
/////////////////////
// LogEntry object //
/////////////////////

function LogEntry(startdate, ltype, funcname, varname, msgval) {
    this.logType = ltype;
    this.funcName = funcname;
    this.varName = varname;
    this.msgValue = msgval;
    this.dateTime = new Date().getTime() - startdate;   //Store the entry time in millisecs after the log started
    //alert(this.toString());
}

LogEntry.prototype.GetTableRow = function(i) {
    var typeMsg = "Info";
    var color = "#006600";

    if (this.logType === 1) {
        typeMsg = "LMS Comm";
        color = "#000033";
    }

    var varName = this.varName;
    if (varName === "") { varName = "&nbsp;"; }

    var msgValue = this.msgValue;
    if (msgValue === "") { msgValue = "&nbsp;"; }

    var html = "<tr>";
    html += "<td align='right'>" + (this.dateTime / 1000) + "</td>";
    html += "<td style='color:" + color + ";'>" + this.funcName + "</td>";
    html += "<td>" + varName + "</td>";
    html += "<td>" + msgValue + "</td>";
    html += "</tr>";

    return html;
}


////////////////
// Log object //
////////////////
function Log(active) {
    this.traceWindow = null;
    this.logArray = new Array();
    this.enabled = active;
    this.startDateTime = new Date();
    this.changed = true;    // Flag for letting external parties know when the log has changed
    this.windowReady = false;
    this.startLog();
}

Log.prototype.startLog = function() {
    if (this.enabled) {
        //this.log_string += "<table border='1'><tr><td>Type</td><td>Function</td><td>Variable</td><td>Message</td></tr>";
        this.addEntry(0, "initLog", "", "Log Intialized");
        this.openTraceWindow();
    }
}

Log.prototype.addEntry = function(ltype, funcname, varname, msgval) {
    if (this.enabled) {
        this.logArray.push(new LogEntry(this.startDateTime.getTime(), ltype, funcname, varname, msgval));
        this.changed = true;
        if (this.traceWindow && this.windowReady)
            this.traceWindow.UpdateTraceStack();
    }
}

Log.prototype.writeLog = function(sortOrder, traceLength) {
    var t = traceLength;
    if (t > this.logArray.length || t == 0) {
        t = this.logArray.length;
    }

    var html = "<table width='600'>";
    html += "<tr>";
    html += "<th colspan=4>Session start: " + this.startDateTime + "</th>";
    html += "</tr>";

    html += "<tr>";
    html += "<th>time</th>";
    html += "<th>function</th>";
    html += "<th>variable</th>";
    html += "<th>message</th>";
    html += "</tr>";

    var logEntry;
    if (sortOrder == 0) {
        for (var i = this.logArray.length - t; i < this.logArray.length; i++) {
            logEntry = this.logArray[i];
            html += logEntry.GetTableRow(i);
        }
    } else {
        for (var i = this.logArray.length - 1; i >= this.logArray.length - t; i--) {
            logEntry = this.logArray[i];
            html += logEntry.GetTableRow(i);
        }
    }
    html += "</table>";

    this.changed = false;   // Reset the changed flag
    this.windowReady = true;    // window initiates first call to writelog, so we know we're up
    return html;
}

Log.prototype.writeDetails = function(i) {
    return this.logArray[i].GetDetails();
}

Log.prototype.openTraceWindow = function() {
    if (this.traceWindow == null) {
        this.changed = true;
        this.traceWindow = window.open(lms_path + "lmsdebug.html", "_blank");
    }
}
/* lms_init.js */ 
/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

// javascript include area

/*
if (typeof lms_path == 'undefined')
lms_path = "../../../";

document.write('<script type="text/javascript" src="' + lms_path + 'kpsettings.js"></script>');
document.write('<script type="text/javascript" src="' + lms_path + 'js/scormoptions.js"></script>');
document.write('<script type="text/javascript" src="' + lms_path + 'js/lmsoptions.js"></script>');
document.write('<script type="text/javascript" src="' + lms_path + 'js/lmsapplet.js"></script>');
document.write('<script type="text/javascript" src="' + lms_path + 'js/lmsresource.js"></script>');
document.write('<script type="text/javascript" src="' + lms_path + 'js/lmscomfactory.js"></script>');
document.write('<script type="text/javascript" src="' + lms_path + 'js/lmscom.js"></script>');
document.write('<script type="text/javascript" src="' + lms_path + 'js/escape.js"></script>');



<script type="text/javascript" src="kpsettings.js"></script>
<script type="text/javascript" src="js/scormoptions.js"></script>
<script type="text/javascript" src="js/lmsoptions.js"></script>
<script type="text/javascript" src="js/lmsapplet.js"></script>
<script type="text/javascript" src="js/lmsresource.js"></script>
<script type="text/javascript" src="js/lmscomfactory.js"></script>
<script type="text/javascript" src="js/lmscom.js"></script>
<script type="text/javascript" src="js/escape.js"></script>


*/

// launch mode determination

var _lmsMode = null;          // LMS, KPT, Cookie or undefined

var _lmsParser = null;

function InitLmsMode(source) {
    if (_lmsParser == null) {
        _lmsParser = new UrlParser();
        _lmsParser.Parse();

        // direct launch
        if (source == "player") {
            if (_lmsParser.GetParameter("directlaunch") != null) {
                _lmsMode = (Kpath_launch == true ? "KPT" : "Cookie");
            }
        }

        // lmstart
        else if (source == "lmstart") {
            if (_lmsParser.GetParameter("toc") != null) {
                // _lmsMode = null;
            }
            else if (_lmsParser.GetParameter("dhtml") != null) {
                _lmsMode = (Kpath_launch == true ? "KPT" : "Cookie");
            }
            else {
                _lmsMode = "LMS";
            }
        }

        // toc
        else if (source == "toc") {
            if (_lmsParser.GetParameter("sco") == null) {
                _lmsMode = (Kpath_launch == true ? "KPT" : "Cookie");
            }
        }

        else {
            alert(R_undefined_lms_source);
        }
    }
}

function GetTopLevelLmsMode() {
    return _GetTopLevelLmsMode(this);
}

function _GetTopLevelLmsMode(w) {
    var m = w._lmsMode;
    if (m == null) {
        return _GetTopLevelLmsMode(w.lms_store.parentW);
    }
    return m;
}

// common lms callback functionality

var lms_initialized = false;

var lms_store;

var lmslog;

// lms_InitPage()
// called from onLoad event
function lms_InitPage(childIndex, parentW, cguid, callbackfunction) {
    if (lms_initialized == true) {
        setTimeout(callbackfunction, 1);
        return;
    }
    __Ialert("lms_InitPage called with parameters:" + childIndex + "," + parentW + "," + cguid + "," + callbackfunction);

    lms_store = { window: window,
        childIndex: childIndex,
        parentW: parentW,
        cguid: cguid,
        callbackfunction: callbackfunction
    };

    if (!parentW || parentW.closed) {
        lmslog = new Log(LmsConfig.DebugMode);
        InitializeLmsCom();
        InsertRuntimeAPI(lms_LoadRuntimeComplete);
    } else {
        if (!parentW.lms_initialized) return; // handle funky refresh handling of Firefox
        lmslog = parentW.lmslog;
        setTimeout(lms_LoadRuntimeComplete, 1);
    }
}

function lms_LoadRuntimeComplete() {
    __Ialert("lms_LoadRuntimeComplete() called");
    if (lms_store.parentW && !lms_store.parentW.closed) {
        lms_store.parentW.GetChildLmsCom(lms_store);
    } else if (!lms_store.parentW && !lms_store.cguid && !window.bigScoItemCount) { // launching a non-bigsco toc
        // NB: window.bigScoItemCount will only be defined in the lmstart page of a big sco
        document.LmsCom = PlayerConfig.EnableCookies ? new LmsComCookie() : new LmsComBase();
    } else {
        CheckForLMSAPI();
        document.LmsCom = _GlobalLmsComFactory.CreateLmsCom();
    }
    var lmscom = document.LmsCom;

    lmscom.guid = lms_store.cguid;
    lmscom.owner = window;
    lmscom.LoadAPIAdapter(lms_LoadAdapterComplete);
}

// lms_UpdateUI()
// called from first level assets to update the UI status bar
function lms_UpdateUI(status) {
    try {
        if (parent && parent.updateUI)
            parent.updateUI(status);
    } catch (e) { }
}

// lms_ClosePage()
// called from onUnload event
var hasClosed = false;
function lms_ClosePage(callClose) {
    __Ialert("lms_ClosePage() called");
    if (hasClosed == true)
        return;
    hasClosed = true;
    var lmscom = document.LmsCom;
    if (!lmscom || !lmscom.session_active)
        return;
    var childlmscom = lmscom.child;
    if (childlmscom && childlmscom.session_active && childlmscom.owner && !childlmscom.owner.closed)
        childlmscom.owner.lms_ClosePage(true);
    childlmscom = lmscom.ancillaryChild;    // close see also trail, if any
    if (childlmscom && childlmscom.session_active && childlmscom.owner && !childlmscom.owner.closed)
        childlmscom.owner.lms_ClosePage(true);
    if (window._closePage)
        _closePage();   // do any asset specific stuff
    if (lmscom.session_active) {    // test if our twin (lmstart/lmsui) snuck in (FF)
        lmscom.SaveStatus();
        lmscom.End();
        lmscom.NotifyParent();
    }
    if (callClose)
        window.close();
}

// connection drop
function lms_ConnectionLost(errText) {
    if (window.ConnectionLostEvent)
        ConnectionLostEvent(errText);
    if (lms_store.parentW && !lms_store.parentW.closed)
        lms_store.parentW.lms_ConnectionLost(errText);
}

function lms_IsConnected() {
    var lmscom = document.LmsCom;
    if (lmscom)
        return lmscom.IsConnected();
    return false;
}

// KPath logout
function lms_IsKPathLogoutAvailable() {
    return !!window.Kpath_logout_available;
}

function _logout(closeWindow) {
    if (lms_store.parentW && !lms_store.parentW.closed && lms_store.parentW._logout) {
        lms_store.parentW._logout(false);
    } else if (window.Kpath_logout_URL) {
        if (GetTopLevelLmsMode() == "LMS") {
            window.parent.parent.location.replace(Kpath_logout_URL);
        } else if (closeWindow) {   // need to logout through the opener window
            if (window.opener && !window.opener.closed) {
                var thisPage = window.opener.location.href;
                window.opener.location.replace(Kpath_logout_URL + "&RedirectURL=" + escape(thisPage));
                window.close();
            } else if (IsTouchDevice()) {   // this will need to go for HR when we get better with the ipad
                var w = window.location.href.split('/').slice(0,5).join('/') + "/ipad.html";
                window.location.replace(Kpath_logout_URL + "&RedirectURL=" + escape(w));
            } else {    // if no opener available, must logout through full screen topic window
                window.location.replace(Kpath_logout_URL);
            }
        } else {
            var thisPage = window.location.href.replace("?genctx","");  // strip if returning to smartmatch TOC
            window.location.replace(Kpath_logout_URL + "&RedirectURL=" + escape(thisPage));
        }
    }
}

// user profile (so it is accessible from everywhere)
function lms_IsUserProfileAvailable() {
    __alert("lms_IsUserProfileAvailable() called");
    if (GetTopLevelLmsMode() !== "KPT")
        return false;
    return document.LmsCom.doGetUPKValue("upk.anonymous") == "0";
}

function lms_GetUserProfileUrl() {
    __alert("lms_GetUserProfileUrl() called");
    if (Kpath_launch == false)
        return "";
    return Kpath_profile_URL + "?UPKLaunch=true";
}

function GetNoSound() {
    if (lms_store.parentW && !lms_store.parentW.closed)
        return lms_store.parentW.GetNoSound();
    else
        return lms_store.noSound;
}

function SetNoSound(value) {
    lms_store.noSound = value;
}

// lms callback trace functions

var _lms_show_all_alert = false;

function __alert(s) {
    if (_lms_show_alert || _lms_show_all_alert)
        alert(s + "\nfile: " + _lms_module_name);
}

function __Ialert(s) {
    if (_lms_show_alert || _lms_show_Ialert || _lms_show_all_alert)
        alert(s + "\nfile: " + _lms_module_name);
}/* playerlaunch.js */ 
﻿/*--
Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
--*/

var playerwindow = null;

function LaunchDoIt(url, params, nosu) {
    var popupVersion = false;
    var _params = params;

    var run = true;
    if (playerwindow) {
        if (!playerwindow.closed)
            run = false;
    }

    if (run) {
        var isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
        if (isIE) {
            try {
                function IsWindowPositioningRestricted() {
                    var p = window.createPopup();
                    p.show(1, 1, 1, 1);
                    var r = p.document.parentWindow.screenTop == 1;
                    p.hide();
                    return !r;
                }

                if (!IsWindowPositioningRestricted() && !IsIE10Modern()) {
                    var safeuri = false;
                    if (_params.substr(0, 3) == "su=") {
                        _params = Escape.SafeUriUnEscape(_params.substr(3));
                        safeuri = true;
                    }
                    _params += "&popup=true";
                    if (safeuri) {
                        _params = "su=" + Escape.SafeUriEscape(_params);
                    }
                    popupVersion = true;
                }
            } catch (e) {
            }
        }

        if (popupVersion) {
//            if (IsIE9()) {url = url + "topicgc.html"; }
//            else {url = url + "topicgcx.html"; }
            url = url + "topicgc.html";
            var url2 = typeof (urlParser) == "undefined" ? url + "?" + _params : urlParser.GetCorrectUrl(url + "?" + _params);
            playerwindow = window.open(url2, "", "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,left=1500");
        }
        else {
            url = url + "topicgcx.html";
            if (isIE) {
                var appVerArray = navigator.appVersion.split(";");
                var appVer = appVerArray[1];
                appVer = appVer.substr(6)
                appVer = parseFloat(appVer);
            }
            var LeftPos = IsSafari() ? screen.availWidth - 361 : screen.availWidth - 290;
            var TopPos = screen.availHeight - 450;
            var popWidth = IsSafari() ? 346 : 275;
            var popHeight = 400;
            if (PlayerConfig.EnableCookies) {
                GICookie = new Cookie(document, "GICookie", 365, "/", null, null)
                if (GICookie.Load()) {
                    if (GICookie["Cleft"] >= 0 && GICookie["Ctop"] >= 0 && GICookie["Cleft"] < screen.availWidth && GICookie["Ctop"] < screen.availHeight) {
                        LeftPos = parseInt(GICookie["Cleft"]);
                        TopPos = parseInt(GICookie["Ctop"]);
                        popWidth = parseInt(GICookie["Cwidth"]);
                        popHeight = parseInt(GICookie["Cheight"]);
                    }
                }
            }
            var url2 = typeof (urlParser) == "undefined" ? url + "?" + _params : urlParser.GetCorrectUrl(url + "?" + _params);
            playerwindow = window.open(url2, "", "toolbar=0,scrollbars=0,location=1,statusbar=0,menubar=0,resizable=1,left=" + LeftPos + ",top=" + TopPos + ",width=" + popWidth + ",height=" + popHeight);
        }
    }
    else {
        alert(R_toc_doit_err);
    }
}

/* smartmatch.js */ 
﻿/* Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved. */
/* Version 11.1.0.0 */

window.SmartMatch={};
(function(v){function w(a){return typeof a=="function"||a!=null&&a.constructor===Function}function x(a){return(typeof a=="object"||w(a))&&a!=null}function A(){function a(d){d=d.toString(16);switch(d.length){case 1:return"\\u000"+d;case 2:return"\\u00"+d;case 3:return"\\u0"+d;case 4:return"\\u"+d}return"?"}function b(d){return'"'+String(d).replace(/(["\\])/g,"\\$1").replace(/([\x00-\x1F])/g,function(g){g=g.charCodeAt(0);var h=y.charAt(g);return h=="?"?a(g):"\\"+h})+'"'}function c(d){return d<10?"0"+
d:d}function e(d,g){var h=typeof d;if(h!="object"){if(h=="string")return b(d);if(h=="number")return isFinite(d)?String(d):"null";if(h=="boolean")return d?"true":"false"}else{if(d===null)return"null";if(d.constructor===String)return b(d);if(d.constructor===Number)return isFinite(d)?String(d):"null";if(d.constructor===Boolean)return d?"true":"false";if(d.constructor===Date)return"".concat(d.getUTCFullYear(),"-",c(d.getUTCMonth()),"-",c(d.getUTCDate()),"T",c(d.getUTCHours()),":",c(d.getUTCMinutes()),
":",c(d.getUTCSeconds()),"Z");if(d.constructor!==Function){if(n(g,d))throw m;h=[];g.push(d);if(d.constructor===Array){for(var j=0,l=d.length;j<l;++j){var s=d[j];s==null||o(s)?h.push("null"):h.push(e(s,g,String(j)))}g.pop();return"["+h.join()+"]"}for(j in d){l=d[j];if(l==null||o(l))l===null&&h.push(b(j)+":null");else if((l=e(l,g,j))!=null)h.push(b(j)+":"+l)}g.pop();return"{"+h.join()+"}"}}}var i=/[^",:\{\}\[\] \t\r\n]|"""|"[ \t\r\n]+"]|[\}\]][ \t\r\n]*[:\{\[]|[\{\[][ \t\r\n]*[,:]|[,:][ \t\r\n]*[,:\}\]]/,
f=/"(?:[^"\\\x00-\x1F]|\\["\\\/bnfrt]|\\u[0-9a-fA-F]{4})*"|null|true|false|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+\-]?[0-9]+)?/g,m=Error(""),o=w,n;(function(){try{if(typeof[].indexOf=="function"&&[1,2,3,4].indexOf(3)==2){n=function(g,h){return g.indexOf(h)!=-1};return}}catch(d){}n=function(g,h){for(var j=0,l=g.length;j<l;++j)if(g[j]===h)return true;return false}})();var y="????????btn?fr??????????????????";p.EncodeObject=function(d){if(d==null||o(d)){if(d===null)return"null"}else try{return e(d,
[],"")}catch(g){if(g!==m)throw g;}};p.DecodeObject=function(d){try{if(d!=null&&!i.test(d.replace(f,'""')))return eval("("+d+")")}catch(g){}}}function B(){var a=document.title;if(a=="")if(typeof window.R_toc_title=="string"&&typeof window.moduleName=="string")a=window.R_toc_title+" - "+q.UnescapeQuotes(window.moduleName);return a}var r={GATEWAY_EMBED:[],GATEWAY_LINK:[],TABBED_GATEWAY:1,TABBED_GATEWAY_OPEN_LAST_ACTIVE_TAB:1,GATEWAYPAGE_TEST:0,GATEWAYPAGE_MAIN_PLAYER:1,GATEWAYPAGE_EXTERNAL_PLAYER_APPLICABLE:2,
GATEWAYPAGE_EXTERNAL_PLAYER_FULL:3,GATEWAYPAGE_HELP:4,GATEWAYPAGE_URL_WITH_NOCTX:5,GATEWAYPAGE_URL_WITH_CTX:6,GATEWAYPAGE_RESOURCES:7,GATEWAY_RESOURCES_TITLE:"Linked Resources",GATEWAY_PLAYER_TITLE:"Main Player",GATEWAY_HELP_TITLE:"Help",GATEWAY_TEST_TITLE:"Test Data",TOCVIEW_ALL:0,HEMIPARAMTEST:0,HELP_URL:null,URL:{"*":"../../"},DIRECT:0,BRAND:null};r.GATEWAY_EMBED.push({Title:r.GATEWAY_PLAYER_TITLE,URL:"",Type:r.GATEWAYPAGE_MAIN_PLAYER});var t={NotDetected:-1,MicrosoftInternetExplorer:0,MozillaFirefox:1,
GoogleChrome:2},k={Type:t.NotDetected,Version:void 0,IE:void 0,FF:void 0,CR:void 0,GetVersionFn:[function(){var a=navigator.userAgent,b=a.indexOf("MSIE ");if(b!=-1){b+=5;var c=a.indexOf(";",b);if(c!=-1)return Number(a.substr(b,c-b))}return-1},null,null]},C={IsIE:function(){if(k.IE!==void 0)return k.IE;if(k.IE=navigator.userAgent.indexOf("MSIE ")!=-1){k.Type=t.MicrosoftInternetExplorer;return true}return false},IsFF:function(){if(k.FF!==void 0)return k.FF;if(k.FF=navigator.userAgent.indexOf("Firefox")!=
-1){k.Type=t.MozillaFirefox;return true}},GetVersion:function(){if(k.Version!==void 0)return k.Version;var a=k.GetVersionFn[k.Type];a=a&&a()||-1;return k.Version=a}},D={Indent:"  "},p={EncodeObject:function(a,b){try{return JSON.stringify(a,null,b?D.Indent:null)}catch(c){if(typeof TypeError=="undefined"||!c||c.constructor!==TypeError)throw c;}},DecodeObject:function(a){if(a!=null)try{return JSON.parse(a)}catch(b){}}};(function(){if(typeof window.JSON!="undefined"&&typeof(JSON.stringify&&JSON.parse)!=
"undefined")try{var a={a:"",b:0.1,c:null,d:true,e:false,f:[[{},{g:function(){return 1},h:1},new Function("return 0;"),function(){return 1},1]]},b=JSON.stringify(a);if(b=='{"a":"","b":0.1,"c":null,"d":true,"e":false,"f":[[{},{"h":1},null,null,1]]}'&&b==JSON.stringify(JSON.parse('{"a":"","b":0.1,"c":null,"d":true,"e":false,"f":[[{},{"h":1},null,null,1]]}'))&&/2345-12-23T12:34:56(?:\.789[0]*)?Z/.test(JSON.stringify(new Date(Date.UTC(2345,11,23,12,34,56,789)))))return}catch(c){}A()})();var q={WriteScript:function(a,
b){var c=a.document.getElementsByTagName("head")[0],e=a.document.createElement("script");e.type="text/javascript";e.src=b;c.appendChild(e)},AccessGranted:function(a){try{if(x(a)&&x(a.location)&&(typeof a.location.href=="string"||typeof a.location.href=="object"&&a.location.href.constructor===String))return true}catch(b){}return false},CreateScript:function(a,b){var c=document.getElementsByTagName("head")[0],e=document.createElement("script");e.type="text/javascript";e.src=b;e.setAttribute("id",a);
c.appendChild(e)},ModifyScript:function(a,b){var c=document.getElementById(a);c&&c.parentNode.removeChild(c);q.CreateScript(a,b)},ExecuteScript:function(a,b){document.getElementById(a)==null?q.CreateScript(a,b):q.ModifyScript(a,b)},AddListener:function(a,b,c){var e=false;if(c===String(c))c=document.getElementById(c);if(c.addEventListener)e=c.addEventListener(a,b,false);else if(c.attachEvent)e=c.attachEvent("on"+a,b);return e},GetClassAttribute:function(){if(!C.IsIE()||document.documentMode>=8)return"class";
return"className"},UnescapeQuotes:function(a){for(var b=a.indexOf("&amp;");b>=0;){a=a.substr(0,b)+"&"+a.substr(b+5);b=a.indexOf("&amp;")}for(b=a.indexOf("&gt;");b>=0;){a=a.substr(0,b)+">"+a.substr(b+4);b=a.indexOf("&gt;")}for(b=a.indexOf("&lt;");b>=0;){a=a.substr(0,b)+"<"+a.substr(b+4);b=a.indexOf("&lt;")}return a}};showscore=0;var u={Variables:{adjusted_maxsearch:0},Query:"querydb",DbRoot:"querydb/topicmap/",DbSize:0,DbSearchedSize:0,EcidArray:[],SearchArray:{},_EcidArray:function(a,b){this.Expr=
a||"";this.Ctx=b||null;this.List=[];this.Hits=0},FramesWithHits:[],AppName:"",AllTopics:0,TopicsPerFile:0,AllFiles:0,CurrentFile:0,CurrentIndex:0,AllScore:0,HighScore:0,LowScore:0,MinScore:0,FilteredbyMaxHit:[],FilteredbyMaxSearch:[],SetAppName:function(a){this.AppName=a},TocWin:null,_Topic:function(a){this.index=-1;this.name=this.guid=this.text="";this.hits=this.ascore=this.score=0;this.type="";this.frameid=-1;this.Process=function(){this.SetGuid();this.SetName()};this.SetGuid=function(){var b=this.text.indexOf("_");
if(b>0)this.guid=this.text.substr(0,b)};this.SetName=function(){var b=this.text.indexOf("#");b={s:this.text.substr(b+3),p:0};var c=ReadBase64_32(b),e=b.s.substr(b.p+c);this.name=b.s.substr(b.p,c);b=e.indexOf("#");if(b>=0){this.frameid=parseInt(e.substr(b+2));e=e.substr(0,b)}this.type=e};if(typeof a=="string"){this.text=a;this.Process()}},_TopicList:function(){this._tmap=[];this.Set=function(a,b){a.index=b;this._tmap.push(a)};this.Sort=function(){this._tmap.sort(this._Sort)};this._Sort=function(a,
b){return b.score-a.score};this.GetGuid=function(a){return this._tmap[a].guid};this.GetName=function(a){return this._tmap[a].name};this.GetFrameid=function(a){return this._tmap[a].frameid};this.GetIndex=function(a){return this._tmap[a].index};this.GetElementByIndex=function(a){for(var b=0;b<this._tmap.length;b++)if(this._tmap[b].index==a)return this._tmap[b];return null}},Ctx:[],CtxProcessor:{Counter:1,_type:"",_count:0,Hex:function(){return this.Counter.toString(16)},GetFile:function(){return SmartMatch.GenericSearch.Query+
this._type+"/"+this.Hex()+".xml"},Iterate:function(a){SmartMatch.GenericSearch.Ctx[this._type]=SmartMatch.GenericSearch.Ctx[this._type].concat(a);this.Counter++;try{LoadXMLDoc(SmartMatch.GenericSearch.CtxProcessor.GetFile(),"SmartMatch.GenericSearch.CtxProcessor.IterateRet")}catch(b){}},_Iterate:function(){LoadXMLDocArray(SmartMatch.GenericSearch.CtxProcessor.GetFile(),"SmartMatch.GenericSearch.CtxProcessor.Iterate","","N")},IterateRet:function(a){if(a==true)setTimeout(this._Iterate,1);else{this._count++;
this._count<2?this.Next("genctx"):setTimeout(SmartMatch.GenericSearch.StartXMLProcessor,1)}},Start:function(){this._type="ctxex";SmartMatch.GenericSearch.Ctx[this._type]=[];LoadXMLDoc(SmartMatch.GenericSearch.CtxProcessor.GetFile(),"SmartMatch.GenericSearch.CtxProcessor.IterateRet")},Next:function(a){this._type=a;SmartMatch.GenericSearch.Ctx[this._type]=[];LoadXMLDoc(SmartMatch.GenericSearch.CtxProcessor.GetFile(),"SmartMatch.GenericSearch.CtxProcessor.IterateRet")}},StartXMLProcessor:function(){SmartMatch.GenericSearch.Variables.showtestpage>
0?LoadXMLDoc(SmartMatch.GenericSearch.DbRoot+"count.xml","SmartMatch.GenericSearch.TopicsCount","",""):SmartMatch.GenericSearch._StartSearch()},TopicsCount:function(a){a=a.responseXML.getElementsByTagName("Count");if(a.length>0)SmartMatch.GenericSearch.AllTopics=a[0].firstChild.data;LoadXMLDocArray(SmartMatch.GenericSearch.DbRoot+"0.xml","SmartMatch.GenericSearch.MaxTopicsPerFile","","T")},MaxTopicsPerFile:function(a){SmartMatch.GenericSearch.TopicsPerFile=parseInt(a[0]);SmartMatch.GenericSearch.AllFiles=
Math.floor(SmartMatch.GenericSearch.AllTopics/SmartMatch.GenericSearch.TopicsPerFile)+(SmartMatch.GenericSearch.AllTopics%SmartMatch.GenericSearch.TopicsPerFile==0?0:1);LoadXMLDocArray(SmartMatch.GenericSearch.DbRoot+SmartMatch.GenericSearch.CurrentFile+".xml","SmartMatch.GenericSearch.IterateXMLFiles","","T")},IterateXMLFiles:function(a){a=DecodeTMapArray(a);SmartMatch.GenericSearch.CurrentFile++;for(var b=1;b<a.length;b++){for(var c=a[b],e=c.indexOf("/"),i=c;e>=0;){c.substr(0,e);e=c.indexOf("/");
c=i=c.substr(e+1)}c=new SmartMatch.GenericSearch._Topic(i);SmartMatch.GenericSearch.TopicList.Set(c,b+SmartMatch.GenericSearch.TopicsPerFile*(SmartMatch.GenericSearch.CurrentFile-1))}SmartMatch.GenericSearch.AllFiles==SmartMatch.GenericSearch.CurrentFile?SmartMatch.GenericSearch._StartSearch():setTimeout(SmartMatch.GenericSearch._IterateXMLFiles,1)},_IterateXMLFiles:function(){LoadXMLDocArray(SmartMatch.GenericSearch.DbRoot+SmartMatch.GenericSearch.CurrentFile+".xml","SmartMatch.GenericSearch.IterateXMLFiles",
"","T")},_StartSearch:function(){if(SmartMatch.GenericSearch.EcidArray.length>0){QueryParser.Parse("URI","g"+SmartMatch.GenericSearch.EcidArray[SmartMatch.GenericSearch.CurrentIndex].Expr);if(QueryParser.ev)try{QueryProcessor.Start(QueryParser.ev,SmartMatch.GenericSearch.Search)}catch(a){}}else SmartMatch.GenericSearch.SearchDone()},Search:function(a){var b=[];if(a=="")b.push(0);else if(a.length>SmartMatch.GenericSearch.Variables.maxhit){b.push(-1);SmartMatch.GenericSearch.EcidArray[SmartMatch.GenericSearch.CurrentIndex].Hits=
a.length;SmartMatch.GenericSearch.Variables.showtestpage>0&&SmartMatch.GenericSearch.FilteredbyMaxHit.push(SmartMatch.GenericSearch.EcidArray[SmartMatch.GenericSearch.CurrentIndex])}else for(var c=0;c<a.length;c++)b.push(a[c].index);SmartMatch.GenericSearch.EcidArray[SmartMatch.GenericSearch.CurrentIndex].List=b;SmartMatch.GenericSearch.CurrentIndex++;SmartMatch.GenericSearch.CurrentIndex<SmartMatch.GenericSearch.EcidArray.length?setTimeout(SmartMatch.GenericSearch.IterateSearch,1):SmartMatch.GenericSearch.SearchDone()},
SearchDone:function(){if(SmartMatch.GenericSearch.Variables.showtestpage>0)if(typeof CDB!="undefined"&&CDB!=null&&typeof CDB.index!="undefined")SmartMatch.GenericSearch.DbSearchedSize=CDB.index.length;SmartMatch.GenericSearch.GetTopics();var a=SmartMatch.GenericSearch.GetTopicsList();ShowGenToc(a);if(SmartMatch.GenericSearch.Variables.showtestpage>0){if(!(r.GATEWAY_EMBED.length>1))SmartMatch.GenericSearch.Utility.TestWindow=window.open("../stdhemi/context/context.html?smartmatch","_upktestpage_");
SmartMatch.GenericSearch.Utility.TestWindow&&window.focus()}},IterateSearch:function(){SmartMatch.GenericSearch._StartSearch()},GetTopics:function(){this.HighScore=0;if(SmartMatch.GenericSearch.EcidArray.length!=0){for(var a=0,b=SmartMatch.GenericSearch.EcidArray.length;a<b;a++){for(var c=SmartMatch.GenericSearch.EcidArray[a],e=0;e<c.List.length;e++){var i=c.List[e]-1;if(SmartMatch.GenericSearch.Variables.showtestpage>0){if(i>0){SmartMatch.GenericSearch.TopicList._tmap[i].score+=1;SmartMatch.GenericSearch.TopicList._tmap[i].hits++}}else if(typeof SmartMatch.GenericSearch.SearchArray[c.List[e]]!=
"undefined")SmartMatch.GenericSearch.SearchArray[c.List[e]]+=1;else SmartMatch.GenericSearch.SearchArray[c.List[e]]=1}if(c.List.length>0&&c.List[0]>=0)SmartMatch.GenericSearch.AllScore+=1}if(SmartMatch.GenericSearch.Variables.showtestpage>0){var f=0;for(a=SmartMatch.GenericSearch.TopicList._tmap.length;f<a;f++){b=SmartMatch.GenericSearch.TopicList._tmap[f];typeof b=="object"&&b!=null&&b.score>0&&b.frameid!=-1&&SmartMatch.GenericSearch.FramesWithHits.push(f+1);b.ascore=b.score;c=b.score/SmartMatch.GenericSearch.AllScore;
c=parseFloat(c.toFixed(2));b.score=parseFloat(c);if(SmartMatch.GenericSearch.HighScore<b.score)SmartMatch.GenericSearch.HighScore=b.score}}else for(f in SmartMatch.GenericSearch.SearchArray){a=parseFloat((SmartMatch.GenericSearch.SearchArray[f]/SmartMatch.GenericSearch.AllScore).toFixed(2));SmartMatch.GenericSearch.SearchArray[f]=a;if(f>0)if(SmartMatch.GenericSearch.HighScore<a)SmartMatch.GenericSearch.HighScore=a}}},GetTopicsList:function(){SmartMatch.GenericSearch.LowScore=parseFloat((SmartMatch.GenericSearch.HighScore*
SmartMatch.GenericSearch.Variables.threshold/100).toFixed(2));SmartMatch.GenericSearch.MinScore=parseFloat(SmartMatch.GenericSearch.LowScore<=parseFloat((SmartMatch.GenericSearch.Variables.minscore/100).toFixed(2))?parseFloat((SmartMatch.GenericSearch.Variables.minscore/100).toFixed(2)):this.LowScore);var a=[];if(SmartMatch.GenericSearch.Variables.showtestpage>0&&SmartMatch.GenericSearch.EcidArray.length>0)for(var b=0,c=SmartMatch.GenericSearch.TopicList._tmap.length;b<c;b++){var e=SmartMatch.GenericSearch.TopicList._tmap[b];
if(e.frameid!=-1)if(e.score>0)if(e.score>=this.MinScore){var i={index:0,score:0};i.index=e.index;i.score=e.score;a.push(i)}}else for(b in SmartMatch.GenericSearch.SearchArray){c=SmartMatch.GenericSearch.SearchArray[b];if(b>0)if(c>=this.MinScore){e={index:0,score:0};e.index=b;e.score=c;a.push(e)}}return a},CallBack:function(){typeof SmartMatch.GenericSearch.Utility.TestWindow=="object"&&SmartMatch.GenericSearch.Utility.TestWindow.SMTestPage.Show(SmartMatch.GenericSearch.Variables.showtestpage)},Utility:{TestWindow:null,
Dec2Hex:function(a){return a.toString(16).toUpperCase()},Hex2Dec:function(a){return parseInt(a,16)},GetEcid:function(a){a=a.Expr.substr(1,a.Expr.length-2);var b=a.indexOf("$");if(b>0){a=a.substr(b+1).substr(4);return Escape.MyUnEscape(a)}return""},GetPrefix:function(a){var b="";a=a.Expr.substr(1,a.Expr.length-2);var c=a.indexOf("$");if(c>0)b=a.substr(c+1).substr(0,4);return b},GetWeight:function(){var a="";return 1},GetCaption:function(a){var b="";return b=a.Ctx.caption}}};u.TopicList=new u._TopicList;
if(q.AccessGranted(window.parent)){var z=window.parent;if(z.location.href.indexOf("gateway.html")!=-1){var E=B();z.GatewayHelper.SetTitleFromThePlayer(E)}}v.ShowContent=function(a,b,c,e){window.setTimeout(function(){try{var i=b!=""?p.DecodeObject(b):null,f=c!=""?p.DecodeObject(c):{},m=e!=""?p.DecodeObject(e):{};SmartMatch.GenericSearch.Variables.threshold=m.Threshold;SmartMatch.GenericSearch.Variables.maxhit=m.MaxHit;SmartMatch.GenericSearch.Variables.maxsearch=m.MaxSearch;SmartMatch.GenericSearch.Variables.minscore=
m.MinScore;if(a=="STDHTML"){if(f.threshold)SmartMatch.GenericSearch.Variables.threshold=f.threshold;if(f.maxhit)SmartMatch.GenericSearch.Variables.maxhit=f.maxhit;if(f.maxsearch)SmartMatch.GenericSearch.Variables.maxsearch=f.maxsearch;if(f.minscore)SmartMatch.GenericSearch.Variables.minscore=f.minscore}if(f.showtestpage)SmartMatch.GenericSearch.Variables.showtestpage=f.showtestpage;if(f.showscore)showscore=f.showscore;SmartMatch.GenericSearch.EcidArray.length=0;if(a.length>0)if(i.length>0){SmartMatch.GenericSearch.SetAppName(a);
for(f=0;f<i.length;f++){var o="'"+a+"$"+Escape.MyEscape(i[f])+"'",n=new SmartMatch.GenericSearch._EcidArray(o,i[f]);SmartMatch.GenericSearch.EcidArray.push(n)}SmartMatch.GenericSearch.Variables.adjusted_maxsearch=SmartMatch.GenericSearch.EcidArray.length}setTimeout(SmartMatch.GenericSearch.StartXMLProcessor,1)}catch(y){}},100)};v.GenericSearch=u})(window.SmartMatch);
