if ( typeof browser == 'undefined' )
{
    browser = chrome;
}

if ( typeof extra_css != 'undefined' && extra_css != '' )
{
    jQuery ( 'link[rel=stylesheet]:last' ).after ( '<link rel="stylesheet" href="' + extra_css + '"></link>' );
}
if ( typeof skin_logo != 'undefined' && skin_logo != '' )
{
    jQuery ( 'a#img-logo img' ).attr ( 'src' , skin_logo );
}

var baseUrlPlugin = browser.runtime.getURL ( '/' );

var lang = (navigator.language.substr(0,2) === 'es')? 'es' : 'en';
addI18n(lang);

var wallet = null;
var providers = null;
var provider = null;
var claimIdx = null;
var providerObj = null;
var form = null;
var currentClaim = null;
var claimForDeletion = null;
var permissionForRevocation = null;
var checkResult = null;

function block()
{
    jQuery ( 'div#block' ).append ( '<div class="spinner-border" style="width: 4rem; height: 4rem;" role="status"><span class="sr-only">' + getI18n ( 'popup.initiated.loading' ) + '...</span></div><h2>' + escapeHTML ( getI18n ( 'popup.initiated.processing' ) ) + '</h2><p>' + escapeHTML ( getI18n ( 'popup.initiated.dont_close' ) ) + '</p>' );
    jQuery ( 'div#block' ).addClass('processing');
    jQuery ( 'div#block' ).show();
}

function unblock()
{
    jQuery ( 'div#block' ).hide();
    jQuery ( 'div#block' ).empty();
}

function getClaimValue ( claim , field )
{
    var parts = field.split ( '.' );
    var value = claim.claim.credentialSubject;
    for ( var i = 0 ; i < parts.length ; i++ )
    {
        if ( typeof value[parts[i]] != 'undefined' )
        {
            value = value[parts[i]];
        }
        else
        {
            return value;
        }
    }
    return value;

}

function getClaimDescription ( claim )
{
    if ( typeof claim.description_field != 'undefined' )
    {
        return getClaimValue ( claim , claim.description_field );
    }
    else
    {
        return claim.claim.credentialSubject[Object.keys ( claim.claim.credentialSubject )[Object.keys ( claim.claim.credentialSubject )[0] != 'id' ? 0 : 1 ]]
    }
}

function getClaimType ( claim )
{
    return claim.claim.type[claim.claim.type.length - 1];
}

function showErrorMessage ( message , back , callback )
{
    jQuery ( 'div#alertas section.notification' ).append ( '<h1 class="screen-title notification-title">' + escapeHTML ( message ) + '</h1>' );
    jQuery ( 'div#alertas section.notification' ).append ( '<div class="buttons-wrapper"></div>' );
    jQuery ( 'div#alertas section.notification div.buttons-wrapper' ).append ( '<a href="" class="primary-btn">' + getI18n ( 'popup.initiated.accept' ) + '</a>' );
    jQuery ( 'div#alertas section.notification div.buttons-wrapper a.primary-btn' ).click ( function () {
        jQuery ( 'div#alertas section.notification' ).empty();
        jQuery ( 'div#alertas' ).hide();
        jQuery ( 'div#block' ).hide();
        if ( back )
        {
            loadIndex();
        }
        else if ( typeof callback == 'function' )
        {
            callback();
        }
        return false;
    } );
    jQuery ( 'div#block' ).show();
    jQuery ( 'div#alertas' ).show();
}

function showConfirmMessage ( message , callback , cancel_callback , info_message)
{
    if ( typeof info_message != 'undefined' )
    {
        jQuery ( 'div#alertas section.notification' ).append ( '<p class="screen-title notification-title">' + info_message + '</p>' );
    }
    jQuery ( 'div#alertas section.notification' ).append ( '<h1 class="screen-title notification-title">' + escapeHTML ( message ) + '</h1>' );
    jQuery ( 'div#alertas section.notification' ).append ( '<div class="buttons-wrapper"></div>' );
    jQuery ( 'div#alertas section.notification div.buttons-wrapper' ).append ( '<a href="#" class="primary-btn accept-btn">' + getI18n ( 'popup.initiated.accept' ) + '</a>' );
    jQuery ( 'div#alertas section.notification div.buttons-wrapper a.accept-btn' ).click ( function () {
        jQuery ( 'div#alertas section.notification' ).empty();
        jQuery ( 'div#alertas' ).hide();
        jQuery ( 'div#block' ).hide();
        callback();
        return false;
    } );
    jQuery ( 'div#alertas section.notification div.buttons-wrapper' ).append ( '<a href="#" class="primary-btn cancel-btn">' + getI18n ( 'popup.initiated.cancel' ) + '</a>' );
    jQuery ( 'div#alertas section.notification div.buttons-wrapper a.cancel-btn' ).click ( function () {
        jQuery ( 'div#alertas section.notification' ).empty();
        jQuery ( 'div#alertas' ).hide();
        jQuery ( 'div#block' ).hide();
        if ( typeof cancel_callback == 'function' )
        {
            cancel_callback();
        }
        return false;
    } );
    jQuery ( 'div#block' ).show();
    jQuery ( 'div#alertas' ).show();
}

function showProgress ( progress )
{
    if ( typeof progress == 'undefined' || typeof progress['status'] == 'undefined' )
    {
        progress = { status: 'uploading' , progress: 0 , complete: 100 };
    }
    if ( jQuery ( 'div#alertas section.notification h1' ).length == 0 )
    {
        jQuery ( 'div#alertas section.notification' ).append ( '<h1 class="screen-title notification-title">' + escapeHTML ( getI18n ( 'popup.security.synchronizing' ) ) + '</h1>' );
        jQuery ( 'div#alertas section.notification' ).append ( '<div id="progress-area"></div>' );
        jQuery ( 'div#alertas section.notification div#progress-area' ).append ( '<div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div></div>' );
        jQuery ( 'div#block' ).show();
        jQuery ( 'div#alertas' ).show();
    }
    if ( progress['progress'] == -1 ) // error
    {
        jQuery ( 'div#alertas section.notification div#progress-area' ).html ( escapeHTML ( getI18n ( 'errors.synchronizing_error' ) ) );
        jQuery ( 'div#alertas section.notification' ).append ( '<div class="buttons-wrapper"></div>' );
        jQuery ( 'div#alertas section.notification div.buttons-wrapper' ).append ( '<a href="#" class="primary-btn accept-btn">' + getI18n ( 'popup.initiated.accept' ) + '</a>' );
        jQuery ( 'div#alertas section.notification div.buttons-wrapper a.accept-btn' ).click ( function () {
            saveStatus ( '' );
            jQuery ( 'div#alertas section.notification' ).empty();
            jQuery ( 'div#alertas' ).hide();
            jQuery ( 'div#block' ).hide();
            getStatus();
            return false;
        } );
    }
    else if ( progress['progress'] < progress['complete'] ) // progresando
    {
        jQuery ( 'div#alertas section.notification div#progress-area div.progress div.progress-bar' ).attr ( 'aria-valuenow' , parseInt ( 100 * progress['progress'] / progress['complete'] ) );
        jQuery ( 'div#alertas section.notification div#progress-area div.progress div.progress-bar' ).css ( 'width' , parseInt ( 100 * progress['progress'] / progress['complete'] ) + '%' );
        setTimeout ( getStatus , 1000 );
    }
    else
    {
        jQuery ( 'div#alertas section.notification div#progress-area div.progress div.progress-bar' ).attr ( 'aria-valuenow' , parseInt ( progress['progress'] / progress['complete'] ) );
        jQuery ( 'div#alertas section.notification div#progress-area div.progress div.progress-bar' ).css ( 'width' , '100%' );
        jQuery ( 'div#alertas section.notification div#progress-area div.progress div.progress-bar' )
        jQuery ( 'div#alertas section.notification' ).append ( '<div class="buttons-wrapper"></div>' );
        jQuery ( 'div#alertas section.notification div.buttons-wrapper' ).append ( '<a href="#" class="primary-btn accept-btn">' + getI18n ( 'popup.initiated.accept' ) + '</a>' );
        jQuery ( 'div#alertas section.notification div.buttons-wrapper a.accept-btn' ).click ( function () {
            saveStatus ( '' );
            jQuery ( 'div#alertas section.notification' ).empty();
            jQuery ( 'div#alertas' ).hide();
            jQuery ( 'div#block' ).hide();
            return false;
        } );
    }

}

/**
 *  Background communication
 */

function sendMessage ( message , callback )
{
    browser.runtime.sendMessage ( { data: message } , callback );
}

function sendCommand ( cmd , params , callback )
{
    sendMessage ( { cmd: cmd , params: params } , callback );
}


function receiveWallet ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' )
    {
        return;
    }
    if ( data.errnum === 1 ) // No se ha fijado la contraseña inicial
    {
        jQuery ( 'button#menu-button' ).hide();
        jQuery ( 'div#noninitiated' ).show();
        jQuery ( 'div#askpassword' ).hide();
        jQuery ( 'div#initiated' ).hide();
        jQuery ( 'div#noninitiated form.create-wallet-form input#wallet_name' )[0].focus();
    }
    else if ( data.errnum === 2 ) // No se ha solicitado la contraseña
    {
        jQuery ( 'button#menu-button' ).hide();
        jQuery ( 'div#noninitiated' ).hide();
        jQuery ( 'div#askpassword' ).show();
        jQuery ( 'div#initiated' ).hide();
        jQuery ( 'div#askpassword form.unlock-form input#ask_password' )[0].focus();
    }
    else if ( data.errnum === 3 ) // Contraseña incorrecta
    {
        jQuery ( 'button#menu-button' ).hide();
        jQuery ( 'div#noninitiated' ).hide();
        jQuery ( 'div#askpassword' ).show();
        jQuery ( 'div#initiated' ).hide();
        jQuery ( 'div#askpassword form.unlock-form input#ask_password' )[0].focus();
    }
    else
    {
        jQuery ( 'button#menu-button' ).show();
        wallet = data.data;
        if ( typeof data.selectedAddress != 'undefined' && data.selectedAddress != null )
        {
            _selectedAddress = data.selectedAddress;
        }
        jQuery ( 'div#noninitiated' ).hide();
        jQuery ( 'div#askpassword' ).hide();
        jQuery ( 'div#initiated' ).show();
        jQuery ( 'div#initiated h2' ).html ( wallet.wallet_name );
        if ( typeof data.returnData != 'undefined' && typeof data.returnData.showPermissions != 'undefined' && data.returnData.showPermissions == true )
        {
            showPermissions();
        }
        else
        {
            getStatus();
        }
    }
}

