/**
 * @author Microcraft eLearning
 * @version 1.0
 * @copyright Microcraft eLearning 2010
 */
/**
 * WebAuthor runtime object
 */
//<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>

Author = {
    lessonVersion:16,
    log:function (msg) {
        alert(msg);
    },
    showAD:false,
    showLoginWindow:true,
    processTime:0,
    isHTA:(window.external == null),
    isFileSystem:function () {
        var fileUrl = /file:(.)+/gi;
        var loc = window.location.toString();
        return loc.match(fileUrl);
    },
    exitConfirm:true,
    isFromMenu:false,
    loginFromMenu:"",
    screensizeDiv:null,
    noLoginWindow:false,
    goingBack:false,
    goingUpperMenu:false,
    goingToSubMenu:false,
    closeActionsDone:false,
    optionBMString:"",
    variableBMString:"",
    AP:false,
    isHTML5:true,
    useFlashInIE:true,
    isFlash9:false,
    userDefinedScormResult:false,
    popupQC:true,
    isAuthorViewer:function () {
        return navigator.userAgent.match(/AuthorViewer/i);
    },
    isIOS:function () {
        return ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) && (Author.isAuthorViewer() == null);
    },
    isIEMobile:function () {
        return ((navigator.userAgent.match(/IEMobile/i)));
    },
    isAndroid: function () {
        return BrowserDetect.browser == "Android";
    },
    isChrome: function () {
        return BrowserDetect.browser == "Chrome";
    },
    titleImage:{
        timer:null,
        cancelled:false
    },
    login:{},
    frame:{
        useFrame:false,
        lessonFrame:"NONE",
        repeat:"NONE"
    },
    pressedKeyCode:0,
    resultSent:false,
    autoZoom:true,
    zoomRatio:1,
    version:"1.2.0222",
    lessonName:"",
    location:"",
    resourcePath:"resources/",
    traineeID:"",
    qcURL:"",
    qcKey:0,
    passRate:100,
    setWebResult:false,
    bookMark:false,
    sendTo:"",
    networkFields:"0000000000",
    scorm:false,
    Testing:false,
    repeatLesson:false,
    eventFromVariableWatch: false,
    browserBackgroundType: "COLOR",
    browserBackgroundImage: "",
    browserBackgroundColor: "#FFFFFF",
    browserBackgroundImageMode: "Scaled",
    Test:{
        type:"full",
        startLessonNode:null,
        startElement:null,
        resourcePath:null,
        startAtRandom:false
    },
    actionKeyMap:new Ext.util.MixedCollection(),
    keyNameMap:new Array(222),
    lastError:{
        errNumber:"",
        errDescription:""
    },
    speech:{
        id:""

    },
    AudioInitialized: false,
    ActionTypeReg:/(PROGRESSBAR|BACKGROUND|FLVPLAYERACTION|SOUNDACTION|PAUSE|VARIABLE|VISIBLEACTION|WEBACTION|TXTEXTACTION|TEXTACTION|IMAGEACTION|CUSTOMBUTTON|DDBUTTON|TEXTFIELD|TEXTFIELD|RADIOBUTTON|COMBOBOX|CHECKBOX|HOTSPOT|SPECIAL)-(\d+)(-(.+))?/
}
;

/**
 * Initialize the web lesson
 */
