// Copyright © 1998, 2012, Oracle and/or its affiliates.  All rights reserved.
/*
document.write('<script src="../../../kpsettings.js"></script>');
*/

var urlParser = null;

// var _lmsMode = "";          // LMS, KPT, Cookie or undefined | defined in lms_init.js
var _lmsEnvironment = "";   // LMS, TOC, DHTML

function InitLmsEnvironment() {
    if (urlParser.GetParameter("toc") != null) {
        _lmsEnvironment = "TOC";
    }
    else if (urlParser.GetParameter("dhtml") != null) {
        _lmsEnvironment = "DHTML";
    }
    else {
        _lmsEnvironment = "LMS";
    }
}

function decodeHTMLString(strHTMLString) {
    strHTMLString = replaceString("&amp;", "&", strHTMLString);
    return strHTMLString;
}

function fixHTMLString(strHTMLString) {
    strHTMLString = replaceString("<", "&lt;", strHTMLString);
    strHTMLString = replaceString(">", "&gt;", strHTMLString);
    strHTMLString = replaceString("'", "&#39;", strHTMLString);
    strHTMLString = replaceString('"', "&#34;", strHTMLString);
    var k = strHTMLString.indexOf("\\\\");
    while (k >= 0) {
        strHTMLString = strHTMLString.substr(0, k) + strHTMLString.substr(k + 1);
        k = strHTMLString.indexOf("\\\\", k + 1);
    }

    return strHTMLString;
}

var _deviceDPI = 0;

function InitUI() {

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

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

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

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

    concept = decodeHTMLString(concept);
    concept = resolveIfRelative(concept);
    if (concept.length == 0 && assetType == "T") {
        concept = "./tpc/" + topicID + "/leadin.html";
    }
    topicName = decodeHTMLString(topicName);
    InitLmsEnvironment();
    InitLmsMode("lmstart");
    var childIndex = 0;
    var childIndexParam = urlParser.GetParameter("lmsChildIndex");
    if (childIndexParam > 0) {
        childIndex = childIndexParam;
    }
    var guid = (assetType == "B" ? originalType : assetType) + "_" + topicID;

    //    oType = (assetType == "B" ? originalType : "");
    //    if (concept.length == 0 && (assetType == "C" || oType == "C")) {
    //        guid = null;
    //    }

    if (concept.length == 0) {
        if (assetType == "B" || assetType == "C")
            guid = null;
    }

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

    lms_InitPage((_lmsMode == null ? childIndex : -1), (_lmsMode == null ? window.parent : null), guid, "InitUI2()");
}

function InitUI2() {

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

    if (topicDescriptor == null)
        LoadDescriptor();
    if (assetType == "Q") {
        BuildQuestionConcept();
    }
    if (assetType == "A") {
        BuildAssessmentConcept();
    }
    if (!topicDescriptor.userdefined) {
        if (concept.length > 0)
            concept = urlParser.GetCorrectUrl(concept, true);
    }
    try {
        if (getInnerWidth() > 0 && getInnerHeight() > 0)
            this.frames["myframe"].location.replace(urlParser.GetCorrectUrl("../../lmsui.html"));
    }
    catch (e) { return; }
    _resize();
    window.onresize = resize;
}

function ResizeFrame() {
    _resize();
}

function resize() {
    setTimeout("_resize()", 0);
}

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

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

function _resize() {
    if (IsIE7() == false)	//Bug 16023024 - add support for ie7 to hammerhead
        return; //Bug 12992054 - wrong player toc behavior if i use ie8 zoom - iframe is resized automatically - 14797706 for merging it into HammerHead
    if (checkIEDPI() == false)
        return;

    cw = getInnerWidth();
    ch = getInnerHeight();

    if (IsIE8())
        cw -= 1; // Bug 12568455 - lms - perpetual iframe resize in ie8
    f = document.getElementById("myframe");
    try {
        f.style.width = "" + cw + "px";
        f.style.height = "" + ch + "px";
    }
    catch (e) {
        setTimeout("InitUI2();", 200);
    }
}

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 BuildQuestionConcept() {
    var _userdefined = topicDescriptor.userdefined;
    concept = topicDescriptor.concept;
    if (_userdefined.toLowerCase() == "true") {
        var kpnextpage = AbsUrl("../../toc/udq_callback.html");
        //            kpnextpage = "../../js/udq_callback.html";
        var kpmode = 0;
        var kprnda = 0;
        var kpremed = 0;
        var kpfeedbk = 0;
        switch (topicDescriptor.remediation.toLowerCase()) {
            case "always":
                kpremed = 3;
                kpfeedbk = 1;
                break;
            case "userasks":
                kpremed = 1;
                kpfeedbk = 1;
                break;
            case "incorrect":
                kpremed = 2;
                kpfeedbk = 1;
                break;
            case "resultsonly":
                kpremed = 0;
                kpfeedbk = 1;
                break;
            case "none":
                kpremed = 0;
                kpfeedbk = 0;
                break;
        }
        concept += "?kpnextpage=" + kpnextpage + "&kpmode=" + kpmode + "&kpremed=" + kpremed + "&kpfeedbk=" + kpfeedbk + "&kprnda=" + kprnda;
    }
    if (_lmsMode == "LMS") { concept += "&lms"; }
    concept += "&question=" + topicID + "&host=player";
}

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 {
        k = base.lastIndexOf('/');
        base = base.substr(0, k);
        base = base + "/" + url;
    }
    return (base);
}