function receiveProvidersForStatus ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum )
    {
        return;
    }
    providers = data.data;
    if ( providerObj != null )
    {
        providers[providerObj.name] = providerObj;
    }
    paintForm ( currentClaim , providers[provider].i18n );
}

function statusReceived ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        console.log ( 'Error');
        return;
    }
    if ( data.data.status == 'showForm' && data.data.provider && data.data.form )
    {
        provider = data.data.provider;
        form = data.data.form;
        currentClaim = data.data.currentClaim;
        providerObj = data.data.providerObj;
        if ( providers == null )
        {
            sendCommand ( 'getProviders' , {} , receiveProvidersForStatus );
        }
        else
        {
            paintForm ( currentClaim , providers[provider].i18n );
        }
    }
    else if ( data.data.status == 'uploading' || data.data.status == 'downloading' )
    {
        showProgress ( data.data );
    }
    else
    {
        if ( Object.keys ( wallet.data.attributes ).length > 0 )
        {
            showWallet();
        }
        else
        {
            showAddClaim ( true );
        }
    }

}

sendCommand ( 'getWallet' , {} , receiveWallet );

function getStatus ( )
{
    sendCommand ( 'getPopupStatus' , {}  , statusReceived );
}

function saveStatus ( status )
{
    sendCommand ( 'savePopupStatus' , { status: status , provider: provider , form: form , currentClaim: currentClaim , providerObj: providerObj } );
}

function walletCreated ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        console.log ( 'Error');
        return;
    }
    sendCommand ( 'getWallet' , {} , receiveWallet );
}

function walletImported ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        if ( data.errnum == 2 )
        {
            showErrorMessage ( getI18n ( 'errors.wrong_password' ) );
        }
        else
        {
            showErrorMessage ( getI18n ( 'errors.error' ) );
        }
        console.log ( data );
        return;
    }
    sendCommand ( 'getWallet' , {} , receiveWallet );
}

function unlocked ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        console.log ( 'Error');
        return;
    }
    sendCommand ( 'getWallet' , {} , receiveWallet );
}

function locked ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        console.log ( 'Error');
        return;
    }
    sendCommand ( 'getWallet' , {} , receiveWallet );
}

function clickProvider ( e )
{
    provider = this.dataset.provider;
    if ( providerObj != null && providerObj['name'] != provider )
    {
        providerObj = null;
    }
    if ( typeof provider == 'undefined' || typeof providers[provider] == 'undefined' )
    {
        return;
    }
    var idx = this.dataset.idx;
    if ( idx == 'check' )
    {
        claimIdx = null;
        if ( typeof providers[provider].check != 'undefined' )
        {
            paintForm ( providers[provider].check , providers[provider].i18n );
        }
    
    }
    else
    {
        idx = parseInt ( idx );
        claimIdx = idx;
        if ( typeof idx != 'undefined' && typeof providers[provider].claims != 'undefined' && typeof providers[provider].claims[idx] != 'undefined' )
        {
            paintForm ( providers[provider].claims[idx] , providers[provider].i18n );
        }
    
    }
}

function paintClaims ( provider )
{
    for ( var i = 0 ; i < providers[provider].claims.length ; i++ )
    {
        jQuery ( 'div#initiated div#content ul#providers_list' ).append ( '<li' + ( providers[provider].claims[i].added === true ? ' class="no-clickable"' : '' ) +'><a id="' + escapeHTML ( provider ) + '_' + i + '" data-provider="' + escapeHTML ( provider ) + '" data-idx="' + i + '"><span class="claim-label">' + escapeHTML ( getI18n ( providers[provider].claims[i].name , providers[provider].i18n ) ) + ( typeof providers[provider].claims[i].description != 'undefined' ? ' ' + escapeHTML ( getI18n ( providers[provider].claims[i].description , providers[provider].i18n ) ) : '' ) + '</span><span class="claim-cert">' + ( typeof providers[provider].logo != 'undefined' && providers[provider].logo != '' ? '<img src="' + providers[provider].logo + '">' : escapeHTML ( getI18n ( providers[provider].name , providers[provider].i18n ) ) ) + '</span></a></li>' );
        if ( providers[provider].claims[i].added !== true )
        {
            jQuery ( 'a#'  + provider + '_' + i ).click ( clickProvider );
        }
    }
}

function receiveProviders ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum )
    {
        return;
    }
    providers = data.data;

    jQuery ( 'div#initiated div#content' ).append ( '<ul class="claims-list" id="providers_list"></ul>' );

    
    for ( var provider in providers )
    {
        if ( typeof providers[provider].claims != 'undefined' && typeof providers[provider].claims.length != 'undefined' )
        {
            paintClaims ( provider );
        }
        if ( typeof providers[provider].check != 'undefined' )
        {
            jQuery ( 'div#initiated div#content ul#providers_list' ).append ( '<li><a id="' + escapeHTML ( provider ) + '_check' + '" data-provider="' + escapeHTML ( provider ) + '" data-idx="check"><span class="claim-label">' + escapeHTML ( getI18n ( providers[provider].check.name , providers[provider].i18n ) ) + '</span><span class="claim-cert">' + ( typeof providers[provider].logo != 'undefined' && providers[provider].logo != '' ? '<img src="' + providers[provider].logo + '">' : escapeHTML ( getI18n ( providers[provider].name , providers[provider].i18n ) ) ) + '</span></a></li>' );
            jQuery ( 'a#'  + provider + '_check' ).click ( clickProvider );
        }
    }
    jQuery ( 'div#initiated div#content ul#providers_list' ).append ( '<li class="li-form"><form class="add-claim-form needs-validation"><div class="form-group form-group-grid" id="div_provider_code"><label class="form-label" for="provider_code">' + escapeHTML ( getI18n ( 'popup.initiated.provider_code' , i18n ) ) + '</label><br /><input type="number" id="provider_code" value=""></div><button class="primary-btn" id="send_get_provider">' + escapeHTML ( getI18n ( 'popup.initiated.send') ) + '</button></form></li>' );
    jQuery ( 'div#initiated div#content ul#providers_list form button#send_get_provider' ).click ( getProvider );

    if ( Object.keys ( wallet.data.attributes ).length > 0 )
    {
        jQuery ( 'div#initiated div#content' ).append ( '<a id="link_back" class="back-link" arial-label="' + escapeHTML ( getI18n ( 'popup.initiated.back_to_list' ) ) + '"><img src="icons/back-icon.png"></a>' );
        jQuery ( 'div#initiated div#content a#link_back' ).click ( function ()
        {
            loadIndex();
            return false;
        } );
    
    }
}

var formError = false;

function deleteClaim ()
{
    sendCommand ( 'deleteClaim' , { wallet_name: wallet['wallet_name'] , type: getClaimType ( claimForDeletion ) , key: claimForDeletion.key } , claimDeleted );
    claimForDeletion = null;
}

function revokePermission ()
{
    sendCommand ( 'revokePermission' , { wallet_name: wallet['wallet_name'] , transaction: permissionForRevocation.verification.transaction } , permissionRevoked );
}

var filesReading = 0;
var downloadingObj;

function clone ( obj )
{
    if ( null == obj || "object" != typeof obj )
        return obj;
    var copy = obj.constructor();
    for ( var attr in obj ) {
        if ( obj.hasOwnProperty ( attr ) )
        {
            copy[attr] = clone(obj[attr]);
        }
    }
    return copy;
}

function exportClaim ( claim )
{
    downloadingObj = clone ( claim.claim );

    if ( typeof downloadingObj.credentialSubject.file_key != 'undefined' && typeof downloadingObj.credentialSubject.name != 'undefined' && typeof downloadingObj.credentialSubject.type != 'undefined' )
    {
        filesReading ++;
        sendCommand ( 'loadFile' , { key: downloadingObj.credentialSubject.file_key , returnData: { field: '' } } , function ( data ) 
        {
            if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum || typeof data.data == 'undefined' || typeof data.returnData == 'undefined' || typeof data.returnData.field == 'undefined' || data.returnData.field != '' )
            {
                return;
            }

            downloadingObj.credentialSubject = data.data;
            filesReading--;
        } );
    }
    else
    {
        for ( var i in downloadingObj.credentialSubject )
        {
            if ( typeof downloadingObj.credentialSubject[i].file_key != 'undefined' && typeof downloadingObj.credentialSubject[i].name != 'undefined' && typeof downloadingObj.credentialSubject[i].type != 'undefined' )
            {
                filesReading ++;
                sendCommand ( 'loadFile' , { key: downloadingObj.credentialSubject[i].file_key , returnData: { field: i } } , function ( data ) 
                {
                    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum || typeof data.data == 'undefined' || typeof data.returnData == 'undefined' || typeof data.returnData.field == 'undefined' || data.returnData.field == '' )
                    {
                        return;
                    }
        
                    downloadingObj.credentialSubject[data.returnData.field] = data.data;
                    filesReading--;
                } );
            }
        }
    }
    download();
}

function download()
{
    if ( filesReading == 0 )
    {
        sendCommand ( 'createPresentation' , { wallet: wallet.wallet_name , claims: [ downloadingObj ] } , function ( data ) 
        {
            if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum || typeof data.data == 'undefined' )
            {
                return;
            }

            var a = document.createElement("a");
            a.href = window.URL.createObjectURL ( b64toBlob ( btoa ( serializeObject ( data.data ) ) , 'application/json' ) );
            a.setAttribute ( "download", getClaimType ( { claim: downloadingObj } ) + '_presentation.agnia' );
            a.click();
        } );
    }
    else
    {
        window.setTimeout ( download , 500 );
    }
}