function initializeLesson() {
    var lessonXML = "lesson.xml";
    Author.lessonXMLDoc = null;
    if (window.ActiveXObject) {
        Author.lessonXMLDoc = new ActiveXObject("Microsoft.XMLDOM");
        Author.lessonXMLDoc.validateOnParse = false;
        Author.lessonXMLDoc.onreadystatechange = function () {
            switch (Author.lessonXMLDoc.readyState) {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    if (Author.lessonXMLDoc.parseError < 0) {
                        switch (Author.lessonXMLDoc.parseError.errorCode) {
                            case -2146697210:
                                alert('Author cannot find the lesson description file.');
                                break;
                            default:
                                var errStr = "ErrorCode: " + Author.lessonXMLDoc.parseError.errorCode;
                                errStr += "\nReason: " + Author.lessonXMLDoc.parseError.reason;
                                errStr += "\nFilePosition: " + Author.lessonXMLDoc.parseError.filepos;
                                errStr += "\nLine: " + Author.lessonXMLDoc.parseError.line;
                                errStr += "\nLinePosition: " + Author.lessonXMLDoc.parseError.linepos;
                                errStr += "\nsrcURL: " + Author.lessonXMLDoc.parseError.url;
                                errStr += "\nSrcText: " + Author.lessonXMLDoc.parseError.srcText;
                                alert(errStr);
                                break;
                        }
                    }
                    else {
                        initlizeLesson2();
                        return;
                    }
                    break;
            }
        };
        if (Author.lessonXMLDoc != null) {
            Author.lessonXMLDoc.async = true;
            if (!Author.lessonXMLDoc.load(Author.resourcePath + lessonXML)) {
                alert("Invalid lesson description file: " + lessonXML);
            }
            return;
        }
        else {
            alert("Can't initlise XML parser.");
            return;
        }
    }
    else if (window.XMLHttpRequest) {
        var xmlhttp = new window.XMLHttpRequest();
        xmlhttp.open("GET", Author.resourcePath + lessonXML, false);
        try {
            xmlhttp.send(null);
        }
        catch (err) {
            alert(err);
            return;
        }
        Author.lessonXMLDoc = xmlhttp.responseXML;
        if (xmlhttp.responseXML == null) {
            alert("Invalid lesson description file: " + lessonXML);
            return;
        }
        initlizeLesson2();
        return;
    }
    else {
        if (document.implementation.createDocument) {
            Author.lessonXMLDoc = document.implementation.createDocument("", "", null);
        }
        if (Author.lessonXMLDoc != null) {
            Author.lessonXMLDoc.async = false;
            if (!Author.lessonXMLDoc.load(Author.resourcePath + lessonXML)) {
                alert("Invalid lesson description file: " + lessonXML);
                return;
            }
            initlizeLesson2()
        }
        else {
            alert("Can't initlise XML parser.");
            return;
        }
    }
    alert("Can't initlise XML parser.");
}
function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}


window.onorientationchange = function () {
    try {
        var vW = "device-width";
        var vH = "device-height";
        switch (window.orientation) {
            case -90:
            case 90:
               // vW ="device-height";
             //   vW = "device-width";
                break;
            default:
                break;
        }
        var viewPort = document.getElementById('viewportmeta');
        var viewPortStr = Ext.String.format("width={0}, height={1}, initial-scale=1,user-scalable=no,maximum-scale=1", vW,vH);

        viewPort.setAttribute('content', viewPortStr);
        setTimeout(function () {
            Author.LessonManager.setViewPort();
        }, 300);
    } catch (err) {
    }
};
function onLessonManager_InitializedLesson() {
    //Setup some handy functions.
    Author.log = function (info) {
        Author.LessonManager.log(info);
    };
    Author.showCurrentListActions = function () {
        Author.log(Author.CurrentStateManager.getCurrentActions());
    };
    Ext.getDoc().dom.title = Author.LessonManager.AuthorLesson.Name;
    AuthorCommons.setupKeyNameMap();
    Ext.get("loadingDIV").remove();
    Author.closeActionsDone = false;
    Author.LessonManager.setViewPort();
    Author.LessonManager.doLogin(onLessonManager_DoneLogin);
    //  Author.LessonManager.checkScreenSize(onLessonManager_CheckedScreenSize);
    //checkUrlParams();
    //checkScreenSize();
}
function onLessonManager_CheckedScreenSize() {
    if (Author.LessonManager.ScreensizeDiv) {
        Author.LessonManager.ScreensizeDiv.remove();
    }

    Author.LessonManager.doLogin(onLessonManager_DoneLogin);
    // showLesson();
}
function onLessonManager_DoneLogin(loginResult) {
    if (loginResult) {
        Author.LessonManager.initializeStateManager();
        showLesson();
    }
}

/**
 * Call this after all the initializations are done.
 */
