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

var disableAutocomplete = navigator.userAgent.indexOf ( 'Chrome' ) != -1 ? 'chrome-off' : 'off';
var baseUrlPlugin = browser.runtime.getURL ( '/' );

var processing = false;
var sendingForm = null;

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

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

function fileReceived ( data )
{
    if ( data.errnum == 0 )
    {
        var jQueryElement = jQuery ( 'input[data-agnia-key=' + data.returnData.elementKey + ']' );
        if ( jQueryElement.length != 1 )
        {
            return;
        }
        var element = jQueryElement[0];
        var value = element.agniaValue;
        var ficheros = element.agniaFiles;
        if ( data.returnData.fichero.path == '' )
        {
            value.data[data.returnData.fichero.type] = data.data;
        }
        else
        {
            value.data[data.returnData.fichero.type][data.returnData.fichero.path] = data.data;
        }
        if ( ficheros.length == 0 )
        {
            console.log ( 'Fijamos el valor' );
            jQuery ( 'input#_agnia_data_' + element.dataset.agniaKey ).val ( serializeObject ( value.data ) );
            delete element.agniaValue;
            delete element.agniaFiles;
        }
        else
        {
            element.agniaValue = value;
            var fichero = ficheros.shift();
            element.agniaFiles = ficheros;
            sendCommand ( 'loadFile' , { key: fichero.key , returnData: { fichero: fichero , elementKey: element.dataset.agniaKey } } , fileReceived );
        }
    }
}

function setValue ( element , value )
{
    element.value = typeof value.data.description != 'undefined' ? value.data.description : value.data.value;
    element.dataset.agniaValueKey = value.key;
    element.dataset.agniaValueProvider = getI18n ( value.issuer , value.i18n );
    if ( jQuery ( 'input#_agnia_data_' + element.dataset.agniaKey ).length == 0 )
    {
        jQuery ( element ).after ( '<input type="hidden" name="' + element.name + '_agnia_data" id ="_agnia_data_' + element.dataset.agniaKey + '" value="" />')
    }
    
    var ficheros = [];
    if ( typeof value.data.value == 'object' )
    {
        if ( typeof value.data.value.name != 'undefined' && typeof value.data.value.type != 'undefined' && typeof value.data.value.file_key != 'undefined' )
        {
            ficheros.push ( { key: value.data.value.file_key , type: 'value' , 'path': '' } );
        }
        else
        {
            for  ( key in value.data.value )
            {
                if ( typeof value.data.value[key] == 'object' && typeof value.data.value[key].name != 'undefined' && typeof value.data.value[key].type != 'undefined' && typeof value.data.value[key].file_key != 'undefined' )
                {
                    ficheros.push ( { key: value.data.value[key].file_key , type: 'value' , 'path': key } );
                }
            }
        }
    }
    if ( typeof value.data.extra_data == 'object' )
    {
        if ( typeof value.data.extra_data.name != 'undefined' && typeof value.data.extra_data.type != 'undefined' && typeof value.data.extra_data.file_key != 'undefined' )
        {
            ficheros.push ( { key: value.data.extra_data.file_key , type: 'extra_data' , 'path': '' } );
        }
        else
        {
            for  ( key in value.data.extra_data )
            {
                if ( typeof value.data.extra_data[key] == 'object' && typeof value.data.extra_data[key].name != 'undefined' && typeof value.data.extra_data[key].type != 'undefined' && typeof value.data.extra_data[key].file_key != 'undefined' )
                {
                    ficheros.push ( { key: value.data.value[key].file_key , type: 'extra_data' , 'path': key } );
                }
            }
        }
    }

    if ( ficheros.length == 0 )
    {
        jQuery ( 'input#_agnia_data_' + element.dataset.agniaKey ).val ( serializeObject ( value.data ) );
    }
    else
    {
        element.agniaValue = value;
        var fichero = ficheros.shift();
        element.agniaFiles = ficheros;
        sendCommand ( 'loadFile' , { key: fichero.key , returnData: { fichero: fichero , elementKey: element.dataset.agniaKey } } , fileReceived );
        
    }

    if ( jQuery ( 'input#_agnia_verification_' + element.dataset.agniaKey ).length == 0 )
    {
        jQuery ( element ).after ( '<input type="hidden" name="' + element.name + '_agnia_verification" id ="_agnia_verification_' + element.dataset.agniaKey + '" value="" />')
    }
    jQuery ( 'input#_agnia_verification_' + element.dataset.agniaKey ).val ( serializeObject ( value.verification ) );
}