function viewClaimFile ()
{
    var type = this.dataset['claimType'];
    var claimKey = this.dataset['claim'];
    var idx = typeof this.dataset['field'] != 'undefined' ? this.dataset['field'] : '';
    for ( var i = 0 ; i < wallet.data.attributes[type].length ; i++ )
    {
        if ( wallet.data.attributes[type][i].key == claimKey )
        {
            browser.tabs.create( { url: browser.runtime.getURL ( 'viewFile.html?claimType=' + type + '&claim=' + claimKey + '&field=' + idx  ) } );
            break;
        }
    }
}
function showClaimDetail ( data_type , key , permissionKey )
{
    if ( typeof wallet == 'undefined' || typeof wallet.data == 'undefined' || typeof wallet.data.attributes == 'undefined' || typeof wallet.data.attributes[data_type] == 'undefined' )
    {
        return;
    }
    var claim = null;
    for ( var i = 0 ; i < wallet.data.attributes[data_type].length ; i++ )
    {
        if ( wallet.data.attributes[data_type][i].key == key )
        {
            claim = wallet.data.attributes[data_type][i];
            break;
        }
    }
    if ( claim == null )
    {
        return;
    }
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<section class="claim-info"></section>' );
    jQuery ( 'div#initiated div#content section.claim-info' ).append ( '<h1 class="screen-title claim-title"><span class="claim-title__label">' + escapeHTML ( getI18n ( 'data-types.' + getClaimType ( claim ) , claim.i18n ) ) +  '</span><span class="claim-title__value">' + escapeHTML ( getClaimDescription ( claim ) ) + '</span><span class="claim-title__cert">' + ( typeof claim.issuer_logo != 'undefined' && claim.issuer_logo != '' ? '<img src="' + claim.issuer_logo + '">' : escapeHTML ( getI18n ( claim.issuer , claim.i18n ) )  )+ '</span></h1>' );

    if ( Object.keys ( claim.claim.credentialSubject ).length > 2 || typeof claim.claim.credentialSubject[Object.keys ( claim.claim.credentialSubject )[0]] == 'object' || typeof claim.claim.credentialSubject[Object.keys ( claim.claim.credentialSubject )[1]] == 'object' )
    {
        jQuery ( 'div#initiated div#content section.claim-info' ).append ( '<div class="claim-info-group" id="claim_detail"></div' );
        jQuery ( 'div#initiated div#content section.claim-info div#claim_detail' ).append ( '<h2>' + escapeHTML ( getI18n ( 'popup.initiated.detail' ) ) + '</h2>' );

        if ( typeof claim.fields_order != 'undefined' && typeof claim.fields_order[getClaimType ( claim )] != 'undefined' && typeof claim.fields_order[getClaimType ( claim )].length != 'undefined' )
        {
            for ( var i = 0 ; i < claim.fields_order[getClaimType ( claim )].length ; i++ )
            {
                var value = getClaimValue ( claim , claim.fields_order[getClaimType ( claim )][i] );
                if ( value != 'undefined' && value != '' )
                {
                    jQuery ( 'div#initiated div#content section.claim-info div#claim_detail' ).append ( '<div class="claim-info-pair" id="claim_field_' + escapeHTML ( claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' ) ) + '"><div class="claim-info--label">' + escapeHTML ( getI18n ( claim.fields_order[getClaimType ( claim )][i] , claim.i18n ) ) + '</div><div class="claim-info--value">' + formatValue ( value ) + '</div></div>' );
                    if ( typeof value == 'object' && typeof value['file_key'] != 'undefined' && typeof value['name'] != 'undefined' )
                    {
                        sendCommand ( 'loadFile' , { key: value['file_key'] , returnData: { key: value['file_key'] , field: claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' ) } } , function ( data ) 
                        {
                            if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum || typeof data.data == 'undefined' || typeof data.returnData == 'undefined' || typeof data.returnData.key == 'undefined' || typeof data.returnData.field == 'undefined' )
                            {
                                return;
                            }
                            jQuery ( 'div#initiated div#content section.claim-info div#claim_detail div#claim_field_' + escapeHTML ( data.returnData.field ) + ' img[data-file-key="' + data.returnData.key + '"]' ).prop ( 'src' , 'data:' + data.data.type + ';base64,' + data.data.data );
                        } );
                    }
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' ).addClass ( 'clickable' );
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' )[0].dataset['claimType'] = getClaimType ( claim );
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' )[0].dataset['claim'] = claim.key;
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' )[0].dataset['field'] = claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' );
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[getClaimType ( claim )][i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' ).click ( viewClaimFile );
                }
            }
        }
        else if ( typeof claim.fields_order != 'undefined' && typeof claim.fields_order.length != 'undefined' )
        {
            for ( var i = 0 ; i < claim.fields_order.length ; i++ )
            {
                var value = getClaimValue ( claim , claim.fields_order[getClaimType ( claim )][i] );
                if ( typeof value != 'undefined' && value != '' )
                {
                    jQuery ( 'div#initiated div#content section.claim-info div#claim_detail' ).append ( '<div class="claim-info-pair" id="claim_field_' + escapeHTML ( claim.fields_order[i].replaceAll ( '.' , '_' ) ) + '"><div class="claim-info--label">' + escapeHTML ( getI18n ( claim.fields_order[i] , claim.i18n ) ) + '</div><div class="claim-info--value">' + formatValue ( value ) + '</div></div>' );
                    if ( typeof value == 'object' && typeof value['type'] != 'undefined' && typeof value['file_key'] != 'undefined' && typeof value['name'] != 'undefined' )
                    {
                        sendCommand ( 'loadFile' , { key: value['file_key'] , returnData: { key: value['file_key'] , field: claim.fields_order[i].replaceAll ( '.' , '_' ) } } , function ( data ) 
                        {
                            if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum || typeof data.data == 'undefined' || typeof data.returnData == 'undefined' || typeof data.returnData.key == 'undefined' || typeof data.returnData.field == 'undefined' )
                            {
                                return;
                            }
                            jQuery ( 'div#initiated div#content section.claim-info div#claim_detail div#claim_field_' + escapeHTML ( data.returnData.field ) + ' img[data-file-key="' + data.returnData.key + '"]' ).prop ( 'src' , 'data:' + data.data.type + ';base64,' + data.data.data );
                        } );
                    }
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' ).addClass ( 'clickable' );
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' )[0].dataset['claimType'] = getClaimType ( claim );
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' )[0].dataset['claim'] = claim.key;
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' )[0].dataset['field'] = claim.fields_order[i].replaceAll ( '.' , '_' );
                    jQuery ( 'div#claim_field_' + escapeHTML ( claim.fields_order[i].replaceAll ( '.' , '_' ) ) + ' div.claim-info--value' ).click ( viewClaimFile );
                }
            }
        }
        else
        {
            for ( var data in claim.claim.credentialSubject )
            {
                if ( data != 'id' && typeof claim.claim.credentialSubject[data] != 'undefined' && claim.claim.credentialSubject[data] != '' )
                {
                    jQuery ( 'div#initiated div#content section.claim-info div#claim_detail' ).append ( '<div class="claim-info-pair" id="claim_field_' + escapeHTML ( data ) + '"><div class="claim-info--label">' + escapeHTML ( getI18n ( data , claim.i18n ) ) + '</div><div class="claim-info--value">' + formatValue ( claim.claim.credentialSubject[data] ) + '</div></div>' );
                    if ( typeof claim.claim.credentialSubject[data] == 'object' && typeof claim.claim.credentialSubject[data]['type'] != 'undefined' && typeof claim.claim.credentialSubject[data]['file_key'] != 'undefined' && typeof claim.claim.credentialSubject[data]['name'] != 'undefined' )
                    {
                        sendCommand ( 'loadFile' , { key: claim.claim.credentialSubject[data]['file_key'] , returnData: { key: claim.claim.credentialSubject[data]['file_key'] , field: data } } , function ( data ) 
                        {
                            if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum || typeof data.data == 'undefined' || typeof data.returnData == 'undefined' || typeof data.returnData.key == 'undefined' || typeof data.returnData.field == 'undefined' )
                            {
                                return;
                            }
                            jQuery ( 'div#initiated div#content section.claim-info div#claim_detail div#claim_field_' + escapeHTML ( data.returnData.field ) + ' img[data-file-key="' + data.returnData.key + '"]' ).prop ( 'src' , 'data:' + data.data.type + ';base64,' + data.data.data );
                        } );
                    }
                    jQuery ( 'div#claim_field_' + escapeHTML ( data ) + ' div.claim-info--value' ).addClass ( 'clickable' );
                    jQuery ( 'div#claim_field_' + escapeHTML ( data ) + ' div.claim-info--value' )[0].dataset['claimType'] = getClaimType ( claim );
                    jQuery ( 'div#claim_field_' + escapeHTML ( data ) + ' div.claim-info--value' )[0].dataset['claim'] = claim.key;
                    jQuery ( 'div#claim_field_' + escapeHTML ( data ) + ' div.claim-info--value' )[0].dataset['field'] = data;
                    jQuery ( 'div#claim_field_' + escapeHTML ( data ) + ' div.claim-info--value' ).click ( viewClaimFile );
                }
            }
        }
    }
    else
    {
        jQuery ( 'div#initiated div#content section.claim-info div#claim_detail' ).append ( '<div class="claim-info-pair" id="claim_field_' + escapeHTML ( getClaimType ( claim ) ) + '"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'data-types.' + getClaimType ( claim ) , claim.i18n ) ) + '</div><div class="claim-info--value">' + escapeHTML ( getClaimDescription ( claim ) ) + '</div></div>' );

    }
    jQuery ( 'div#initiated div#content section.claim-info' ).append ( '<div class="claim-info-group" id="claim_signature"></div' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_signature' ).append ( '<h2>' + escapeHTML ( getI18n ( 'popup.initiated.signature' ) ) + '</h2>' );
    var fecha = new Date ( claim.claim.proof.created );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_signature' ).append ( '<div class="claim-info-pair"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.date' ) ) + '</div><div class="claim-info--value">' + escapeHTML ( formatDateTime ( fecha ) ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_signature' ).append ( '<div class="claim-info-pair"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.from' ) ) + '</div><div class="claim-info--value clickable expandable" id="claim_signer"><span>' + escapeHTML ( getI18n ( claim.issuer , claim.i18n ) ) + ' (' + escapeHTML ( claim.claim.issuer.substr ( claim.claim.issuer.length - 5 ) ) + ')' + '</span></div><div class="claim-info--value value-detail" id="claim_signer_full"">' + escapeHTML ( claim.claim.issuer ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_signature div#claim_signer' ).click (
        function()
        {
            jQuery ( 'div#initiated div#content section.claim-info div#claim_signature div#claim_signer_full' ).toggle();
            jQuery ( 'div#initiated div#content section.claim-info div#claim_signature div#claim_signer' ).toggleClass ( 'expanded' );
            return false;
        }
    );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_signature' ).append ( '<div class="claim-info-pair"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.to' ) ) + '</div><div class="claim-info--value clickable expandable" id="claim_address"><span>' + escapeHTML ( wallet.wallet_name ) + ' (' + escapeHTML ( claim.claim.credentialSubject.id.substr ( claim.claim.credentialSubject.id.length - 5 ) ) + ')' + '</span></div><div class="claim-info--value value-detail" id="claim_address_full">' + escapeHTML ( claim.claim.credentialSubject.id ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_signature div#claim_address' ).click (
        function()
        {
            jQuery ( 'div#initiated div#content section.claim-info div#claim_signature div#claim_address_full' ).toggle();
            jQuery ( 'div#initiated div#content section.claim-info div#claim_signature div#claim_address' ).toggleClass ( 'expanded' );
            return false;
        }
    );
    if ( typeof claim.claim.validFrom != 'undefined' )
    {
        fecha = new Date ( claim.claim.validFrom );
        jQuery ( 'div#initiated div#content section.claim-info div#claim_signature' ).append ( '<div class="claim-info-pair"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.valid_from' ) ) + '</div><div class="claim-info--value">' + escapeHTML ( formatDateTime ( fecha ) ) + '</div></div>' );

    }
    if ( typeof claim.claim.validUntil != 'undefined' )
    {
        fecha = new Date ( claim.claim.validUntil );
        jQuery ( 'div#initiated div#content section.claim-info div#claim_signature' ).append ( '<div class="claim-info-pair"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.valid_until' ) ) + '</div><div class="claim-info--value">' + escapeHTML ( formatDateTime ( fecha ) ) + '</div></div>' );

    }
    fecha = new Date ( claim.claim.proof.created );
    jQuery ( 'div#initiated div#content section.claim-info' ).append ( '<div class="claim-info-group" id="claim_blockchain"></div' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_blockchain' ).append ( '<h2>' + escapeHTML ( getI18n ( 'popup.initiated.blockchain_record' ) ) + '</h2>' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_blockchain' ).append ( '<div class="claim-info-pair"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.date' ) ) + '</div><div class="claim-info--value">' + escapeHTML ( formatDateTime ( fecha ) ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_blockchain' ).append ( '<div class="claim-info-pair"><div class="claim-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.transaction' ) ) + '</div><div class="claim-info--value clickable expandable" id="claim_transaction"><span>' + escapeHTML ( claim.claim.proof.domain.substr ( claim.claim.proof.domain.length - 5 ) ) + '</span></div><div class="claim-info--value value-detail" id="claim_transaction_full">' + escapeHTML ( claim.claim.proof.domain ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.claim-info div#claim_blockchain div#claim_transaction' ).click (
        function()
        {
            jQuery ( 'div#initiated div#content section.claim-info div#claim_blockchain div#claim_transaction_full' ).toggle();
            jQuery ( 'div#initiated div#content section.claim-info div#claim_blockchain div#claim_transaction' ).toggleClass( 'expanded' );
            return false;
        }
    );

    
    if ( typeof permissionKey != 'undefined' )
    {
        jQuery ( 'div#initiated div#content section.claim-info' ).append ( '<a id="link_back" class="back-link" arial-label="' + getI18n ( 'popup.initiated.back_to_list' ) + '"><img src="icons/back-icon.png"></a>' );
        jQuery ( 'div#initiated div#content section.claim-info a#link_back' ).click (
            function()
            {
                showPermissionDetail ( permissionKey );
                return false;
            }
        );

    }
    else
    {
        jQuery ( 'div#initiated div#content section.claim-info' ).append ( '<a id="link_back" class="back-link" arial-label="' + getI18n ( 'popup.initiated.back_to_list' ) + '"><img src="icons/back-icon.png"></a>' );
        jQuery ( 'div#initiated div#content section.claim-info a#link_back' ).click (
            function()
            {
                showWallet();
                return false;
            }
        );

        jQuery ( 'div#initiated div#content section.claim-info' ).append ( '<div class="buttons-wrapper"><a id="export_claim" class="primary-btn export-link"><img src="icons/export-icon.png"></a> <a id="delete_claim" class="primary-btn delete-link"><img src="icons/delete-icon.png"></a> <a id="verify_claim" class="primary-btn verify-link"><img src="icons/verify-icon.png"></div>' );
    
        jQuery ( 'div#initiated div#content section.claim-info a#delete_claim' ).click (
            function()
            {
                claimForDeletion = claim;
                showConfirmMessage ( getI18n ( 'popup.initiated.confirm_delete' ) , deleteClaim );
                return false;
            }
        );

        jQuery ( 'div#initiated div#content section.claim-info a#export_claim' ).click (
            function()
            {
                exportClaim ( claim );
                return false;
            }
        );
        jQuery ( 'div#initiated div#content section.claim-info a#verify_claim' ).click (
            function()
            {
                browser.tabs.create( { url: browser.runtime.getURL ( 'verifyClaim.html?type=' + getClaimType ( claim ) + '&claim=' + claim.key  ) } );
                return false;
            }
        );
    }
    jQuery ( 'div.container' ).scrollTop ( 0 );
}