function showLesson() {
    //Author.log("Is ios: "+ (Author.isIOS()));

    Author.LessonManager.AuthorLesson.StartTime = new Date().getTime();
    setInterval(function () {
        try {
            if (Author.DisplayManager.BackgroundObject) {
                Author.DisplayManager.BackgroundObject.center();
            }
        } catch (err) {
        }
    }, 500);
    Author.DisplayManager.showLesson(Author.LessonManager.AuthorLesson, Author.LessonManager.StartNodeID, Author.LessonManager.StartElementID);

}
ShowPlayOnMobile: false;
AutoPlayDisabled: false;
function AudioPlayed()
{
    if(Author.AudioInitialized)
    {
        return;
    }
    Author.AudioInitialized = true;
    
    var audioPlayer = document.getElementById("html5audio");
    audioPlayer.removeEventListener("onplay", AudioPlayed);
    initializeLesson3();
};
function DisplayPlayButton ()
{
    if (Author.AudioInitialized)
    {
        return;
    }
    
    var playdiv = document.getElementById("playDiv");
    var playButton = document.getElementById("playButton")
    playDiv.style.display = "flex";
    playButton.onclick = function(evt, el, o) { 
        if (evt)  evt.stopPropagation();//Prevents advance to next page when image clicked
        playdiv.style.display = "none";
        var audio = document.getElementById("html5audio");
        audio.src = "lib/media/silence.mp3";
        audio.play();
    }
}

function initlizeLesson2() {
    var preferences = Author.lessonXMLDoc.getElementsByTagName('lessonPreference')[0];
    ShowPlayOnMobile = XmlHelper.getBooleanAttribute(preferences, 'showPlayOnMobile');
    
    if(ShowPlayOnMobile) {//Set in the lesson preferences UI
        try 
        {
            var audio = document.getElementById("html5audio");

            audio.src = "lib/media/silence.mp3";
            audio.onplay = AudioPlayed;
            
            var success = audio.play();//Try to audo play incase user is in a brower that supports it.
            if(success)
            {
                success.catch(function(e){
                    DisplayPlayButton();//Audio failed to play, display the play button
                });
            }
            
        }
        catch (ex)
        {
            DisplayPlayButton();//Audio failed to play, display the play button
        }
    }
    else
    {
        initializeLesson3();//Play button disabled. in Lesson Preferences
    }
   
}

function initializeLesson3() {

    Author.AudioManager = new AudioManager();
    Author.VideoManager = new VideoManager();
    Author.DisplayManager = new DisplayManager();
    Author.VariableManager = new VariableManager();
    Author.CurrentStateManager = new CurrentStateManager();
    Author.LessonManager = new LessonManager();
    Author.LessonManager.initializeLesson(onLessonManager_InitializedLesson);
}


function LoadConstantVariables() {
    try {
        var constantVariableXML = Author.lessonXMLDoc.getElementsByTagName("constants")[0];
        var constantVariables = constantVariableXML.getElementsByTagName("constantVariable");
        var varCount = constantVariables.length;
    }
    catch (err) {
        //alert("LoadConstantVariables : "+err.description);
        return;
    }
    //alert(varCount);
    for (var i = 0; i < varCount; i++) {
        try {
            LoadConstantVariable(constantVariables[i]);
        }
        catch (err) {
            alert("LoadConstantVariables : " + err.description);
        }
    }
}
/**
 * Fire an event on a HTML element
 *
 * @param {Object} element
 * @param {Object} event
 */
function fireEvent(element, event) {
    if (document.createEvent) {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true);
        return !element.dispatchEvent(evt);
    }
    if (document.createEventObject) {
        var evt = document.createEventObject();
        return element.fireEvent('on' + event, evt)
    }
    else {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true);
        return !element.dispatchEvent(evt);
    }
}
function closeBrowserWindow() {
    if (Author.isAuthorViewer()) {
        window.location = "author:ExitLesson";
        return;
    }
    if (Author.isFromMenu) {
        var loc = '../index.html?FromLesson=true';
        if (Author.loginFromMenu.length > 0) {
            loc += "&LoginID=" + Author.loginFromMenu;
        }
        window.location = loc;
        return;
    }
    if (Author.AP) {
        window.location = '../default.htm';
    }
    else {
        window.open('', '_self', '');
        window.close();
        top.window.close();
        setTimeout(function () {
            Ext.MessageBox.show({
                msg:"<p>You have exited the eLearning module. Please close this window.</p>",
                title:"eLearning module finished",
                width:380
            });
        }, 1000)
    }
}
/**
 * Things to be done when the lesson ends.
 */
