var objApp = WizExplorerApp;
var objWindow = objApp.Window;
var objDocuments = objWindow.DocumentsCtrl.SelectedDocuments;
if (objDocuments && objDocuments.Count >= 1) {
    var objDoc = objDocuments.Item(0);
    var objCommonUI = objApp.CreateWizObject("WizKMControls.WizCommonUI");
    //
    var reg = new RegExp('[/\\:*?*<>|]', 'g');
    var name = objDoc.Title;
    if (reg.test(objDoc.Title)) {
        name = makeValidFileName(name);
    }
    //
    var filename = objCommonUI.SelectWindowsFileEx(false, "Mht files (*.mht)|*.mht|Html files (*.htm)|*.htm|Zip files (*.zip)|*.zip|Ziw files (*.ziw)|*.ziw|Text files (*.txt)|*.txt|PDF files (*.pdf)|*.pdf|", name, "mht");
    //
    if (filename && filename.length > 0) {
        //
        if (filename.length >= 4 && filename.length - 4 == filename.lastIndexOf(".txt")) {
            var text = objDoc.GetText(0);
            objCommonUI.SaveTextToFile(filename, text, "unicode");
        }
        else if (filename.length >= 4 && filename.length - 4 == filename.lastIndexOf(".zip")
            || filename.length >= 4 && filename.length - 4 == filename.lastIndexOf(".ziw")) {
            var localprotected = objDoc.LocalDataProtect;
            if (1 == localprotected) {
                objDoc.LocalDataProtect = 0;
            }
            var srcFileName = objDoc.FileName;
            objCommonUI.CopyFile(srcFileName, filename);
            if (1 == localprotected) {
                objDoc.LocalDataProtect = 1;
            }
        }
        else if(filename.length >= 4 && filename.length - 4 == filename.lastIndexOf(".pdf")){
            objDoc.SaveToHtml(filename, 0x40000);
        }
        else {
            var flags = 0x4 | 0x200 | 0x400;  //utf-8
            if (filename.length >= 4 && filename.length - 4 == filename.lastIndexOf(".htm")) {

            }
            else {
                if (filename.length < 4 || filename.length - 4 != filename.lastIndexOf(".mht")) {
                    filename += ".mht";
                }
            }
            //
            if (filename.length < 4 || filename.length - 4 == filename.lastIndexOf(".mht")) {
                flags |= 0x8;  //mht format
            }
            //
            objDoc.SaveToHtml(filename, flags);
        }
    }
}
function makeValidFileName(name) {
    name = name.replace(/(^\s*)|(\s*$)/g, "");
    //
    name = name.replace(/\//g, "-");
    name = name.replace(/\\/g, "-");
    name = name.replace(/\?/g, "-");
    name = name.replace(/\:/g, "-");
    name = name.replace(/\*/g, "-");
    name = name.replace(/\|/g, "-");
    name = name.replace(/\</g, "-");
    name = name.replace(/\>/g, "-");
    name = name.replace(/\r/g, "-");
    name = name.replace(/\n/g, "-");
    name = name.replace(/\t/g, "-");
    name = name.replace(/\%/g, "-");
    name = name.replace(/\'/g, "-");
    name = name.replace(/\"/g, "-");
    //
    if (name.length > 50)
        name = name.substr(0, 50);
    //
    return name;
}