function showClaim ( claim )
{
    var ahora = new Date().toISOString().replace ( 'Z' , '+00:00' );
    jQuery ( 'div#initiated div#content ul#claims_list' ).append ( '<li' + ( ( typeof claim.claim.validFrom != 'undefined' && claim.claim.validFrom > ahora ) || ( typeof claim.claim.validUntil != 'undefined' && claim.claim.validUntil < ahora ) ? ' class="invalid"' : '' ) + '><a data-claim-type="' + escapeHTML ( getClaimType ( claim ) ) + '" data-claim-key="' + escapeHTML ( claim.key ) + '"><span class="claim-label">' + escapeHTML ( getI18n ( 'data-types.' + getClaimType ( claim ) , claim.i18n ) ) + '</span><span class="claim-cert">' + ( typeof claim.issuer_logo != 'undefined' && claim.issuer_logo != '' ? '<img src="' + claim.issuer_logo + '">' : escapeHTML ( getI18n ( claim.issuer , claim.i18n ) ) )+ '</span><span class="claim-value">' + escapeHTML ( getClaimDescription ( claim ) ) + '</span></a></li>' );
    jQuery ( 'div#initiated div#content ul#claims_list li a[data-claim-key=' + claim.key + ']' ).click (
        function()
        {
            showClaimDetail ( this.dataset['claimType'] , this.dataset['claimKey'] );
        }
    )

}

function showWallet ()
{
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<h1 class="screen-title">' + escapeHTML ( getI18n ( 'popup.initiated.your_claims' ) ) + '</h1>' );
    jQuery ( 'div#initiated div#content' ).append ( '<ul id="claims_list" class="claims-list"></ul>' );
    for ( var type in wallet.data.attributes )
    {
        for ( var i = 0 ; i < wallet.data.attributes[type].length ; i++ )
        {
            showClaim ( wallet.data.attributes[type][i] );
        }
    }
    
    jQuery ( 'div#initiated div#content' ).append ( '<a id="button_add" class="float-btn add-claim"><i class="fas fa-plus"></i></a>' );
    jQuery ( 'div#initiated div#content a#button_add' ).click ( function ()
    {
        showAddClaim();
        return false;
    } );
    jQuery ( 'div.container' ).scrollTop ( 0 );

}

