var objApp = WizExplorerApp;
var objCommon = objApp.CreateWizObject("WizKMControls.WizCommonUI");
var objSettings = objApp.CreateWizObject("WizKMCore.WizSettings");

objSettings.Open(objApp.SettingsFileName);

function GetVoiceName() {
    return objSettings.StringValue("Plugin_Speech", "VocieName");
}

function CallWizTTS(text, voiceName) {
    var tmpfilename = objCommon.GetATempFileName(".txt");
    objCommon.SaveTextToFile(tmpfilename, text, "unicode");
    //
    var exefilename = objApp.AppPath + "WizShell.exe";
    var params = "\"" + objApp.AppPath + "WizTools.dll" + "\" WizTTSSpeech2 /VoiceName=" + voiceName + " /TextFileName=" + tmpfilename;
    //
    objCommon.RunExe(exefilename, params, false);
}

var objWindow = objApp.Window;
var objCurrentHtmlDocument = objWindow.CurrentDocumentHtmlDocument;
//
var voiceName = GetVoiceName();
//
function SpeakDocument(doc, sel) {
    if (null == doc)
        return;
    //
    var text = null;
    //
    if (sel) {
        var selection = doc.selection;
        if (null == selection)
            return;
        var range = selection.createRange();
        if (null == range)
            return;
        text = range.text;
    }
    else {
        var text = doc.body.innerText;
    }
    //
    if (null == text)
        return;
    if (text.length == 0)
        return;
    //
    CallWizTTS(text, voiceName);
}

SpeakDocument(objCurrentHtmlDocument, false);