function BuildAssessmentConcept() {
    concept = topicDescriptor.concept + "&assessment=" + topicID;
    if (_lmsMode == "LMS") { concept += "&lms"; }
    var _owner = urlParser.GetParameter("owner");
    if (_owner != null) {
        if (_owner.length > 0) {
            concept += "&owner=" + _owner;
        }
    }
}

function OnQuestionContinue() {
    if (parent.OnQuestionContinue)
        parent.OnQuestionContinue();
}

function StartTopic(mode, frame_id, fromjumpin) {
    this.frames["myframe"].launchTopic(mode, frame_id, fromjumpin);
}

function SetCtxexParam(s) {
    urlParser.AddParameter("ctxex", s);
}

function RoleStatusChanged() {
    var k = CheckSeeAlso();
    // call lmsui (lms.js) to update the link on the UI
    this.frames["myframe"].UpdateSeeAlso(k);
}

function OpenSeeAlso(seeAlsoRoot, index) {
    this.frames["myframe"].OpenSeeAlso(seeAlsoRoot, index);
}

function OnNotesClosed() {
    this.frames["myframe"].OnNotesClosed();
}

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

////////////////////////////////////////////////////////////////////////////////////////////
// Descriptor support

var topicDescriptor = null;

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 seeAlsoLink(type, title, guid, empty) {
    this.type = type;
    this.title = title;
    this.guid = guid;
    this.filtered = false;
    this.empty = empty;
}

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

function LoadDescriptor() {

    var 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.open("GET", "descriptor.xml", false);
    req.send();

    if (location.hostname == "" && 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;
        }
    }

    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;
        for (var j = 0; j < n.attributes.length; j++) {
            a = n.attributes[j];
            if (a.nodeName.toLowerCase() == "frameid")
                frameid = a.nodeValue;
            if (a.nodeName.toLowerCase() == "modes")
                modes = a.nodeValue;
        }
        jumpInArray[jumpInArray.length] = new JumpInPoint(fixHTMLString(label), frameid, modes);
    }
    _leadIn = "./toc/empty.html";
    nodes = req.responseXML.getElementsByTagName("Leadin");
    if (nodes.length > 0) {
        _leadIn = "./tpc/" + topicID + "/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";

    topicDescriptor = new topicDescriptorObj(_title, _type, topicID, 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;
        topicDescriptor.seealsoroot = saroot;
    }

    nodes = req.responseXML.getElementsByTagName("SeeAlso");
    for (var i = 0; i < nodes.length; i++) {
        n = nodes[i];
        var type = "";
        var title = "";
        var guid = "";
        var empty = false;
        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 (a.nodeName == "Empty")
                empty = true;
        }
        if (type.length > 0 && title.length > 0) {
            topicDescriptor.seealsolinks[topicDescriptor.seealsolinks.length] = new seeAlsoLink(type, title, guid, empty);
        }
    }
}

function UpdateSeeAlsoLinks(tdesc) {
    for (var i = 0; i < tdesc.seealsolinks.length; i++) {
        tdesc.seealsolinks[i].filtered = parent._getFilteredStatus(tdesc.seealsolinks[i].guid);
    }
}

function CheckSeeAlso() {
    if (topicDescriptor.seealsoroot.length == 0)
        return false;
    if (topicDescriptor.seealsolinks.length == 0)
        return false;
    if (_lmsEnvironment == "TOC") {
        if (parent.CheckSeeAlso() == false)
            return false;
        UpdateSeeAlsoLinks(topicDescriptor);
        for (var i = 0; i < topicDescriptor.seealsolinks.length; i++) {
            if (topicDescriptor.seealsolinks[i].filtered == false)
                return true;
        }
        return false;
    }
    return true;
}

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 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 "";
    }

}
