// This function attempts to load the Nexus plugin, for either IE or Mozilla based browsers. If it succeeds it
// means that BankID säkerhetsprogram is installed. If it fails it is not installed.
function isInstalled() {
    var browser = navigator.appName;
    var isInst = false;
    try {
        var xObj = new ActiveXObject("Nexus.VersionCtl");
        if (xObj) {
            isInst = true;
        }
    }
    catch (e) {
    }
    if(!isInst) {
        if (navigator.plugins) {
            if (navigator.plugins.length > 0) {
                if (navigator.mimeTypes && navigator.mimeTypes["application/x-personal-version"]) {
                   if (navigator.mimeTypes["application/x-personal-version"].enabledPlugin) {
                        isInst = true;
                    }
                }
            }
        }
    }
    return isInst;
}
// This function looks for the substring “best_before”. If it exists it means that a correct version
// of BankID säkerhetsprogram is installed. Otherwise it needs to be upgraded.
function versionOk(verStr){
	return (verStr.search("best_before") >= 0);
}
// This function compares the value of “best_before” with current date. If it is up to date, the
// installed version has been verified. If is not up to date, the installed version must be verified
function versionVerified(verStr){
	var ct = new Date();
	var currentUsrTime = Math.round(ct.getTime()/1000);
	var index = verStr.search("best_before");
	if (index < 0) {
        // Syntax error in the version string, return false.
	    return false;
	}
	var subStr = verStr.substring(index+12);
	index = subStr.search("&");
	if (index < 0) {
		// Syntax error in the version string, return false.
			return false;
	}
	var bfdStr = subStr.substring(0,index);
	// The bfdStr should now hold the value we are looking for.
	// Compare it with current time. If best_before is greater than
	// current time the control passes.
	return (bfdStr > currentUsrTime);
}

// This function checks if BankID säkerhetsprogram is installed and has the correct version.
// If the plugin is missing or is outdated it returns information about where to
// get or update the plugin.
function isVerified() {
    var statusMessage = "";
    var retVal;
    if (isInstalled()) {
        var plugin;
        plugin = document.getElementById("versionPlugin");
        retVal = plugin.GetVersion();
        if (retVal != 0) {
            if (versionOk(retVal)) {
                if (versionVerified(retVal)) {
                    // Everything is ok.
                } else {
                    statusMessage = "<BR>BankID s&auml;kerhetsprogram i din dator beh&ouml;ver kontrolleras. Det " +
					"g&ouml;r du snabbt och enkelt i det nya f&ouml;nster som &ouml;ppnas n&auml;r du klickar p&aring; l&auml;nken:<BR>" +
	                "<BR><a HREF='https://install.bankid.com/bisp' target='_blank'>install.bankid.com</a><BR>";
                }
            } else {
                statusMessage = "<BR> Din version av BankID s&auml;kerhetsprogram beh&ouml;ver uppgraderas innan du kan logga in. Det " +
			    "g&ouml;r du i det nya f&ouml;nster som &ouml;ppnas n&auml;r du klickar p&aring; l&auml;nken:<BR>" +
	            "<BR><a HREF='https://install.bankid.com/rp' target='_blank'>install.bankid.com</a><BR>";
            }
        } else {
             statusMessage = "<BR>Ett fel har uppst&aring;tt d&aring; versionen av BankID s&auml;kerhetsprogram skulle kontrolleras, f&ouml;lj f&ouml;ljande l&auml;nk f&ouml;r ytterligare kontroller:<BR>" +
	         "<BR><a HREF='https://install.bankid.com/rp' target='_blank'>install.bankid.com</a><BR>";
        }
    } else {
        statusMessage = "<BR> Innan du kan anv&auml;nda ditt BankID beh&ouml;ver du installera BankID s&auml;kerhetsprogram. Det g&ouml;r du i det nya f&ouml;nster som &ouml;ppnas n&auml;r du klickar p&aring; l&auml;nken:<BR>" +
	    "<BR><a HREF='https://install.bankid.com/rp' target='_blank'>install.bankid.com</a><BR>";
    }
    return statusMessage;
}
// This function calls the Nexus BankID säkerhetsprogram and sets
// the parameters necessary for authentication. 
function authenticate(challenge) {
    var retVal;
    var errorMessage = isVerified();
    if (errorMessage == "") { // Means everything is ok.
        var plugin;
        plugin = document.getElementById("authPlugin");
        plugin.SetParam('Challenge', challenge);
        // Use only in production.
        plugin.SetParam('Policys', 'MS4yLjc1Mi43OC4xLjE7MS4yLjc1Mi43OC4xLjI=');
        retVal = plugin.PerformAction('Authenticate');
        if (retVal == 0) { // Authentication ok.
            signature = plugin.GetParam('Signature');
            var sign = document.getElementById("signature");
            sign.value = signature;
            document.aspnetForm.submit();
        } else {
            retVal = plugin.GetLastError();
            var errMsg = document.getElementById("errorMessage");
            errMsg.innerHTML = "N&aring;gonting blev fel vid inloggning. Felkod: " + retVal;
        }
    } else { // Plugin is missing or is outdated.
        var errMsg = document.getElementById("errorMessage");
        errMsg.innerHTML = errorMessage;
    }
}
// This function calls the Nexus BankID säkerhetsprogram and sets
// the parameters necessary for signing. 
function sign(nonce, tbs) {
    var retVal;
    var signature = "Not Present";
    var errorMessage = isVerified();
    if (errorMessage == "") { // Means everything is ok.
        var plugin;
        plugin = document.getElementById("signerPlugin");
        plugin.SetParam('Nonce', nonce);
        plugin.SetParam('TextToBeSigned', tbs);
        // Use only in production.
        plugin.SetParam('Policys', 'MS4yLjc1Mi43OC4xLjE7MS4yLjc1Mi43OC4xLjI=');
        retVal = plugin.PerformAction('Sign');
        if (retVal == 0) { // Signing ok.
            signature = plugin.GetParam('Signature');
            var bidSignature = document.getElementById("signature");
            bidSignature.value = signature;
            document.aspnetForm.submit();
        } else {
            retVal = plugin.GetLastError();
            var errMsg = document.getElementById("errorMessage");
            errMsg.innerHTML = "N&aring;gonting blev fel vid signering. Felkod: " + retVal;
        }
     } else { // Plugin is missing or is outdated.
        var errMsg = document.getElementById("errorMessage");
        errMsg.innerHTML = errorMessage;
     }
}