function selectVal ( event )
{
    console.log ( event.target.dataset );
    console.log ( popup.agniaData );
    for ( var i = 0 ; i < popup.agniaData.length ; i++ )
    {
        if ( popup.agniaData[i].key == event.target.dataset._agniaFieldKey )
        {
            setValue ( popup.agniaFieldElement , popup.agniaData[i] );
            document.body.removeChild ( popup );
            popup = null;
            break;
        }
    }
}

function receiveData ( data )
{
    console.log ( data );
    if ( popup != null )
    {
        document.body.removeChild ( popup );
        popup = null;
    }
    if ( typeof data != 'object' || data.errnum != 0 || typeof data.data != 'object' || typeof data.data.length == 'undefined' || data.data.length == 0 )
    {
        return;
    }
    var jQueryElement = jQuery ( formElements[data.returnData.elementKey] );
    var pos = jQueryElement.position();
    var element = document.createElement ( 'div' );
    element.classList.add("agnia-selector");
    element.style = 'position: absolute !important; z-index: 2147483647 !important; display: block !important; opacity: 1 !important; visibility: visible !important; transform: none !important; clip: auto !important; clip-path: none !important; filter: none !important; mask: none !important; top: ' + ( pos.top + jQueryElement.height() + 10 ) + 'px !important; left: ' + pos.left + 'px !important; box-shadow: 0 2px 6px #3C4A54 !important;';

    var dl = document.createElement ( 'dl' );
    for ( var i = 0 ; i < data.data.length ; i++ )
    {
        var dd = document.createElement (  'dd' );
        dd.dataset._agniaFieldKey = data.data[i].key;
        dd.onclick = selectVal;
        dd.innerText = typeof data.data[i].data.description != 'undefined' ? data.data[i].data.description : data.data[i].data.value;
        dl.appendChild ( dd );
    }
    element.appendChild ( dl );
    element.onclick = function ( event )
    {
        event.stopPropagation();
    }
    element.agniaData = data.data;
    element.agniaFieldElement = formElements[data.returnData.elementKey];
    document.body.appendChild ( element );
    popup = element;
    console.log ( pos );
}

function closeAgniaWindow()
{
    jQuery ( 'div#agnia_screen_block' ).remove();
    jQuery ( 'div#agnia_screen_parent' ).remove();
}

function loginSignatureReceived ( data )
{
    console.log ( data );
    if ( data.errnum == 0 )
    {
        jQuery ( 'form#' + data.returnData.formKey + ' input[name=agnia_signature]' ).val ( data.data );
        jQuery ( 'form#' + data.returnData.formKey  )[0].submit();
    }
}

function doLogin ( key , data )
{
    var element = jQuery ( '[data-agnia-login="true"][data-agnia-element-key="' + key + '"]' )[0];
    var url = element.dataset['agniaLoginUrl'];
    var dataName = data.data.data_type;
    var formKey = getKey();
    jQuery ( document.body ).append ( '<form id="' +  formKey + '" method="POST"></form>' );
    jQuery ( 'form#' + formKey ).attr( 'action' , url )
    jQuery ( 'form#' + formKey ).append ( '<input type="hidden" name="' + dataName + '">' );
    jQuery ( 'form#' + formKey ).append ( '<input type="hidden" name="' + dataName + '_agnia_data">' );
    jQuery ( 'form#' + formKey ).append ( '<input type="hidden" name="' + dataName + '_agnia_verification">' );
    jQuery ( 'form#' + formKey ).append ( '<input type="hidden" name="timestamp">' );
    jQuery ( 'form#' + formKey ).append ( '<input type="hidden" name="agnia_signature">' );
    jQuery ( 'form#' + formKey + ' input[name=' + dataName + ']') .val ( typeof data.data.description != 'undefined' ? data.data.description : data.data.value );
    jQuery ( 'form#' + formKey + ' input[name=' + dataName + '_agnia_data]' ).val ( serializeObject ( data.data ) );
    jQuery ( 'form#' + formKey + ' input[name=' + dataName + '_agnia_verification]' ).val ( serializeObject ( data.verification ) );
    jQuery ( 'form#' + formKey + ' input[name=timestamp]' ).val ( parseInt ( new Date().getTime() / 1000 ) );
    var formData = {};
    formData[dataName] = jQuery ( 'form#' + formKey + ' input[name=' + dataName + ']' ).val();
    formData[dataName + '_agnia_data'] = jQuery ( 'form#' + formKey + ' input[name=' + dataName + '_agnia_data]' ).val();
    formData[dataName + '_agnia_signature'] = jQuery ( 'form#' + formKey + ' input[name=' + dataName + '_agnia_signature]' ).val();
    formData['timestamp'] = jQuery ( 'form#' + formKey + ' input[name=timestamp]' ).val();
    sendCommand ( 'sign' , {  data:  formData , returnData: { formKey: formKey } } , loginSignatureReceived );
}

