/*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
keystore.js deals with Keystore Management
*/
var KEYSTORE_UUID;
var PRIVATE_KEY_ALIASE;
var PRIVATE_KEY_PASSWORD;
var PROVIDER;

var ONLY_ONE_ALIAS = false;

function keystoreSetting(thisObj,index){

    if (thisObj && index) {
        renderSelectedMenuItem(thisObj,index);
        gatherHistoryObject(thisObj.id, index);
    }

    var objDiv = document.getElementById("divKeystoreSetting");

    var strHTML =     "<h2>Keystore Management</h2>"+
                      "<fieldset style='border:none;'>" +
                      "<div id='formset'>"+
                      "<form>"+
                      "<fieldset>" +
                      "<legend>Available Keystores</legend>" +
                      "<div id='availableKeyStoreDivId' />"+
                      "</fieldset>"+
                      "</form>"+
                      "</div>"+
                      "<div id='formset'>" +
                      "<form method='post' name='keysotoreupload' action='fileupload/keystore' enctype='multipart/form-data' target='globalIFrame'>" +
                      "<fieldset>" +
                      "<legend>Add Keystore - Step 1: Upload Keystore file</legend>" +
                      "<div><label>Keystore File<font color='red'>*</font>"+
                      "</label><input type='file' name='keystoreFile' id='keystoreFile' size='50'/></div>" +
                      "<br/>"+
                      "<div><label>Keystore Password<font color='red'>*</font>" +
                      "</label><input type='password' id='ksPassword'/></div>" +
                      "<br/>"+
                      "<div><label>Provider" +
                      "</label><input type='text' id='provider'/></div>" +
                      "<br/>"+
                      "<div><label>Keystore Type</label>"+
                      "<select id='keystoreType'>"+
                      "<option value='jks'>JKS</option>"+
                      "<option value='pkcs12'>PKCS12</option>"+
                      "</select>"+
                      "</div>"+
                      "<br/>"+
                      "<div class='buttonrow'>" +
                      "<input type=\"submit\" onclick=\"return validateKeyStoreUpload();\" value=\"Next >\"/>" +
                      "</div>" +
                      "</fieldset>" +
                      "</form>" +
                      "</div>" +
                      "</fieldset>";

        objDiv.innerHTML = strHTML;
        wso2.wsf.Util.showOnlyOneMain(objDiv);

        // loading the existing keysotres
        getKeyStores();
}

function validateKeyStoreUpload(){
   if(wso2.wsf.Util.trim(document.keysotoreupload.keystoreFile.value) == ""){
       wso2.wsf.Util.alertWarning("Please select a keystore file.");
       return false;
   }
   var ksPassword = wso2.wsf.Util.trim(document.getElementById("ksPassword").value);
   if(ksPassword==""){
       wso2.wsf.Util.alertWarning("Please enter the Keystore password.");
       return false;
   }
   KEYSTORE_PASSWORD = ksPassword;
   var objComboKeystoreType = document.getElementById("keystoreType");
   var keystoreType = objComboKeystoreType[objComboKeystoreType.selectedIndex].text;
   if (keystoreType == null) {
        keystoreType = objComboKeystoreType[objComboKeystoreType.selectedIndex].value;
   }
   KEYSTORE_TYPE = keystoreType;
   PROVIDER = wso2.wsf.Util.trim(document.getElementById("provider").value);

   //pass the callback to FileExcutor.execute
   FileExcutor.execute = getKeystoreUUID;
   return true;
}

function getKeystoreUUID(uuid){
    KEYSTORE_UUID = uuid;
    getPrivateKeys();
}