function showPermissionDetail ( permissionKey )
{
    if ( typeof wallet == 'undefined' || typeof wallet.data == 'undefined' || typeof wallet.data.permissions == 'undefined' )
    {
        return;
    }
    var permission = null;
    for ( var i = 0 ; i < wallet.data.permissions.length ; i++ )
    {
        if ( wallet.data.permissions[i].key == permissionKey )
        {
            permission = wallet.data.permissions[i];
            break;
        }
    }
    if ( permission == null )
    {
        return;
    }
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<section class="permission-info"></section>' );
    jQuery ( 'div#initiated div#content section.permission-info' ).append ( '<h1 class="screen-title permission-title"><span class="permission-title_organization">' + escapeHTML ( permission.organization.name ) +  '</span><span class="claim-title_permission">' + escapeHTML ( getI18n ( 'permissions.' + permission.permission.permission + '.label' ) ) + '</span></h1>' );

    jQuery ( 'div#initiated div#content section.permission-info' ).append ( '<div class="permission-info-group" id="permission_detail"></div' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_detail' ).append ( '<h2>' + escapeHTML ( getI18n ( 'permissions.' + permission.permission.permission + '.description' ) ) + '</h2>' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_detail' ).append ( '<div>' + escapeHTML ( getI18n ( 'permissions.' + permission.permission.permission + '.details' ) ) + '</div>' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_detail div' ).hide();
    jQuery ( 'div#initiated div#content section.permission-info div#permission_detail h2' ).click ( function()
    {
        jQuery ( 'div#initiated div#content section.permission-info div#permission_detail div' ).toggle(); 
    } );

    jQuery ( 'div#initiated div#content section.permission-info' ).append ( '<div class="permission-info-group" id="permission_signature"></div' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_signature' ).append ( '<div class="permission-info-pair"><div class="permission-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.granted_to' ) ) + '</div><div class="permission-info--value clickable expandable" id="permission_address"><span>' + escapeHTML ( permission.organization.name ) + ' (' + escapeHTML ( permission.organization.address.substr ( permission.organization.address.length - 5 ) ) + ')' + '</span></div><div class="permission-info--value value-detail" id="permission_address_full">' + escapeHTML ( permission.organization.address ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_address' ).click (
        function()
        {
            jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_address_full' ).toggle();
            jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_address' ).toggleClass ( 'expanded' );
            return false;
        }
    );
    var fecha = new Date();
    fecha.setTime ( permission.verification.timestamp * 1000 );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_signature' ).append ( '<div class="permission-info-pair"><div class="permission-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.date' ) ) + '</div><div class="permission-info--value">' + escapeHTML ( formatDateTime ( fecha ) ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_signature' ).append ( '<div class="permission-info-pair"><div class="permission-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.transaction' ) ) + '</div><div class="permission-info--value clickable expandable" id="permission_transaction"><span>' + escapeHTML ( permission.verification.transaction.substr ( permission.verification.transaction.length - 5 ) ) + '</span></div><div class="permission-info--value value-detail" id="permission_transaction_full">' + escapeHTML ( permission.verification.transaction ) + '</div></div>' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_transaction' ).click (
        function()
        {
            jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_transaction_full' ).toggle();
            jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_transaction' ).toggleClass ( 'expanded' );
            return false;
        }
    );

    if ( typeof permission.revocation != 'undefined' )
    {
        jQuery ( 'div#initiated div#content section.permission-info div#permission_signature' ).append ( '<div class="permission-info-pair"><div class="permission-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.revoked_by' ) ) + '</div><div class="permission-info--value clickable expandable" id="permission_revoked_by"><span>' + ( permission.organization.address == permission.revocation.who ? escapeHTML ( permission.organization.name ) + ' (' + escapeHTML ( permission.revocation.who.substr ( permission.revocation.who.length - 5 ) ) + ')' : escapeHTML ( wallet.wallet_name ) + ' (' + escapeHTML ( permission.revocation.who.substr ( permission.revocation.who.length - 5 ) ) + ')' ) + '</span></div><div class="permission-info--value value-detail" id="permission_revoked_by_full">' + escapeHTML ( permission.revocation.who ) + '</div></div>' );
        jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_revoked_by' ).click (
            function()
            {
                jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_revoked_by_full' ).toggle();
                jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_revoked_by' ).toggleClass ( 'expanded' );
                return false;
            }
        );
        fecha.setTime ( permission.revocation.timestamp * 1000 );
        jQuery ( 'div#initiated div#content section.permission-info div#permission_signature' ).append ( '<div class="permission-info-pair"><div class="permission-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.revocation_date' ) ) + '</div><div class="permission-info--value">' + escapeHTML ( formatDateTime ( fecha ) ) + '</div></div>' );

        jQuery ( 'div#initiated div#content section.permission-info div#permission_signature' ).append ( '<div class="permission-info-pair"><div class="permission-info--label">' + escapeHTML ( getI18n ( 'popup.initiated.revocation_transaction' ) ) + '</div><div class="permission-info--value clickable expandable" id="permission_revocation_transaction"><span>' + escapeHTML ( permission.revocation.transaction.substr ( permission.revocation.transaction.length - 5 ) ) + '</span></div><div class="permission-info--value value-detail" id="permission_revocation_transaction_full">' + escapeHTML ( permission.revocation.transaction ) + '</div></div>' );
        jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_revocation_transaction' ).click (
            function()
            {
                jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_revocation_transaction_full' ).toggle();
                jQuery ( 'div#initiated div#content section.permission-info div#permission_signature div#permission_revocation_transaction' ).toggleClass ( 'expanded' );
                return false;
            }
        );
            
    }

    jQuery ( 'div#initiated div#content section.permission-info' ).append ( '<div class="permission-info-group" id="permission_data"></div' );
    jQuery ( 'div#initiated div#content section.permission-info div#permission_data' ).append ( '<h2>' + escapeHTML ( getI18n ( 'popup.initiated.data' ) ) + '</h2>' );

    for ( var i = 0 ; i < permission.permission.fields.length ; i++ )
    {
        var field = permission.permission.fields[i];
        if ( typeof field.agniaKey == 'undefined' )
        {
            jQuery ( 'div#initiated div#content section.permission-info div#permission_data' ).append ( '<div class="permission-info-pair" id="permission_field_' + permission.key + '_' + i + '"><div class="permission-info--label">' + escapeHTML ( field.label ) + '</div><div class="permission-info--value">' + formatValue ( field.value ) + '</div></div>' );
            if ( typeof field.value == 'object' && typeof field.value['type'] != 'undefined' && typeof field.value['file_key'] != 'undefined' && typeof field.value['name'] != 'undefined' )
            {
                sendCommand ( 'loadFile' , { key: field.value['file_key'] , returnData: { key: field.value['file_key'] } } , function ( data ) 
                {
                    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum || typeof data.data == 'undefined' || typeof data.returnData == 'undefined' || typeof data.returnData.key == 'undefined' )
                    {
                        return;
                    }
                    jQuery ( 'div#initiated div#content section.permission-info div#permission_data img[data-file-key="' + data.returnData.key + '"]' ).prop ( 'src' , 'data:' + data.data.type + ';base64,' + data.data.data );
                } );
            }
            if ( typeof field.value == 'object' && typeof field.value['type'] != 'undefined' && ( typeof field.value['data'] != 'undefined' || typeof field.value['file_key'] != 'undefined' ) && typeof field.value['name'] != 'undefined' )
            {
                jQuery ( 'div#permission_field_' + permission.key + '_' + i + ' div.permission-info--value' ).addClass ( 'clickable' );
                jQuery ( 'div#permission_field_' + permission.key + '_' + i + ' div.permission-info--value' )[0].dataset['permission'] = permission.key;
                jQuery ( 'div#permission_field_' + permission.key + '_' + i + ' div.permission-info--value' )[0].dataset['field'] = i;
                jQuery ( 'div#permission_field_' + permission.key + '_' + i + ' div.permission-info--value' ).click ( function()
                {
                    var permissionKey = this.dataset['permission'];
                    var idx = this.dataset['field'];
                    for ( var i = 0 ; i < wallet.data.permissions.length ; i++ )
                    {
                        if ( wallet.data.permissions[i].key == permissionKey )
                        {
                            if ( idx < wallet.data.permissions[i].permission.fields.length && typeof wallet.data.permissions[i].permission.fields[idx].value == 'object' && typeof wallet.data.permissions[i].permission.fields[idx].value['type'] != 'undefined' && ( typeof wallet.data.permissions[i].permission.fields[idx].value.data != 'undefined' || typeof wallet.data.permissions[i].permission.fields[idx].value.file_key != 'undefined' ) && typeof wallet.data.permissions[i].permission.fields[idx].value.name != 'undefined')
                            {
                                browser.tabs.create( { url: browser.runtime.getURL ( 'viewFile.html?permission=' + permissionKey + '&field=' + idx  ) } );
                            }
                            break;
                        }
                    }
                    console.log ( permissionKey + ': ' + idx );
                } );
            }
        }
        else
        {
            var fieldWallet = null;
            for ( var dataType in wallet.data.attributes )
            {
                for ( var j = 0 ; j < wallet.data.attributes[dataType].length ; j++ )
                {
                    if ( wallet.data.attributes[dataType][j].key == field.agniaKey )
                    {
                        fieldWallet = wallet.data.attributes[dataType][j];
                        break;
                    }
                }
                if ( fieldWallet != null )
                {
                    break;
                }
            }
            jQuery ( 'div#initiated div#content section.permission-info div#permission_data' ).append ( '<div class="permission-info-pair"><a data-claim-key="' + fieldWallet.key + '" data-claim-type="' + fieldWallet.data.data_type + '" id="permission-info-pair_' + fieldWallet.key + '"><span class="claim-cert">' + ( escapeHTML ( getI18n ( fieldWallet.issuer , fieldWallet.i18n ) ) ) + '</span><div class="permission-info--label">' + escapeHTML ( field.label ) + '</div><div class="permission-info--value">' + escapeHTML ( field.value ) + '</div></a></div>' );
            jQuery ( 'div#initiated div#content section.permission-info div#permission_data div.permission-info-pair a[data-claim-key=' + fieldWallet.key + ']' ).click (
                function()
                {
                    showClaimDetail ( this.dataset['claimType'] , this.dataset['claimKey'] , permissionKey );
                }
            )
        }
    }

    jQuery ( 'div#initiated div#content section.permission-info' ).append ( '<a id="link_back" class="back-link" arial-label="' + getI18n ( 'popup.initiated.back_to_list' ) + '"><img src="icons/back-icon.png"></a>' );
    jQuery ( 'div#initiated div#content section.permission-info a#link_back' ).click (
        function()
        {
            showPermissions();
            return false;
        }
    );

    jQuery ( 'div#initiated div#content section.permission-info' ).append ( '<div class="buttons-wrapper"><a id="revoke_permission" class="primary-btn delete-link"><img src="icons/delete-icon.png"></a></div>' );
    
    jQuery ( 'div#initiated div#content section.permission-info a#revoke_permission' ).click (
        function()
        {
            permissionForRevocation = permission;
            showConfirmMessage ( getI18n ( 'popup.initiated.confirm_revokePermission' ) , revokePermission );
            return false;
        }
    );

    jQuery ( 'div.container' ).scrollTop ( 0 );
}


function showPermission ( permission )
{
    console.log ( permission );
    jQuery ( 'div#initiated div#content ul#permissions-list' ).append ( '<li><a data-permission-key="' + escapeHTML ( permission.key ) + '"><span class="permission-organization">' + escapeHTML ( permission.organization.name ) + '</span><span class="permission-type">' + escapeHTML ( getI18n ( 'permissions.' + permission.permission.permission + '.label' ) ) + '</span></li>' );
    jQuery ( 'div#initiated div#content ul#permissions-list li a[data-permission-key=' + permission.key + ']' ).click (
        function()
        {
            showPermissionDetail ( this.dataset['permissionKey'] );
        }
    )

}