function receiveLoginData ( data )
{
    jQuery ( document.body ).append ( '<div id="agnia_screen_block"></div>' );
    jQuery ( document.body ).append ( '<div id="agnia_screen_parent"></div>' );
    jQuery ( 'div#agnia_screen_parent' ).append ( '<div id="agnia_screen"></div>' );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen' ).append ( '<div id="agnia_screen_close">X</div>' );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_close' ).click ( closeAgniaWindow );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen' ).append ( '<div id="agnia_screen_content"></div>' );
    if ( data.errnum != 0 )
    {
        var errstr;
        if ( typeof data.errstr != 'undefined' )
        {
            errstr = data.errstr;
        }
        else
        {
            errstr = 'Error';
        }
        jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<p class="agnia_error">' + escapeHTML ( errstr ) + '</p>' );
    }
    else
    {
        jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<h1>' + escapeHTML ( getI18n ( 'content.select_data' ) ) + '</h1>' );
        jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<ul id="data_selector"></ul>' );
        window._agnia.data = data.data;
        for ( var i = 0 ; i < data.data.length ; i++ )
        {
            jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#data_selector' ).append ( '<li data-agnia-login-data-idx="' + i + '" data-agnia-login-element="' + data.returnData.elementKey + '">' + escapeHTML ( typeof data.data[i].data.description != 'undefined' ? data.data[i].data.description : data.data[i].data.value ) + '</li>' );
        }
        jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#data_selector li' ).click ( function() {
            var key = this.dataset['agniaLoginElement'];
            var idx = this.dataset['agniaLoginDataIdx'];
            closeAgniaWindow();
            doLogin ( key , window._agnia.data[idx] );
            delete ( window._agnia.data )
        } );
    }
}

function sendForm ()
{
    if ( sendingForm == null )
    {
        return;
    }
    if ( processing )
    {
        window.setTimeout ( sendForm , 500 );
    }
    else
    {
        sendingForm.submit();
    }
}

async function storedPermissions ( data )
{
    console.log ( data );
    if ( typeof data != 'object' || data.errnum != 0 || typeof data.data != 'object' )
    {
        console.log ( getI18n ( 'errors.error' ) );
        closeAgniaWindow();
        return;
    }
    var form = forms[data.returnData.formKey];
    if ( jQuery ( 'input#_agnia_granted_permission_' + form.dataset.agniaKey ).length == 0 )
    {
        jQuery ( form ).append ( '<input type="hidden" name="_agnia_granted_permission" id ="_agnia_granted_permission_' + form.dataset.agniaKey + '" value="" />');
    }
    jQuery ( 'input#_agnia_granted_permission_' + form.dataset.agniaKey ).val ( serializeObject ( data.data ) );

    if ( jQuery ( 'input#_agnia_timestamp_' + form.dataset.agniaKey ).length == 0 )
    {
        jQuery ( form ).append ( '<input type="hidden" name="_agnia_timestamp" id ="_agnia_timestamp_' + form.dataset.agniaKey + '" value="" />');
    }
    jQuery ( 'input#_agnia_timestamp_' + form.dataset.agniaKey ).val ( parseInt ( new Date ().getTime() / 1000 ) );

    var formData = {};
    for ( var i = 0 ; i < form.elements.length ; i++ )
    {
        if ( form.elements[i].name != '' )
        {
            if ( form.elements[i].type == 'file' && form.elements[i].value != '' )
            {
                if ( form.elements[i].multiple )
                {
                    formData[form.elements[i].name] = [];
                    for ( var j = 0 ; j < form.elements[i].files.length ; j++ )
                    {
                        var file = await readFile ( form.elements[i].files[j] );
                        formData[form.elements[i].name].push ( file.replace ( /^data:[a-z0-9]+\/[a-z0-9\.\-]+;base64,/ , '' ) );
                    }
                }
                else if ( form.elements[i].files.length > 0 )
                {
                    var file = await readFile ( form.elements[i].files[0] );
                    formData[form.elements[i].name] = file.replace ( /^data:[a-z0-9]+\/[a-z0-9\.\-]+;base64,/ , '' );
                }
                else
                {
                    formData[form.elements[i].name] = "";
                }
            }
            else
            {
                formData[form.elements[i].name] = form.elements[i].value;
            }
        }
    }

    sendCommand ( 'sign' , { data: formData } , 
    function ( data )
    {
        if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' )
        {
            return;
        }
        if ( data.errnum === 0 && typeof data.data != 'undefined' )
        {
            if ( jQuery ( 'input#_agnia_signature_' + form.dataset.agniaKey ).length == 0 )
            {
                jQuery ( form ).append ( '<input type="hidden" name="_agnia_signature" id ="_agnia_signature_' + form.dataset.agniaKey + '" value="" />')
            }
            jQuery ( 'input#_agnia_signature_' + form.dataset.agniaKey ).val ( data.data );
            if ( jQuery ( 'input#_agnia_address_' + form.dataset.agniaKey ).length == 0 )
            {
                jQuery ( form ).append ( '<input type="hidden" name="_agnia_address" id ="_agnia_address_' + form.dataset.agniaKey + '" value="" />')
            }
            jQuery ( 'input#_agnia_address_' + form.dataset.agniaKey ).val ( data.address );
            sendingForm = form;
            sendForm();
        }
    } );

    //jQuery ( form ).append ( '<input type="hidden" name="_agnia_permissions_granted" value="' + grantedPermissions.join ( '|' ) + '">');
}