function privateKeyPassword(privateKey) {
    var objDiv = document.getElementById("divListPrivetKeyPassword");
        /*"<h4><a href='#' onClick='javascript:showEndpoints(); return false;'>Endpoint Management</a>"+
                      "</a>&nbsp;&gt;&nbsp;Add Endpoint</h4>" +*/
        var strHTML = "<h2>Add Keystore Wizard</h2>"+
                      "<fieldset style='border:none;'>" +
                      "<div id='formset'>" +
                      "<form>" +
                      "<fieldset>" +
                      "<legend>Add Keystore - Step 2: Enter Password for Private Key <font color='blue'>'"+ privateKey+ "'</font></legend>" +
                      "<div><label>Private Key Password<font color='red'>*</font>" +
                      "</label><input type='password' id='pkPassword'/></div>" +
                      "<br/>"+
                      "<div class='buttonrow'>" +
                      "<input type='button' onclick='javascript:privateKPSBack();return false;' value='< Back'/>" +
                      "<input type='button' onclick='javascript:finishKeystoreSetting(document.getElementById(\"pkPassword\"));return false;' value='Next >'/>" +
                      "</div>" +
                      "</fieldset>" +
                      "</form>" +
                      "</div>" +
                      "</fieldset>";

        objDiv.innerHTML = strHTML;
        wso2.wsf.Util.showOnlyOneMain(objDiv);
}

function privateKPSBack() {
    if (ONLY_ONE_ALIAS) {
        ONLY_ONE_ALIAS = false;
       keystoreSetting();
    } else {
       getPrivateKeys();
    }
}

function selectedSpecificPrivatekey(objRadio) {
    var checkedRadioObjValue;
    var checkedRadioObj = false;
    for (var i = 0; objRadio.length; i++) {
        if (objRadio[i].checked) {
            checkedRadioObjValue = objRadio[i].value;
            PRIVATE_KEY_ALIASE = checkedRadioObjValue;
            checkedRadioObj = true;
            break;
        }

        if (objRadio[i] == (objRadio.length - 1)) {
            wso2.wsf.Util.alertWarning("Please select a private key.");
        }
    }
    if (checkedRadioObj) {
        checkedRadioObj = false;
        privateKeyPassword(checkedRadioObjValue);
    }
}

function finishKeystoreSetting(pass) {
    PRIVATE_KEY_PASSWORD = pass.value;
    addNewKeyStore();
}

function finalizeKeystoreWizard(msg) {
    var objDiv = document.getElementById("divFinishKeystoreSetting");
    /*"<h4><a href='#' onClick='javascript:showEndpoints(); return false;'>Endpoint Management</a>"+
  "</a>&nbsp;&gt;&nbsp;Add Endpoint</h4>" +*/
    var strHTML = "<h2>Add Keystore Wizard</h2>" +
                  "<fieldset style='border:none;'>" +
                  "<div id='formset'>" +
                  "<form>" +
                  "<fieldset>" +
                  "<legend>Add Keystore - Step 3: Keystore upload complete</legend>" +
                  "<div><p>"+msg+"</p></div>" +
                  "<div class='buttonrow'>" +
                  "<input type='button' onclick='javascript:keystoreSetting();return false;' value='Finish'/>" +
                  "</div>" +
                  "</fieldset>" +
                  "</form>" +
                  "</div>" +
                  "</fieldset>";

    objDiv.innerHTML = strHTML;
    wso2.wsf.Util.showOnlyOneMain(objDiv);
}

function deleteKeyStore(keyStoreName) {

    var ans = confirm("Do you really want to delete the Keystore  '" +
                      keyStoreName + "'");

    if (!ans) {
        return false;
    }

    var body_xml = '<ns1:deleteKeyStoreRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '<keyStoreName>' + keyStoreName + '</keyStoreName>' +
                   '</ns1:deleteKeyStoreRequest>';

    var callURL = serverURL + "/" + "CryptoAdmin";
    new wso2.wsf.WSRequest(callURL,"deleteKeyStore",body_xml,deleteKeyStoreCallback);


}

function deleteKeyStoreCallback() {

    wso2.wsf.Util.showResponseMessage(this.req.responseXML);
    //loading the firstpage
    keystoreSetting();
}

function getKeyStores() {
    var body_xml = '<ns1:getKeyStoresRequest xmlns:ns1="http://org.apache.axis2/xsd">' +
                   '</ns1:getKeyStoresRequest>';

    var callURL = serverURL + "/" + "CryptoAdmin";
    new wso2.wsf.WSRequest(callURL,"getKeyStores",body_xml,getKeyStoresCallback);
}

function getKeyStoresCallback() {
    transformationWithoutHistory(this.req.responseXML,"keystores.xsl", document.getElementById("availableKeyStoreDivId"));
}