function endLesson(showAD) {
    showAD = Author.showAD;
    if (Author.isFromMenu) {
        showAD = false;
    }
    Author.current.currentNode = Author.lessonNodes.nodes.itemAt(0);
    if (Author.current.currentNode.showEndOnCompletion && !Author.current.currentNode.endListShown) {
        Author.current.currentNode.endListShown = true;
        showLessonEndList(Author.current.currentNode.endList);
    }
    if (Author.doingLessonEnding) {
        return;
    }
    if (Author.pause != null && Author.pause.cancelType != 0) {
        Author.pause = null;
        window.clearTimeout(Author.actionTimer);
    }
    Author.mediaList.eachKey(function (key, object) {
        try {
            if (Ext.isIE && !Author.useFlashInIE) {
                object.mediaObject.dom.controls.stop();
                object.mediaObject.dom.settings.mute = true;
            }
        }
        catch (err) {
        }
    });
    if (!Author.scorm && Author.setWebResult && !Author.resultSent) {
        var v1, v2, v3, v4, v5, v6, v7, v8, v9, v10;
        v1 = parseInt(Author.networkFields.substring(0, 1));
        v2 = parseInt(Author.networkFields.substring(1, 2));
        v3 = parseInt(Author.networkFields.substring(2, 3));
        v4 = parseInt(Author.networkFields.substring(3, 4));
        v5 = parseInt(Author.networkFields.substring(4, 5));
        v6 = parseInt(Author.networkFields.substring(5, 6));
        v7 = parseInt(Author.networkFields.substring(6, 7));
        v8 = parseInt(Author.networkFields.substring(7, 8));
        v9 = parseInt(Author.networkFields.substring(8, 9));
        v10 = parseInt(Author.networkFields.substring(9, 10));
        var resultLine = "";
        resultLine += "?TraineeID=" + Author.traineeID;
        if (v1 == 1)
            resultLine += "&L=" + Author.lessonName + "_HTML";
        if (v2 == 1)
            resultLine += "&SD=" + Ext.util.Format.date(Author.variables.get(variableName("STARTTIME")).value);
        if (v3 == 1)
            resultLine += "&ED=" + Ext.util.Format.date(new Date());
        if (v4 == 1)
            resultLine += "&ST=" + Ext.util.Format.date(Author.variables.get(variableName("STARTTIME")).value, "g:i:s A");
        if (v5 == 1)
            resultLine += "&ET=" + Ext.util.Format.date(new Date(), "g:i:s A");
        if (v6 == 1)
            resultLine += "&S=" + Author.variables.get(variableName("LESSONSCORE")).value;
        if (v7 == 1)
            resultLine += "&T=" + Author.variables.get(variableName("LESSONTOTAL")).value;
        if (v8 == 1) {
            var pass = "N";
            if (parseInt(Author.variables.get(variableName("LESSONTOTAL")).value) > 0) {
                if (parseInt(Author.variables.get(variableName("LESSONSCORE")).value) / parseInt(Author.variables.get(variableName("LESSONTOTAL")).value) * 100 > Author.passRate) {
                    pass = "P";
                }
                else {
                    pass = "F";
                }
            }
            resultLine += "&P=" + pass;
        }
        if (v9 == 1)
            resultLine += "&PR=" + Author.passRate;
        if (v10 == 1)
            resultLine += Author.variables.get(variableName("WEBINFO")).value;
        //this line is for australia post only	
        //resultLine += "&strWCC="+ top.frGlobal.gintWorkcentre + top.frGlobal.gintCounter;
        var requestURL = Author.sendTo + resultLine;
        var httpIFrame = Author.backgroundObject.getContent().createChild({
            tag:"iframe",
            frameborder:Ext.isIE ? "0" : "1",
            style:"position:absolute;background-color:#fff;width:0px;height:0px;left:0px;top:-9999px"
        });
        httpIFrame.dom.src = eval(Ext.encode(requestURL));
        httpIFrame.on("load", function (e) {
            Author.resultSent = true;
            try {
                iText = httpIFrame.dom.contentWindow.document.body.innerText;
                if (iText.indexOf("success!") >= 0) { //success.
                    Ext.MessageBox.alert('Result', 'Result has been sent successfully.', function () {
                        closeBrowserWindow();
                    });
                    ////
                }
                else {
                    Ext.MessageBox.alert('Result', 'Result has been sent.', function () {
                        closeBrowserWindow();
                    });
                }
            }
            catch (err) {

                //  Ext.MessageBox.alert('Result', 'Result is not sent successfully.', function(){
                closeBrowserWindow();
                //});
            }
        });
    }
    else {
        if (showAD) {
            Ext.MessageBox.show({
                msg:'<p align = "center">Developed by <a href="http://www.microcraft.org">Microcraft</a>.</p>',
                width:350,
                wait:true,
                waitConfig:{
                    interval:50,
                    duration:4000,
                    increment:70,
                    fn:function () {
                        Ext.MessageBox.hide();
                        closeBrowserWindow();
                    }
                }
            });
        }
        else {
            closeBrowserWindow();
        }
    }
}