function showPermissions ()
{
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<h1 class="screen-title">' + escapeHTML ( getI18n ( 'popup.initiated.permissions' ) ) + '</h1>' );
    jQuery ( 'div#initiated div#content' ).append ( '<ul id="permissions-list" class="permissions-list"></ul>' );
    for ( var i = 0 ; i < wallet.data.permissions.length ; i++ )
    {
        showPermission ( wallet.data.permissions[i] );
    }
    
}

function showAddClaim ( empty )
{
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<h1 class="screen-title">' + escapeHTML ( getI18n ( empty ? 'popup.initiated.wallet_empty' : 'popup.initiated.add_claims' ) ) + '</h1>' );
    sendCommand ( 'getProviders' , {} , receiveProviders );
}

function claimDeleted ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        console.log ( 'Error');
        return;
    }
    sendCommand ( 'getWallet' , {} , receiveWallet );
}

function permissionRevoked ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        console.log ( 'Error');
        return;
    }
    console.log ( data );
    permissionForRevocation.revocation = data.data;
    permissionForRevocation = null;
//    sendCommand ( 'getWallet' , {} , receiveWallet );
}

function claimAdded ( data )
{
    if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' || data.errnum !== 0 )
    {
        console.log ( 'Error');
        return;
    }
    if ( checkResult === providers[provider] && typeof providers[provider].claims != 'undefined' )
    {
        jQuery ( 'div#initiated div#content' ).empty();
        jQuery ( 'div#initiated div#content' ).append ( '<h1 class="screen-title">' + escapeHTML ( getI18n ( 'popup.initiated.claims_can_add' ) ) + '</h1>' );
        jQuery ( 'div#initiated div#content' ).append ( '<ul class="claims-list" id="providers_list"></ul>' );
        paintClaims ( provider );
        jQuery ( 'div#initiated div#content' ).append ( '<a id="link_back" class="back-link" arial-label="' + escapeHTML ( getI18n ( 'popup.initiated.back_to_list' ) ) + '"><img src="icons/back-icon.png"></a>' );
        jQuery ( 'div#initiated div#content a#link_back' ).click ( function ()
        {
            loadIndex();
            return false;
        } );
    }
    else
    {
        sendCommand ( 'getWallet' , {} , receiveWallet );
    }
}

function processSavedClaim ( claim )
{
    if ( checkResult === providers[provider] && typeof providers[provider].claims != 'undefined' )
    {
        if ( claimIdx != null )
        {
            providers[provider].claims[claimIdx].added = true;
        }
        else
        {
            for ( var i = 0 ; i < providers[provider].claims.length ; i++ )
            {
                if ( providers[provider].claims[i].claim == claim['type'][claim['type'].length - 1] )
                {
                    providers[provider].claims[i].added = true;
                }
            }
        }
    }
    var meta_claim = { claim: claim };
    meta_claim['issuer'] = providers[provider].name;
    if ( typeof  providers[provider].logo != 'undefined' && providers[provider].logo != '' )
    {
        meta_claim['issuer_logo'] = providers[provider].logo;
    }
    meta_claim['i18n'] = providers[provider].i18n;
    if ( typeof providers[provider].fields_order != 'undefined' )
    {
        meta_claim['fields_order'] = providers[provider].fields_order;
    }
    if ( typeof providers[provider].description_field != 'undefined' && typeof providers[provider].description_field[claim['type'][claim['type'].length - 1]] != 'undefined' )
    {
        meta_claim['description_field'] = providers[provider].description_field[claim['type'][claim['type'].length - 1]];
    }
    sendCommand ( 'addClaim' , { wallet_name: wallet['wallet_name'] , claim: meta_claim } , claimAdded );
}

function processResponse ( data )
{
    if ( data.errnum )
    {
        showErrorMessage ( typeof data.errstr != 'undefined' ? getI18n ( data.errstr , providers[provider].i18n ) : getI18n ( 'errors.error' ) );
        return;
    }
    if ( typeof data.data != 'undefined' )
    {
        if ( typeof data.proof == 'undefined' )
        {
            showErrorMessage ( getI18n ( 'errors.response_signature_mismatch' ) );
            return;
        }
        sendCommand ( 'verifyRequestProof' , { data: data.data , proof: data.proof , did: providers[provider].did } , function ( verification ) 
        {
            if ( verification.errnum || typeof verification.data == 'undefined' || verification.data == false )
            {
                showErrorMessage ( getI18n ( 'errors.response_signature_mismatch' ) );
                return;
            }

            if ( typeof data.data != 'undefined' && typeof data.data.form != 'undefined' )
            {
                paintForm ( data.data , providers[provider].i18n );
            }
            else if ( typeof data.data != 'undefined' && typeof data.data.claims != 'undefined' )
            {
                checkResult = providers[provider];
                providers[provider].claims = data.data.claims;
                jQuery ( 'div#initiated div#content' ).empty();
                jQuery ( 'div#initiated div#content' ).append ( '<h1 class="screen-title">' + escapeHTML ( getI18n ( 'popup.initiated.claims_can_add' ) ) + '</h1>' );
                if ( providers[provider].claims.length > 0 )
                {
                    jQuery ( 'div#initiated div#content' ).append ( '<ul class="claims-list" id="providers_list"></ul>' );
                    paintClaims ( provider );
                }
                else
                {
                    jQuery ( 'div#initiated div#content' ).append ( '<p class="warning"">' + escapeHTML ( getI18n ( 'popup.initiated.no_claims' ) ) + '</p>' );
                }
                jQuery ( 'div#initiated div#content' ).append ( '<a id="link_back" class="back-link" arial-label="' + escapeHTML ( getI18n ( 'popup.initiated.back_to_list' ) ) + '"><img src="icons/back-icon.png"></a>' );
                jQuery ( 'div#initiated div#content a#link_back' ).click ( function ()
                {
                    loadIndex();
                    return false;
                } );
                
            }
            else if ( typeof data.data != 'undefined' && typeof data.data.savedClaims != 'undefined' && typeof data.data.savedClaims.length != 'undefined' )
            {
                for ( var i = 0 ; i < data.data.savedClaims.length ; i++ )
                {
                    processSavedClaim ( data.data.savedClaims[i] );
                }
            }
        
        } );
    }
}

function receiveProvider ( data )
{
    if ( data.errnum )
    {
        showErrorMessage ( typeof data.errstr != 'undefined' ? getI18n ( data.errstr ) : getI18n ( 'errors.error' ) );
        return;
    }
    if ( typeof data.data != 'undefined' )
    {
        if ( typeof data.signature == 'undefined' )
        {
            showErrorMessage ( getI18n ( 'errors.response_signature_mismatch' ) );
            return;
        }
        sendCommand ( 'getSigner' , { data: data.data , signature: data.signature } , function ( signerData ) 
        {
            if ( signerData.errnum || typeof signerData.data == 'undefined' || signerData.data != providerStorageAddress )
            {
                showErrorMessage ( getI18n ( 'errors.response_signature_mismatch' ) );
                return;
            }

            if ( typeof data.data != 'undefined' && typeof data.data.provider != 'undefined' )
            {
                providerObj = data.data.provider;
                providers[providerObj.name] = providerObj;
                provider = providerObj.name;
                if ( typeof providers[provider].check != 'undefined' )
                {
                    paintForm ( providers[provider].check , providers[provider].i18n );
                }
                else if ( typeof providers[provider].claims != 'undefined' && typeof providers[provider].claims.length != 'undefined' )
                {
                    jQuery ( 'div#initiated div#content' ).empty();
                    jQuery ( 'div#initiated div#content' ).append ( '<h1 class="screen-title">' + escapeHTML ( getI18n ( 'popup.initiated.add_claims' ) ) + '</h1>' );
                    jQuery ( 'div#initiated div#content' ).append ( '<ul class="claims-list" id="providers_list"></ul>' );
                    paintClaims ( provider );
                    if ( Object.keys ( wallet.data.attributes ).length > 0 )
                    {
                        jQuery ( 'div#initiated div#content' ).append ( '<a id="link_back" class="back-link" arial-label="' + escapeHTML ( getI18n ( 'popup.initiated.back_to_list' ) ) + '"><img src="icons/back-icon.png"></a>' );
                        jQuery ( 'div#initiated div#content a#link_back' ).click ( function ()
                        {
                            loadIndex();
                            return false;
                        } );
                    
                    }
                    
                }
            }
        
        } );
    }
}

function getProvider ( e )
{
    var params = {};
    var value = jQuery ( 'input#provider_code' ).val();
    clearErrors();

    if ( typeof value == 'undefined' || value == null || value == '' )
    {
        showError ( 'div#initiated div#div_provider_code' , getI18n ( 'errors.field_required' ) );
        return false;
    }
    else if ( !validators['NUMERIC'] ( value ) )
    {
        showError ( 'div#initiated div#div_provider_code' , getI18n ( 'NUMERIC' , validatorsI18N ) );
        return false;
    }
    params['provider_id'] = value;
    var requestData = { params: params , timestamp: ( new Date() ).getTime() / 1000 };
    sendCommand ( 'sign' , { wallet: wallet.wallet_name , data: requestData } , 
    function ( data )
    {
        if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' )
        {
            return;
        }
        if ( data.errnum === 0 && typeof data.data != 'undefined' )
        {
            block();
            jQuery.ajax ( {
                url: getProviderUrl ,
                method: 'POST',
                data: {
                    data: serializeObject ( requestData ),
                    signature: data.data,
                    address: wallet.keys.address
                },
                complete: function ( resp , status )
                {
                    unblock();
                    if ( status == 'success' )
                    {
                        receiveProvider ( resp.responseJSON );
                    }
                    else
                    {
                        showErrorMessage ( getI18n ( 'errors.error' ) );
                    }
                }
            } );
        }
    } );
    return false;
}

