var WShell = new ActiveXObject("WScript.Shell");
var WFile = new ActiveXObject("Scripting.FileSystemObject");

var vbOKOnly = 0;
var vbOKCancel = 1;
var vbYesNo = 4;
var vbQuestion = 32;
var vbInformation = 64;
var vbCancel = 2;
var vbYes = 6;

var buzePath = getBuzePath();
var envelopePath = getEnvelopeOcxPath();
var ret = 6;
if (envelopePath!="")
    ret = WShell.Popup("Envelope.ocx is currently registered as:\n\n" + envelopePath + "\n\nDo you want to register again?", 0, "Re-register envelope?", vbYesNo+vbQuestion);

if (ret==6)
    registerEnvelopeOcx();



function getBuzePath() {
    // look for bin/buze.exe in script folder and parents
    var buzePath = WScript.ScriptFullName.replace(/\//gim, "\\");
    buzePath = checkPath(buzePath.substr(0, buzePath.lastIndexOf("\\")+1));
    
    while (!WFile.FileExists(buzePath + "buze.exe")) {
        buzePath = WFile.GetParentFolderName(buzePath) + "\\";
        if (buzePath=="\\") break;
    }
    return buzePath;
}

function registerEnvelopeOcx() {
    // register our envelope.ocx
    var registerCommand = "regsvr32 /s " + buzePath + "lib\\envelope.ocx";
    var exec = WShell.Exec(registerCommand);
    while (exec.Status == 0) WScript.Sleep(100);

    if (exec.ExitCode!=0) {
        WScript.Echo("Envelope registration failed");
    } else
        WScript.Echo("Registered local envelope.ocx");
    //WScript.Echo(registerCommand + ", exit code = " + exec.ExitCode);
}

function getEnvelopeOcxPath() {
    // envelope.ocx, HKEY_CLASSES_ROOT\CLSID\{396D2EB7-53AA-11D1-A1D9-4676EE000000}\InprocServer32 (Default)
    try {
        // returns f ex c:\buzz\envelope.ocx
        return WShell.RegRead("HKCR\\CLSID\\{396D2EB7-53AA-11D1-A1D9-4676EE000000}\\InprocServer32\\");
    } catch (e) {
        return null;
    }

}

// ensures there is an ending backslash on the filename
function checkPath(path) {
    if (path.length==0) return "";
    if (path.charAt(path.length-1)!="\\")
        path+="\\";
        
    return path;
}