/**
 * Convert millisends to the scorm time format.
 *
 * @param {int} intTotalMilliseconds
 * @param {Object} blnIncludeFraction
 */
function ConvertMilliSecondsToSCORMTime(intTotalMilliseconds, blnIncludeFraction) {
    var intHours;
    var intintMinutes;
    var intSeconds;
    var intMilliseconds;
    var intHundredths;
    var strCMITimeSpan;
    if (blnIncludeFraction == null || blnIncludeFraction == undefined) {
        blnIncludeFraction = true;
    }
    //extract time parts
    intMilliseconds = intTotalMilliseconds % 1000;
    intSeconds = ((intTotalMilliseconds - intMilliseconds) / 1000) % 60;
    intMinutes = ((intTotalMilliseconds - intMilliseconds - (intSeconds * 1000)) / 60000) % 60;
    intHours = (intTotalMilliseconds - intMilliseconds - (intSeconds * 1000) - (intMinutes * 60000)) / 3600000;
    /*
     deal with exceptional case when content used a huge amount of time and interpreted CMITimstamp
     to allow a number of intMinutes and seconds greater than 60 i.e. 9999:99:99.99 instead of 9999:60:60:99
     note - this case is permissable under SCORM, but will be exceptionally rare
     */
    if (intHours == 10000) {
        intHours = 9999;
        intMinutes = (intTotalMilliseconds - (intHours * 3600000)) / 60000;
        if (intMinutes == 100) {
            intMinutes = 99;
        }
        intMinutes = Math.floor(intMinutes);
        intSeconds = (intTotalMilliseconds - (intHours * 3600000) - (intMinutes * 60000)) / 1000;
        if (intSeconds == 100) {
            intSeconds = 99;
        }
        intSeconds = Math.floor(intSeconds);
        intMilliseconds = (intTotalMilliseconds - (intHours * 3600000) - (intMinutes * 60000) - (intSeconds * 1000));
    }
    //drop the extra precision from the milliseconds
    intHundredths = Math.floor(intMilliseconds / 10);
    //put in padding 0's and concatinate to get the proper format
    strCMITimeSpan = ZeroPad(intHours, 4) + ":" + ZeroPad(intMinutes, 2) + ":" + ZeroPad(intSeconds, 2);
    if (blnIncludeFraction) {
        strCMITimeSpan += "." + intHundredths;
    }
    //check for case where total milliseconds is greater than max supported by strCMITimeSpan
    if (intHours > 9999) {
        strCMITimeSpan = "9999:99:99";
        if (blnIncludeFraction) {
            strCMITimeSpan += ".99";
        }
    }
    return strCMITimeSpan;
}
/**
 * ZeroPad a given number
 *
 * @param {Object} intNum
 * @param {Object} intNumDigits
 */