function showSelectableClaims ( e )
{
    if ( $(this).hasClass ( 'remove-field' ) ) // eliminamos valor
    {
        var fieldName = this.dataset['fieldname'];
        jQuery ( 'input#field_' + fieldName ).val ( '' );
        jQuery ( '#field_' + fieldName ).removeAttr ( 'data-fieldKey' );
        jQuery ( 'div#div_' + fieldName + ' a.edit-field i.fas' ).attr ( 'title' , escapeHTML ( getI18n ( 'popup.initiated.edit_field' ) ) );
        jQuery ( 'div#div_' + fieldName + ' a.edit-field' ).removeClass ( 'remove-field' );
        jQuery ( 'div#div_' + fieldName + ' a.edit-field i.fas' ).removeClass ( 'fa-minus' );
        jQuery ( 'div#div_' + fieldName + ' a.edit-field i.fas' ).addClass ( 'fa-plus' );
        if ( jQuery ( '#field_' + fieldName ).data ( 'unverified' ) == true )
        {
            jQuery ( '#field_' + fieldName ).removeAttr ( 'readonly' );
        }
    }
    else // mostramos selector
    {
        var fieldName = this.dataset['fieldname' ];
        jQuery ( '#field_' + fieldName )[0].toggleValues();
    }
}

async function sendForm ( e )
{
    if ( typeof form == 'undefined' && form == 'null' )
    {
        return false;
    }
    var params = {};
    clearErrors();
    if ( typeof form.fields != 'undefined' )
    {
        for ( var i = 0 ; i < form.fields.length ; i++ )
        {
            var value = await getFieldValue ( form.fields[i] );
            if ( value !== false )
            {
                params[form.fields[i].name] = value;
                if ( form.fields[i].verified )
                {
                    var fieldKey = getVerifiedField ( form.fields[i] );
                    var keyFound = false;
                    if ( typeof fieldKey != 'undefined' && fieldKey != '' )
                    {
                        for ( var j = 0 ; j < wallet.data.attributes[form.fields[i]['data-type']].length ; j++ )
                        {
                            if ( wallet.data.attributes[form.fields[i]['data-type']][j].key == fieldKey )
                            {
                                params [ form.fields[i].name + '_data' ] = wallet.data.attributes[form.fields[i]['data-type']][j].claim;
                                keyFound = true;
                                break;
                            }
                        }
                    }
                    if ( !keyFound && !form.fields[i].unverified )
                    {
                        showFieldError ( form.fields[i] , getI18n ( 'errors.value_not_in_wallet' ) );
                    }
                }
            }
        }
    }
    if ( formError )
    {
        return false;
    }
    var requestData = { params: params , timestamp: ( new Date() ).getTime() / 1000 };
    sendCommand ( 'createRequestProof' , { wallet: wallet.wallet_name , data: requestData } , 
    function ( data )
    {
        if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' )
        {
            return;
        }
        if ( data.errnum === 0 && typeof data.data != 'undefined' )
        {
            block();
            jQuery.ajax ( {
                url: form.url ,
                method: 'POST',
                data: {
                    data: serializeObject ( requestData ),
                    proof: serializeObject ( data.data ),
                    did: wallet.did.id
                },
                complete: function ( resp , status )
                {
                    unblock();
                    if ( status == 'success' )
                    {
                        saveStatus ( '' );
                        processResponse ( resp.responseJSON );
                    }
                    else
                    {
                        if ( typeof provider != 'undefined' && typeof providers[provider] != 'undefined' && typeof providers[provider].name != 'undefined' && typeof providers[provider].i18n != 'undefined' )
                        {
                            showErrorMessage ( getI18n ( 'errors.error_calling' ) + ' ' + getI18n ( providers[provider].name , providers[provider].i18n ) , typeof form != 'undefined' && typeof form['auto-send'] != 'undefined' && form['auto-send'] );
                        }
                        else
                        {
                            showErrorMessage ( getI18n ( 'errors.error' ) , typeof form != 'undefined' && typeof form['auto-send'] != 'undefined' && form['auto-send'] );
                        }
                    }
                }
            } );
        }
    } );
    return false;
}

function paintForm ( claim , i18n )
{
    if ( typeof claim.form == 'undefined' )
    {
        form = null;
        return;
    }
    currentClaim = claim;
    form = claim.form;
    saveStatus ( 'showForm' );
    jQuery ( 'div#initiated div#content' ).empty();
    if ( form['auto-send'] )
    {
        sendForm();
    }
    else
    {
        jQuery ( 'div#initiated div#content' ).append ( '<section class="new-claim"></section>' );
        jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<h1 class="screen-title claim-title"><span class="label">' + escapeHTML ( getI18n ( 'popup.initiated.request_claim' ) ) + '</span> ' + escapeHTML ( getI18n ( claim.name , i18n ) ) + '</h1>' );
        jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<form class="add-claim-form needs-validation"></form>' );
        if ( form.fields != 'undefined' )
        {
            var canPaint = true;
            for ( var i = 0 ; i < form.fields.length ; i++ )
            {
                if ( form.fields[i].verified && typeof form.fields[i]['data-type'] != 'undefined' && ( typeof wallet.data.attributes[form.fields[i]['data-type']] == 'undefined' || wallet.data.attributes[form.fields[i]['data-type']].length == 0 ) )
                {
                    canPaint = false;
                    break;
                }
            }
            if ( canPaint )
            {
                for ( var i = 0 ; i < form.fields.length ; i++ )
                {
                    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( paintField ( form.fields[i] , i18n ) );
                    activateField ( form.fields[i] , i18n );
                }
            }
            else
            {
                showErrorMessage ( escapeHTML ( getI18n ( 'popup.initiated.noclaimavailable1' ) + getI18n ( 'data-types.' + form.fields[i]['data-type'] ) ) + escapeHTML ( getI18n ( 'popup.initiated.noclaimavailable2' ) ) , true );
            }
        }
        jQuery ( 'div#initiated div#content section.new-claim form' ).append ( '<button class="primary-btn" id="send_' + claim.name + '">' + escapeHTML ( getI18n ( 'popup.initiated.send' ) ) + '</button>' );
        jQuery ( 'div#initiated div#content section.new-claim form button#send_' + claim.name ).click ( function () {
            sendForm ();
            return false;
        } );

        jQuery ( 'div#initiated div#content section.new-claim form' ).append ( '<span>&nbsp;</span><a href="#" class="primary-btn cancel-btn" id="cancel_' + claim.name + '">' + escapeHTML ( getI18n ( 'popup.initiated.cancel' ) ) + '</a>' );
        jQuery ( 'div#initiated div#content section.new-claim form a#cancel_' + claim.name ).click ( function () {
            if ( checkResult === providers[provider]  && typeof providers[provider].claims != 'undefined' )
            {
                jQuery ( 'div#initiated div#content' ).empty();
                jQuery ( 'div#initiated div#content' ).append ( '<h1 class="screen-title">' + escapeHTML ( getI18n ( 'popup.initiated.add_claims' ) ) + '</h1>' );
                jQuery ( 'div#initiated div#content' ).append ( '<ul class="claims-list" id="providers_list"></ul>' );
                paintClaims ( provider );
                if ( Object.keys ( wallet.data.attributes ).length > 0 )
                {
                    jQuery ( 'div#initiated div#content' ).append ( '<a id="link_back" class="back-link" arial-label="' + escapeHTML ( getI18n ( 'popup.initiated.back_to_list' ) ) + '"><img src="icons/back-icon.png"></a>' );
                    jQuery ( 'div#initiated div#content a#link_back' ).click ( function ()
                    {
                        loadIndex();
                        return false;
                    } );
                }
            }
            else
            {
                loadIndex();
            }
            return false;
        } );
        jQuery ( 'div#initiated div#content section.new-claim form' ).on ( 'keyup' , function ( evt )
        {
            if ( evt.keyCode == 27 )
            {
                loadIndex();
                evt.preventDefault();
                return false;
            }
        } );
        jQuery ( 'div#initiated div#content section.new-claim form a.edit-field' ).click ( showSelectableClaims );
        if ( jQuery ( 'div#initiated div#content section.new-claim form input:not([type=hidden])' ).length > 0 )
        {
            window.setTimeout ( function () {
                jQuery ( 'div#initiated div#content section.new-claim form input:not([type=hidden])' )[0].focus();
            } , 100 );
            
        }
    }
}

function resetForm()
{
    form = null;
    currentClaim = null;
    jQuery ( 'div.agnia-selector' ).remove();
    saveStatus ( '' );
}

function hideMenu()
{
    jQuery ( 'button.navbar-toggler i.fas' ).removeClass ( 'fa-times' );
    jQuery ( 'div#navbarSupportedContent' ).removeClass ( 'show' );

}

function loadIndex()
{
    resetForm();
    sendCommand ( 'getWallet' , {} , receiveWallet );
}

// opción de seguridad

function showExportPage()
{
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<section class="new-claim"></section>' );
    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<h1 class="screen-title claim-title"><span class="label">' + escapeHTML ( getI18n ( 'popup.security.export' ) ) + '</span></h1>' );
    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<form class="add-claim-form needs-validation"></form>' );
    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( paintField ( {
        'label': 'popup.askpassword.password',
        'type': 'password',
        'name': 'password',
        'mandatory': true
    } ) );
    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( '<button class="primary-btn" id="send_verify_password">' + escapeHTML ( getI18n ( 'popup.security.export' ) ) + '</button>' );
    jQuery ( 'div#initiated div#content section.new-claim form button#send_verify_password' ).click ( function () {
        clearErrors();
        if ( jQuery ( 'div#initiated input#field_password' ).val() == '' )
        {
            showError ( 'div#initiated div#div_password' , i18n[lang]['errors']['password_required'] );
        }
        else
        {
            sendCommand ( 'exportWallet' , { password: jQuery ( 'div#initiated input#field_password' ).val() , wallet_name: wallet['wallet_name'] } , function ( data )
            {
                if ( typeof data != 'undefined' && typeof data.errnum != 'undefined' && data.errnum === 0 & typeof data.data != 'undefined' && typeof data.data.exported_wallet != 'undefined' )
                {
                    var a = document.createElement("a");
                    a.href = window.URL.createObjectURL ( b64toBlob ( btoa ( data.data.exported_wallet ) , 'application/json' ) );
                    a.setAttribute ( "download", wallet['wallet_name'] + '.wallet' );
                    a.click();
                    showSecurityConfig();
                    return;
                }
                else
                {
                    showErrorMessage ( i18n[lang]['errors']['error'] , false , function() {
                        showSecurityConfig();
                    } );
                    return;
                }
            } );
        }
        return false;
    } );

    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( '<span>&nbsp;</span><a href="#" class="primary-btn cancel-btn" id="cancel_verify_password">' + escapeHTML ( getI18n ( 'popup.initiated.cancel' ) ) + '</a>' );
    jQuery ( 'div#initiated div#content section.new-claim form a#cancel_verify_password' ).click ( function () {
        showSecurityConfig();
        return false;
    } );
    jQuery ( 'div#initiated div#content section.new-claim form' ).on ( 'keyup' , function ( evt )
    {
        if ( evt.keyCode == 27 )
        {
            showSecurityConfig();
            evt.preventDefault();
            return false;
        }
    } );
}