async function getPermissionFields ( permission , form , noFiles )
{
    var fields = [];
    for ( var i = 0 ; i < permission.fields.length ; i++ )
    {
        if ( typeof form[permission.fields[i]] != 'undefined' )
        {
            if ( typeof form[permission.fields[i]].length == 'undefined' )
            {
                var field;
                field = { 'name': permission.fields[i] , 'label': ( typeof form[permission.fields[i]].id != 'undefined' && form[permission.fields[i]].id != null && form[permission.fields[i]].id != '' ? jQuery ( form ).find ( 'label[for=' + form[permission.fields[i]].id + '' ).html() : permission.fields[i] ) };
                if ( form[permission.fields[i]].type == 'file' && field.value != '' )
                {
                    if ( form[permission.fields[i]].multiple )
                    {
                        var names = [];
                        field.value = [];
                        for ( var j = 0 ; j < form[permission.fields[i]].files.length ; j++ )
                        {
                            if ( typeof noFiles == 'undefined' || !noFiles )
                            {
                                var file = await readFile ( form[permission.fields[i]].files[j] );
                                var parts = file.match ( /^data:([a-z0-9]+\/[a-z0-9\.\-]+);base64,(.+)$/ );
                                field.value.push ( { name: form[permission.fields[i]].files[j].name , type: parts[1] , data: parts[2] } );
                            }
                            names.push ( form[permission.fields[i]].files[j].name );
                        }
                        field.displayValue = names.join ( ', ' );
                    }
                    else if ( form[permission.fields[i]].files.length > 0 )
                    {
                        if ( typeof noFiles == 'undefined' || !noFiles )
                        {
                            var file = await readFile ( form[permission.fields[i]].files[0] );
                            var parts = file.match ( /^data:([a-z0-9]+\/[a-z0-9\.\-]+);base64,(.+)$/ );
                            field.value = { name: form[permission.fields[i]].files[0].name , type: parts[1] , data: parts[2] };
                        }
                        field.displayValue = form[permission.fields[i]].files[0].name;
                    }
                    else
                    {
                        field.value = "";
                        field.displayValue = "";
                    }
                }
                else
                {
                    field.value = form[permission.fields[i]].value;
                }
                if ( typeof form[permission.fields[i]].dataset.agniaValueKey != 'undefined' )
                {
                    field.agniaKey = form[permission.fields[i]].dataset.agniaValueKey;
                }
                if ( typeof form[permission.fields[i]].dataset.agniaValueProvider != 'undefined' )
                {
                    field.agniaProvider = form[permission.fields[i]].dataset.agniaValueProvider;
                }
                if ( form[permission.fields[i]].type == 'date' && field.value != '' )
                {
                    field.displayValue = new Date ( field.value ).toLocaleDateString ( undefined , { year: "numeric", month: "2-digit", day: "2-digit" } );
                }
                fields.push ( field );
            }
        }
    }
    return fields;
}