function ZeroPad(intNum, intNumDigits) {
    var strTemp;
    var intLen;
    var i;
    strTemp = new String(intNum);
    intLen = strTemp.length;
    if (intLen > intNumDigits) {
        strTemp = strTemp.substr(0, intNumDigits);
    }
    else {
        for (i = intLen; i < intNumDigits; i++) {
            strTemp = "0" + strTemp;
        }
    }
    return strTemp;
}
/**
 * When the document is ready, initialize the lesson.
 */
Ext.onReady(function () {
    setTimeout(function () {
        initializeLesson();
    }, 500);
});

function isUrl(s) {
    var regexp = /(ftp|http|https|mailto):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
    return regexp.test(s);
}
function isCapslock(e) {
    e = (e) ? e : window.event;
    var charCode = false;
    if (e.which) {
        charCode = e.which;
    }
    else if (e.keyCode) {
        charCode = e.keyCode;
    }
    var shifton = false;
    if (e.shiftKey) {
        shifton = e.shiftKey;
    }
    else if (e.modifiers) {
        shifton = !!(e.modifiers & 4);
    }
    if (charCode >= 97 && charCode <= 122 && shifton) {
        return true;
    }
    if (charCode >= 65 && charCode <= 90 && !shifton) {
        return true;
    }
    return false;
}
function ccos(angle) {
    return Math.cos(Math.PI * angle / 180);
}
function ssin(angle) {
    return Math.sin(Math.PI * angle / 180);
}
function getCheckBoxValues() {
    var checkBoxStr = "";
    for (var index = Author.interactionList.startIndex; index <= Author.interactionList.endIndex; index++) {
        var action = Author.current.currentList.itemAt(index);
        if (action.objectType == "CHECKBOXOBJECT") {
            checkBoxStr += (action.button.dom.checked) ? "T" : "F";
        }
    }
    return checkBoxStr;
}
function curve(p, c) {
    var k = (Math.atan((1 - 0.5) * c * Math.PI) - Math.atan((0 - 0.5) * c * Math.PI)) / Math.PI;
    return -Math.atan((p - 0.5) * c * Math.PI) / (Math.PI * k) + 0.5;
}
/**
 * Set the background for the lesson frame.
 */