function showSecurityConfig ()
{
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<section class="new-claim"></section>' );
    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<h1 class="screen-title claim-title"><span class="label">' + escapeHTML ( getI18n ( 'popup.security.title' ) ) + '</span></h1>' );
    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<h2><span class="label">' + escapeHTML ( getI18n ( 'popup.security.profile' ) ) + '</h2>' );
    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<form></form>' );
    var remote_storage = typeof wallet.config != 'undefined' && typeof wallet.config.remote_storage != 'undefined' && wallet.config.remote_storage == true ? true : false;
    var attributes = {};
    if ( remote_storage )
    {
        attributes['checked'] = true;
    }
    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( paintField ( {
        'label': 'popup.security.synchronize',
        'type': 'checkbox',
        'name': 'synchronize',
        'attributes': attributes
    } ) );

    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<a id="exportLink"><span class="label">' + escapeHTML ( getI18n ( 'popup.security.export_wallet' ) ) + '</a>' );

    jQuery ( 'div#initiated div#content section.new-claim form input#field_synchronize' ).click ( function()
    {
        var checkbox = this;
        showConfirmMessage ( getI18n ( 'popup.security.confirm_message_' + ( this.checked ? 'remote' : 'local' ) ) ,
        function()
        {
            console.log ( 'acepta: ' + checkbox.checked );
            sendCommand ( 'saveRemoteConfig' , { remote_storage: checkbox.checked } , function ( data )
            {
                console.log ( data );
                showProgress ( );
            } );

        } ,
        function()
        {
            console.log ( 'no acepta: ' + checkbox.checked );
            checkbox.checked = !checkbox.checked;
        } , this.checked ? getI18n ( 'popup.security.explain_message_remote' ) : undefined );

    } );

    jQuery ( 'div#initiated div#content section.new-claim a#exportLink' ).click ( function()
    {
        showExportPage();
        return false;
    } );
    
}

function checkPasswordForm()
{
    jQuery ( 'div#initiated div#content' ).empty();
    jQuery ( 'div#initiated div#content' ).append ( '<section class="new-claim"></section>' );
    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<h1 class="screen-title claim-title"><span class="label">' + escapeHTML ( getI18n ( 'popup.security.check_password' ) ) + '</span></h1>' );
    jQuery ( 'div#initiated div#content section.new-claim' ).append ( '<form class="add-claim-form needs-validation"></form>' );
    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( paintField ( {
        'label': 'popup.askpassword.password',
        'type': 'password',
        'name': 'password',
        'mandatory': true
    } ) );
    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( '<button class="primary-btn" id="send_verify_password">' + escapeHTML ( getI18n ( 'popup.initiated.verify' ) ) + '</button>' );
    jQuery ( 'div#initiated div#content section.new-claim form button#send_verify_password' ).click ( function () {
        clearErrors();
        if ( jQuery ( 'div#initiated input#field_password' ).val() == '' )
        {
            showError ( 'div#initiated div#div_password' , i18n[lang]['errors']['password_required'] );
        }
        else
        {
            sendCommand ( 'checkPassword' , { password: jQuery ( 'div#initiated input#field_password' ).val() } , function ( data )
            {
                if ( typeof data != 'undefined' && typeof data.errnum != 'undefined' && data.errnum === 0 )
                {
                    showSecurityConfig();
                }
                else
                {
                    jQuery ( 'div#initiated input#field_password' ).val ( '' );
                    showErrorMessage ( i18n[lang]['errors']['wrong_password'] , false , function() {
                        jQuery ( 'div#initiated input#field_password' ).focus();
                    } );
                    return;
                }
            } );
        }
        return false;
    } );

    jQuery ( 'div#initiated div#content section.new-claim form' ).append ( '<span>&nbsp;</span><a href="#" class="primary-btn cancel-btn" id="cancel_verify_password">' + escapeHTML ( getI18n ( 'popup.initiated.cancel' ) ) + '</a>' );
    jQuery ( 'div#initiated div#content section.new-claim form a#cancel_verify_password' ).click ( function () {
        loadIndex();
        return false;
    } );
    jQuery ( 'div#initiated div#content section.new-claim form' ).on ( 'keyup' , function ( evt )
    {
        if ( evt.keyCode == 27 )
        {
            loadIndex();
            evt.preventDefault();
            return false;
        }
    } );
}

// \opción de seguridad

jQuery ( 'nav.navbar-dark a#img-logo' ).click ( function ()
{
    loadIndex();
    return false;
} );
jQuery ( 'div#noninitiated p#linkLoad' ).click ( function ()
    {
        jQuery ( 'div#noninitiated div.import_wallet' ).toggle();
    }
);

async function readNoninitiatedForm ()
{
    clearErrors();
    if ( jQuery ( 'div#noninitiated input#wallet_name' ).val() == '' )
    {
        showError ( 'div#noninitiated div#div_wallet_name' , i18n[lang]['errors']['wallet_name_required'] );
    }
    if ( jQuery ( 'div#noninitiated input#init_password' ).val() == '' )
    {
        showError ( 'div#noninitiated div#div_init_password' , i18n[lang]['errors']['password_required'] );
    }
    else if ( jQuery ( 'div#noninitiated input#init_password2' ).val() == '' )
    {
        showError ( 'div#noninitiated div#div_init_password2' , i18n[lang]['errors']['password2_required'] );
    }
    else if ( jQuery ( 'div#noninitiated input#init_password' ).val() != jQuery ( 'div#noninitiated input#init_password2' ).val() )
    {
        showError ( 'div#noninitiated div#div_init_password2' , i18n[lang]['errors']['password_password2_mismatch'] );
    }
    if ( jQuery ( 'div#noninitiated input#init_import_file' ).val() != '' )
    {
        if ( jQuery ( 'div#noninitiated input#file_password' ).val() == '' )
        {
            showError ( 'div#noninitiated div#div_file_password' , i18n[lang]['errors']['password_required'] );
        }
    }
    if ( !formError )
    {
        if ( jQuery ( 'div#noninitiated input#init_import_file' ).val() == '' )
        {
            sendCommand ( 'createWallet' , { wallet_name: jQuery ( 'div#noninitiated input#wallet_name' ).val() , password: jQuery ( 'div#noninitiated input#init_password' ).val() } , walletCreated );
        }
        else
        {
            var input = jQuery ( 'div#noninitiated input#init_import_file' )[0];
            if ( input.files.length == 0 )
            {
                sendCommand ( 'createWallet' , { wallet_name: jQuery ( 'div#noninitiated input#wallet_name' ).val() , password: jQuery ( 'div#noninitiated input#init_password' ).val() } , walletCreated );
            }
            else
            {
                var imported_wallet = await blobToData ( input.files[0] );
                imported_wallet = b64DecodeUnicode ( imported_wallet.substring ( imported_wallet.indexOf ( ',' ) + 1 ) );
                sendCommand ( 'importWallet' , { wallet_name: jQuery ( 'div#noninitiated input#wallet_name' ).val() , password: jQuery ( 'div#noninitiated input#init_password' ).val() , imported_wallet: imported_wallet , file_password: jQuery ( 'div#noninitiated input#file_password' ).val() } , walletImported );
            }
        }
    }
    return false;
}

jQuery ( 'div#noninitiated button#setInitPassword' ).click ( function()
    {
        readNoninitiatedForm ();
        return false;
    }
);

jQuery ( 'div#askpassword button#unlock' ).click ( function ()
    {
        clearErrors();
        if ( jQuery ( 'div#askpassword input#ask_password' ).val() == '' )
        {
            showError ( 'div#askpassword div#div_ask_password' , i18n[lang]['errors']['password_required'] );
        }
        if ( !formError )
        {
            sendCommand ( 'unlock' , { password: jQuery ( 'div#askpassword input#ask_password' ).val()} , unlocked );
            jQuery ( 'div#askpassword input#ask_password' ).val ( '' );
        }
        return false;
    }
);

jQuery ( 'div#initiated button#addAddress' ).click ( function ()
    {
        sendCommand ( 'createAddress' , {} , addressCreated );
        return false;
    }
);

jQuery ( 'div#initiated button#manageData' ).click ( function ()
{
    if ( _selectedAddress != null )
    {
        sendMessage ( { cmd: 'open' , params: { url: 'agnia-wallet.html?address=' + encodeURIComponent ( _selectedAddress ) } } );
        return false;
    }
} );

jQuery ( 'button#menu-button' ).click ( function ()
{
    jQuery ( 'div.agnia-selector' ).remove();
    jQuery ( 'button.navbar-toggler i.fas' ).toggleClass ( 'fa-times' );
} );

jQuery ( 'div#navbarSupportedContent a#menu_claims' ).click ( function ()
{
    loadIndex();
    hideMenu();
} );

jQuery ( 'div#navbarSupportedContent a#menu_permissions' ).click ( function ()
{
    resetForm();
    sendCommand ( 'getWallet' , { returnData: { showPermissions: true } } , receiveWallet );
    hideMenu();
} );

jQuery ( 'div#navbarSupportedContent a#menu_security' ).click ( function ()
{
    resetForm();
    hideMenu();
    checkPasswordForm();
} );

jQuery ( 'div#navbarSupportedContent a#menu_logout' ).click ( function ()
{
    resetForm();
    sendCommand ( 'lock' , {} , locked );
    hideMenu();
} );