function sleep ( ms )
{
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function showTimer ()
{
    jQuery ( 'div#agnia_screen_parent' ).append ( '<div id="timer-block"></div><div id="timer"><div id="timer-content"><div class="logo-wrapper"><img src="'+baseUrlPlugin+'assets/img/agnia-logo.png" alt="Agnia logo" width="80"></div></div></div>' );
    jQuery ( 'div#agnia_screen_parent div#timer div#timer-content' ).append('<div class="timer-content-inner"></div>');
    jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner' ).append('<div class="loader"></div>');
    
    // Firmando permisos
    jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner' ).append ('<p class="signing_permission">' + escapeHTML ( getI18n ( 'content.signing_permission' ) ) + '</p>' );
    for ( var i = 0 ; i < 4 ; i++ )
    {
        await sleep ( 500 );
        jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner .signing_permission' ).append ( ' .' );
    }

    jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner .signing_permission' ).remove();

    // Registrando permisos
    jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner' ).append ( '<p class="registering_permission">' + escapeHTML ( getI18n ( 'content.registering_permission' ) ) + '</p>');
    for ( var i = 0 ; i < 4 ; i++ )
    {
        await sleep ( 500 );
        jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner .registering_permission' ).append ( ' .' );
    }

    jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner .registering_permission' ).remove();
    
    // Enviando datos
    jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner' ).append ( '<p class="sending_data">' + escapeHTML ( getI18n ( 'content.sending_data' ) ) + '</p>');
    for ( var i = 0 ; i < 4 ; i++ )
    {
        await sleep ( 500 );
        jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner .sending_data' ).append ( ' .' );
    }
    processing = false;
    for ( var i = 0 ; i < 20 ; i++ )
    {
        await sleep ( 500 );
        jQuery ( 'div#agnia_screen_parent div#timer div#timer-content .timer-content-inner' ).append ( ' .' );
    }
}

async function acceptPermissions ()
{
    var form = this.agniaForm;
    var requiredPermissions = this.requiredPermissions;
    var permissions = this.permissions;
    var grantedPermissions = [];
    for ( var i = 0 ; i < requiredPermissions.length ; i++ )
    {
        if ( jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions input#required_permissions_' + i ).prop ( 'checked' ) )
        {
            jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions input#required_permissions_' + i ).parent().removeClass ( 'error' );
            var permissionFields = await getPermissionFields ( organizations[form.dataset.agniaOrganization].permissionsIdx[requiredPermissions[i]] , form );
            var permission = { permission: requiredPermissions[i] , fields: permissionFields };
            grantedPermissions.push ( permission );
        }
        else
        {
            jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions input#required_permissions_' + i ).parent().addClass ( 'error' );
            return;
        }
    }
    for ( var i = 0 ; i < permissions.length ; i++ )
    {
        if ( jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions input#permissions_' + i ).prop ( 'checked' ) )
        {
            var permissionFields = await getPermissionFields ( organizations[form.dataset.agniaOrganization].permissionsIdx[permissions[i]] , form );
            var permission = { permission: permissions[i] , fields: permissionFields };
            grantedPermissions.push ( permission );
        }
    }
    processing = true;
    showTimer();
    sendCommand ( 'storePermissions' , { permissions: grantedPermissions , organization: organizations[form.dataset.agniaOrganization] , returnData: { formKey: form.dataset.agniaKey , permissions: grantedPermissions } } , storedPermissions );
}

async function showPermissionPopup ( requiredPermissions , permissions , form )
{
    jQuery ( document.body ).append ( '<div id="agnia_screen_block"></div>' );
    jQuery ( document.body ).append ( '<div id="agnia_screen_parent"></div>' );
    jQuery ( 'div#agnia_screen_parent' ).append ( '<div id="agnia_screen"></div>' );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen' ).append ( '<div id="agnia_screen_close">X</div>' );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_close' ).click ( closeAgniaWindow );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen' ).append ( '<div id="agnia_screen_content"></div>' );

    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<div class="agnia_screen_logo"><img src="'+baseUrlPlugin+'assets/img/agnia-logo.png" alt="Agnia logo" width="80"></div>' );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<h1>' + escapeHTML ( getI18n ( 'content.grant_permissions' ) ) + '</h1>' );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<p>' + escapeHTML ( getI18n ( 'content.grant_permissions_text_1' ) + organizations[form.dataset.agniaOrganization].name + getI18n ( 'content.grant_permissions_text_2' ) ) + '</p>' );
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<ul id="permissions"></ul>' );
    for ( var i = 0 ; i < requiredPermissions.length ; i++ )
    {
        jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions' ).append ( '<li><input id="required_permissions_' + i + '" type="checkbox" value="' + requiredPermissions[i] + '"> <label for="required_permissions_' + i + '">' + getI18n ( 'permissions.' + requiredPermissions[i] + '.label' ) + ': ' + getI18n ( 'permissions.' + requiredPermissions[i] + '.description' ) + '</label><a href="#" onclick="this.innerHTML= ( this.innerHTML == \'Ocultar detalles\' ? \'Más detalles\' : \'Ocultar detalles\' ); var ele = document.getElementById ( \'agnia_required_permission_description_' + i + '\' ); if ( ele != null ) { ele.style.display = ( ele.style.display == \'none\' ? \'block\' : \'none\' ); } return false;">' + getI18n ( 'content.more_details' ) + '</a><p class="permission_details" id="agnia_required_permission_description_' + i + '" style="display: none">' + getI18n ( 'permissions.' + requiredPermissions[i] + '.details' ) + '</p><p>' + getI18n ( 'content.data_related' ) + '</p><ul id="permission_fields_' + requiredPermissions[i] + '"></ul></li>' );
        var permissionFields = await getPermissionFields ( organizations[form.dataset.agniaOrganization].permissionsIdx[requiredPermissions[i]] , form , true );
        for ( var j = 0 ; j < permissionFields.length ; j++ )
        {
            jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions ul#permission_fields_' + requiredPermissions[i] ).append ( '<li>' + escapeHTML ( permissionFields[j].label ) + ' <strong>' + escapeHTML ( typeof permissionFields[j].displayValue != 'undefined' ? permissionFields[j].displayValue : permissionFields[j].value ) + ( typeof permissionFields[j].agniaProvider != 'undefined' ? ' (' + permissionFields[j].agniaProvider + ')' : '' ) + '</strong></li>' );
        }
    }
    for ( var i = 0 ; i < permissions.length ; i++ )
    {
        jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions' ).append ( '<li><input id="permissions_' + i + '" type="checkbox" value="' + permissions[i] + '"> <label for="permissions_' + i + '">' + getI18n ( 'permissions.' + permissions[i] + '.label' ) + ': ' + getI18n ( 'permissions.' + permissions[i] + '.description' ) + '</label><a href="#" onclick="this.innerHTML= ( this.innerHTML == \'Ocultar detalles\' ? \'Más detalles\' : \'Ocultar detalles\' ); var ele = document.getElementById ( \'agnia_permission_description_' + i + '\' ); if ( ele != null ) { ele.style.display = ( ele.style.display == \'none\' ? \'block\' : \'none\' ); }  return false;">' + getI18n ( 'content.more_details' ) + '</a><p class="permission_details" id="agnia_permission_description_' + i + '" style="display: none">' + getI18n ( 'permissions.' + permissions[i] + '.details' ) + '</p><p>' + getI18n ( 'content.data_related' ) + '</p><ul id="permission_fields_' + permissions[i] + '"></ul></li>' );
        var permissionFields = await getPermissionFields ( organizations[form.dataset.agniaOrganization].permissionsIdx[permissions[i]] , form , true );
        for ( var j = 0 ; j < permissionFields.length ; j++ )
        {
            jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content ul#permissions ul#permission_fields_' + permissions[i] ).append ( '<li>' + escapeHTML ( permissionFields[j].label ) + ' <strong>' + escapeHTML ( typeof permissionFields[j].displayValue != 'undefined' ? permissionFields[j].displayValue : permissionFields[j].value ) + ( typeof permissionFields[j].agniaProvider != 'undefined' ? ' (' + permissionFields[j].agniaProvider + ')' : '' ) + '</strong></li>' );
        }
    }
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content' ).append ( '<button id="accept">' + getI18n ( 'content.accept' ) + '</button> <button id="reject">' + getI18n ( 'content.reject' ) + '</button> ' );

    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content button#accept' )[0].requiredPermissions = requiredPermissions;
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content button#accept' )[0].permissions = permissions;
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content button#accept' )[0].agniaForm = form;
    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content button#accept' ).click ( acceptPermissions );

    jQuery ( 'div#agnia_screen_parent div#agnia_screen div#agnia_screen_content button#reject' ).click ( function() {
        closeAgniaWindow();
    } );

}

getKey = function()
{
    var result           = '';
    var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for ( var i = 0 ; i < 10 ; i++ )
    {
       result += characters.charAt ( Math.floor ( Math.random() * charactersLength ) );
    }
    result += ( new Date() ).getTime().toString();
    return result;
}

var formElements = {};
var forms = {};
var popup = null;
var organizations = {};
var getOrganizationUrl = apiBaseUrl + 'getOrganization/get';
var organizationStorageAddress = '0xf5AF235edB3df647edE0f4955588fef7a4e7eCFf';
var permissions = [ 'PROPER_USE' , 'COMMERCIAL_USE' ];
var permissionsIdx = {};
for ( var i = 0 ; i < permissions.length ; i++ )
{
    permissionsIdx[permissions[i]] = 1;
}


function receiveOrganization ( data )
{
    if ( data.errnum )
    {
        console.log ( typeof data.errstr != 'undefined' ? getI18n ( data.errstr ) : getI18n ( 'errors.error' ) );
        return;
    }
    if ( typeof data.data != 'undefined' )
    {
        if ( typeof data.signature == 'undefined' )
        {
          console.log ( 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 != organizationStorageAddress )
            {
                console.log ( getI18n ( 'errors.response_signature_mismatch' ) );
                return;
            }

            if ( typeof data.data != 'undefined' && typeof data.data.organization != 'undefined' &&                 typeof data.data.organization.allowed_urls != 'undefined' && typeof data.data.organization.allowed_urls.length != 'undefined' && data.data.organization.allowed_urls.length > 0 )
            {
              organizations[data.data.organization.address] = data.data.organization;
              organizations[data.data.organization.address].permissionsIdx = {};
              if ( typeof organizations[data.data.organization.address].permissions != 'undefined' && typeof organizations[data.data.organization.address].permissions.length != 'undefined' && organizations[data.data.organization.address].permissions.length > 0 )
              {
                  for ( var i = 0 ; i < organizations[data.data.organization.address].permissions.length ; i++ )
                  {
                      if ( typeof organizations[data.data.organization.address].permissions[i].permission != 'undefined' )
                      {
                        organizations[data.data.organization.address].permissionsIdx[organizations[data.data.organization.address].permissions[i].permission] = organizations[data.data.organization.address].permissions[i];
                      }
                  }
              }
            }
        
        } );
    }
}