function setLessonFrame() {
    if (Author.frame.useFrame && Author.frame.lessonFrame != "none") {
        var bodyEl = Ext.getBody();
        bodyEl.setStyle("background-image", "url(" + Author.resourcePath + Author.frame.lessonFrame + ")");
        var repeat = new Array("repeat-x", "repeat-y", "repeat", "no-repeat");
        bodyEl.setStyle("background-repeat", repeat[Author.frame.repeat]);
        if (repeat[Author.frame.repeat] == "no-repeat") {
            bodyEl.setStyle("background-position", "50% 50%");
        }
    }
}
function flashResult(params) { //flashResult
    if (typeof(Author.doFlashResponse) == 'function') {
        Author.doFlashResponse(params);
    }
}
function setFlashVariable(params) { //flashResult
    if (typeof(Author.doFlashResponse) == 'function') {
        Author.doFlashResponse(params);
    }
}
function getNodePath(node) {
    if (node.parent != 0) {
        return getNodePath(Author.lessonNodes.nodes.get(node.parent)) + "/" + getProperNodeName(false, node.name);
    }
    else {
        return getProperNodeName(false, node.name);
    }
}
function logGoogleAnalytics(event, description) {
    if (typeof(_gaq) != 'undefined') {
        if (_gaq.push) {
            _gaq.push(["CFATracker._trackEvent", "CFAHBSAT", event, description]);
        }
    }
    return;
}
function playMp3WithHtml5(url) {
    if (!Author.isHTML5) {
        return;
    }
    var html5Player = Ext.get("html5audio");
    try {
        html5Player.dom.setAttribute("src", url);
        html5Player.dom.load();
        html5Player.dom.play();
        html5Player.removeListener("ended", playAudioSequence);
        html5Player.addListener("ended", playAudioSequence);
    }
    catch (err) {
    }
}
var speakList = new Array();
function getMp3Name(n, baseUrl) {
    if (typeof baseUrl == 'undefined') {
        baseUrl = "";
    }
    n = n.toLowerCase();
    switch (n) {
        case "0":
        case "1":
        case "2":
        case "3":
        case "4":
        case "5":
        case "6":
        case "7":
        case "8":
        case "9":
        case "a":
        case "b":
        case "c":
        case "d":
        case "e":
        case "f":
        case "g":
        case "h":
        case "i":
        case "j":
        case "k":
        case "l":
        case "m":
        case "n":
        case "o":
        case "p":
        case "q":
        case "r":
        case "s":
        case "t":
        case "u":
        case "v":
        case "w":
        case "x":
        case "y":
        case "z":
            return baseUrl + n.toUpperCase() + ".mp3";
    }
}
function playAudioSequence() {
    if (speakList.length == 0) {
        if (Author.speech.id != "0") {
            Author.speech.id = "0";
            window.clearTimeout(Author.actionTimer);
            Author.actionTimer = setTimeout(showList, 10);
        }
        return;
    }
    var baseAudioUrl = "lib/media/";
    var n = speakList.pop();
    playMp3WithHtml5(getMp3Name(n, baseAudioUrl));
}
function echoKeyPressed(keyCode) {
    var mp3FileName = "";
    switch (keyCode) {
    }
    if (mp3FileName != "") {
        var baseAudioUrl = "lib/meida/";
        mp3FileName = baseAudioUrl + mp3FileName + ".mp3";
        playMp3(mp3FileName);
    }
}
function playMp3(mp3url) {
    if (!Author.isFlash9) {
        playMp3WithHtml5(mp3url);
    }
    else {
        var mp3Player = Ext.get("flashSpeaker").dom;
        if (Author.isHTA) {
            var mp3Player = Ext.get("flashSpeakerHTA").dom;
        }
        //alert(mp3Player.speakText +","+number);
        try {
            mp3Player.playMp3(mp3url);
        }
        catch (err) {
            // alert(err);
        }
    }
}
function speakText(text, id) {
    if (typeof(id) == 'undefined') {
        id = "";
    }
    // Author.isFlash9 = false;
    if (!Author.isFlash9) {
        if (!Author.isHTML5) {
            return;
        }
        speakList = new Array();
        for (var i = text.length - 1; i >= 0; i--) {
            speakList.push(text.charAt(i));
        }
        playAudioSequence();
    }
    else {
        //  var mp3Player = Ext.get("flashSpeaker").dom;
        // if (Author.isHTA) {
        var mp3Player = Ext.get("flashSpeakerHTA").dom;
        // }
        if (!Ext.isIE) {
            var mp3Player = Ext.get("flashSpeakerEmbed").dom;
        }
        try {
            mp3Player.speakText(text, "lib/media/", id);
        }
        catch (err) {
            alert("SpeakText: Flash player does not have the permission to load file on the local file system.");
        }
    }
}
function Reader_Completed(id) {
    if (typeof(id) == 'undefined') {
        id = "";
    }
    if (id != "") {
        if (Author.speech.id == id) {
            //alert("Completed: " + id);
            Author.speech.id = "0";
        }
        window.clearTimeout(Author.actionTimer);
        Author.actionTimer = setTimeout(showList, 10);
    }
}
function Reader_Error(des) {
    alert("Error:\n" + des);
}

var print = function (object) {
    var str = '';
    if (typeof(object) == 'string' || typeof(object) == 'number' || typeof(object) == 'undefined') {
        return object;
    }
    var typeString = object.toString();
    switch (typeString) {
        case '[object Array]':
            for (var i = 0; i < object.length; i++) {
                str += "[" + i + "]: " + print(object[i]);
            }
            return "[\n" + str + "]";
            break;
        case '[object Date]':
            return object.toLocaleTimeString();
            break;
        default:
            for (property in object) {
                var type = typeof(object[property]);
                switch (type) {
                    case 'object':
                        str += property + ': ' + typeof(object[property]) + ';\n';
                        break;
                    case 'function':
                        str += property + ': ' + typeof(object[property]) + ';\n';
                        break;
                    default:
                        str += property + ': ' + object[property] + ';\n';
                }
            }
            break;
    }
    return str;
};