function _agnia_init()
{
    jQuery ( document ).click(
        function ( event )
        {
            if ( popup != null )
            {
                document.body.removeChild ( popup );
                popup = null;
            }
        }
    );

    jQuery ( document ).on ( 'keyup' , function ( event )
    {
        if ( event.keyCode == 27 )
        {
           closeAgniaWindow();
        }
    } );

    window.addEventListener ( "message" , function ( event )
    {
        if (event.source == window &&
            event.data &&
            event.data.application == "_agnia" )
        {
                console.log ( event.data );
                console.log ( window._agnia );
        }
    } );
    jQuery('[data-agnia-login="true"]' ).each (
        function ( i , element )
        {
            jQuery ( element ).click ( function()
            {
                var dataType = this.dataset['agniaLoginDataType'];
                if ( typeof this.dataset['agniaElementKey'] == 'undefined' )
                {
                    this.dataset['agniaElementKey'] = getKey();
                }
                sendCommand ( 'getData' , { type: dataType , returnData: { elementKey: this.dataset['agniaElementKey'] } } , receiveLoginData )
            } );
        }
    );

    jQuery('form[data-agnia-form="true"]' ).each (
        function ( i , form )
        {
            console.log ( form );
            //form.autocomplete = disableAutocomplete;
            var key = getKey();
            while ( typeof forms[key] != 'undefined' )
            {
                key = getKey();
            }
            form.dataset.agniaKey = key;
            forms[key] = form;
            var organizationsInProgress = {};
            jQuery ( form ).submit ( function()
            {
                console.log ( this );
                if ( typeof form.dataset.agniaOrganization == 'undefined' || typeof organizations[form.dataset.agniaOrganization] == 'undefined' )
                {
                    console.log ( "No tenemos datos de la organización" );
                    return false;
                }
                var allowedUrl = false;
                for ( var i = 0 ; i < organizations[form.dataset.agniaOrganization].allowed_urls.length ; i++ )
                {
                    if ( form.action.toLowerCase().indexOf ( organizations[form.dataset.agniaOrganization].allowed_urls[i].toLowerCase() ) == 0 )
                    {
                        allowedUrl = true;
                        break;
                    }
                }

                if ( !allowedUrl )
                {
                    console.log ( "La url destino no está permitida para esta organización" );
                    return false;
                }
                if ( typeof form.dataset.agniaPermissions == 'undefined' )
                {
                    console.log ( "No se solicita ningún permiso" );
                    return false;
                }
                var requestedPermissions = form.dataset.agniaPermissions.split ( '|' );
                var approvedPermissions = [];
                for ( var i = 0 ; i < requestedPermissions.length ; i++ )
                {
                    if ( typeof permissionsIdx[requestedPermissions[i]] != 'undefined' && typeof organizations[form.dataset.agniaOrganization].permissionsIdx[requestedPermissions[i]] != 'undefined' )
                    {
                        approvedPermissions.push ( requestedPermissions[i] );
                    }
                }
                requestedPermissions = form.dataset.agniaRequiredPermissions.split ( '|' );
                var approvedRequiredPermissions = [];
                for ( var i = 0 ; i < requestedPermissions.length ; i++ )
                {
                    if ( typeof permissionsIdx[requestedPermissions[i]] != 'undefined' && typeof organizations[form.dataset.agniaOrganization].permissionsIdx[requestedPermissions[i]] != 'undefined' )
                    {
                        approvedRequiredPermissions.push ( requestedPermissions[i] );
                    }
                }
                if ( approvedPermissions.length == 0 && approvedRequiredPermissions.length == 0 )
                {
                    console.log ( "No se solicita ningún permiso válido" );
                    return false;
                }
                showPermissionPopup ( approvedRequiredPermissions , approvedPermissions , form );
                return false;
            } );
            if ( typeof form.dataset.agniaOrganization != 'undefined' && typeof organizationsInProgress[form.dataset.agniaOrganization] == 'undefined' )
            {
                organizationsInProgress[form.dataset.agniaOrganization] = 1;
                var params = {};
                params['organization_address'] = form.dataset.agniaOrganization;
                var requestData = { params: params , timestamp: ( new Date() ).getTime() / 1000 };
                sendCommand ( 'sign' , { data: requestData } , 
                    function ( data )
                    {
                        if ( typeof data == 'undefined' || typeof data.errnum == 'undefined' )
                        {
                            return;
                        }
                        if ( data.errnum === 0 && typeof data.data != 'undefined' )
                        {
                            jQuery.ajax ( {
                                url: getOrganizationUrl ,
                                method: 'POST',
                                data: {
                                    data: serializeObject ( requestData ),
                                    signature: data.data,
                                    address: data.address
                                },
                                complete: function ( resp , status )
                                {
                                    if ( status == 'success' )
                                    {
                                        receiveOrganization ( resp.responseJSON );
                                    }
                                }
                            } );
                        }
                    } );
            }
            for ( var j = 0 ; j < form.elements.length ; j++ )
            {
                if ( typeof form.elements[j].dataset != 'undefined' &&  typeof form.elements[j].dataset.agniaType != 'undefined' )
                {
                    var key = getKey();
                    while ( typeof formElements[key] != 'undefined' )
                    {
                        key = getKey();
                    }
                    form.elements[j].dataset.agniaProvisionalKey = key;
                    sendCommand ( 'getData' , { type: form.elements[j].dataset.agniaType , returnData: { elementKey: key } } , function ( data )
                    {
                        if ( typeof data != 'object' || data.errnum != 0 || typeof data.data != 'object' || typeof data.data.length == 'undefined' || data.data.length == 0 )
                        {
                            return;
                        }
                        var key = data.returnData.elementKey;
                        var jQueryElement = jQuery ( 'input[data-agnia-provisional-key=' + key + ']' );
                        jQueryElement[0].autocomplete = disableAutocomplete;
                        jQueryElement[0].dataset.agniaKey = key;
                        delete jQueryElement[0].dataset.agniaProvisionalKey;
                        formElements[key] = jQueryElement[0];
                        jQueryElement.focus (
                            function ( event )
                            {
                                workingElement = event.target;
                                console.log ( "Buscamos datos de tipo " + event.target.dataset.agniaType );
                                sendCommand ( 'getData' , { type: event.target.dataset.agniaType , returnData: { elementKey: event.target.dataset.agniaKey } } , receiveData );
                                event.stopPropagation();
                            }
                        );
                        jQueryElement.change (
                            function ( event )
                            {
                                delete event.target.dataset.agniaValueKey;
                                delete event.target.dataset.agniaValueProvider;
                                jQuery ( 'input#_agnia_data_' + event.target.dataset.agniaKey ).remove();
                                jQuery ( 'input#_agnia_verification_' + event.target.dataset.agniaKey ).remove();
                            
                            }
                        );
                        jQueryElement.click (
                            function ( event )
                            {
                                if ( popup != null )
                                {
                                    event.stopPropagation();
                                }
                            }
                        );
                    } );
                }
            }
        }
    )
}

function checkUnlocked()
{
    sendCommand ( 'isWalletUnlocked' , {} , function ( data )
    {
        if ( data.errnum == 0 )
        {
            _agnia_init();
        }
        else
        {
            window.setTimeout ( checkUnlocked , 1000 );
        }
    } );
    
}

( function()
{
    if ( window._agniaRunning )
    {
        console.log ( "Corriendo" );
        return;
    }
    window._agniaRunning = true;
  
    window._agnia = {};
    checkUnlocked();

})();
// window.postMessage ( { application: '_agnia' , tema: { a : 'afsd' , b: 'fads' } } , "*" )