dieuph / ACREVIS/ALPHA COB

// ==UserScript==
// @name                ACREVIS/ALPHA COB
// @namespace           https://github.com/dieuph
// @description         COB DATA filler for Acrevis/Alpha
// @author              dieu
// @license             MIT; https://opensource.org/licenses/MIT
// @homepageURL         https://github.com/dieuph
// @updateURL           https://openuserjs.org/meta/dieuph/ACREVISALPHA_COB.meta.js
// @copyright           2018, dieu (https://github.com/dieuph)
// @include             /^http.?://.*\.axonivy\.io/.*$/
// @include             /^http.?://.*localhost:\d{4}/ivy.*$/
// @include             /^http.?://.*192.168.80.27:\d{4}/ivy.*$/
// @include             /^http.?://.*10.124.1.75:\d{4}/ivy.*$/
// @include             /^http.?://.*10.124.1.149:\d{4}/ivy.*$/
// @include             /^http.?://.*10.124.1.231:\d{4}/ivy.*$/
// @require             https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js
// @require             https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js
// @require             https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.16/chance.min.js
// @require             https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.0/js.cookie.min.js
// @grant               GM_addStyle
// @grant               GM_getResourceText
// @version             2.9.1
// ==/UserScript==

/*
2.0
 - UI right panel.
 - update mandatory fields.
2.1
 - update script metadata.
 - change the way to install scripts.
2.2
 - fix legal status.
2.3
 - update document correct button.
2.4
 - apply higher-order function.
2.5
 - fix mandatory fields and remove config tool for server environment.
2.6
 - add new features and make this tool great again.
2.7
 - fix mandatory fields and make anything is random.
2.8
 - clone to github
2.9
 - correct mandatory fields
2.9.1
 - some said something and I do it
*/

var $ = unsafeWindow.$;
var jQuery = unsafeWindow.jQuery;

/* jshint ignore: start */
var inline_src = (<><![CDATA[
/* jshint ignore:end */
    /* jshint esnext: false */
    /* jshint esversion: 6 */

    //*************************************************************************
    // SETTINGS
    //*************************************************************************

    GM_addStyle(GM_getResourceText('pure'));
    GM_addStyle(GM_getResourceText('jquery-confirm'));
    GM_addStyle(`
        .flyover-btn {
            float: right;
            margin: 0px 10px 10px 10px;
            bottom: 0vh;
            width: 100px;
            height: 35px;
            font-weight: 600 !important;
            font-family: \"Open Sans\", sans-serif;
            text-shadow: rgba(0, 0, 0, 0.4) 1px 1px 1px;
            font-size: 15px !important;
            text-align: center !important;
            box-shadow: rgba(0, 0, 0, 0.2) 0px 3px 0px 0px;
            cursor: pointer !important;
            display: block !important;
            line-height: 0px;
            background: linear-gradient(rgb(78, 181, 229) 0%, rgb(56, 158, 213) 100%) !important;
			border-top: none !important;
			border-right: none !important;
			border-bottom: 4px solid rgb(43, 139, 198) !important;
			border-left: none !important;
			border-image: initial !important;
			border-radius: 5px !important;
            color: rgb(251, 251, 251) !important;
        }
        .flyover-wrapper {
            padding: 0px;
            font-weight: 500;
            -webkit-box-shadow: -1px 0px 11px -1px rgba(0,0,0,0.75);
            -moz-box-shadow: -1px 0px 11px -1px rgba(0,0,0,0.75);
            box-shadow: -1px 0px 11px -1px rgba(0,0,0,0.75);
        }
        .flyover-close {
            margin: 10px 0px 10px 8px;
            display: inline-block;
            font-size: 20px;
            cursor: pointer
        }
        .flyover {
            right: -650px;
            bottom: 0px;
            overflow: hidden;
            position: fixed;
            width: 150px;
            opacity: 1;
            z-index: 1050;
            -webkit-transition: all .6s ease;
            -moz-transition: all .6s ease;
            -o-transition: all .6s ease;
            -ms-transition: all .6s ease;
            transition: all .6s ease;
        }
        .flyover.in {
            right: 0px;
            bottom: 0px;
        }
        .flyover.out {
            right: -110px;
            bottom: 0px;
        }
        .text-left {
            text-align: left !important;
        }
        .bold {
            font-weight: bold !important;
        }
    `);

    //*************************************************************************
    // CONSTANTS
    //*************************************************************************

    const config = {
        cookie: 'aa-simulator-flyover-panel',
        tabs: {
            accountHolder: '[id*="accountHolderTabView"] ',
            powerOfAttorney: '[id*="powerOfAttorneyTabView"] ',
            product: '[id*="productTabView"] '
        },
    	envs: {
			local: [
				/^http.?:\/\/localhost:\d{4}\/ivy.*$/gm
			],
			development: [
				/^http.?:\/\/.*192.168.80.27:\d{4}\/ivy.*$/gm
			],
			test: [
			    /^http.?:\/\/.*10.124.1.75:\d{4}\/ivy.*$/gm,
			    /^http.?:\/\/.*-test\.axonivy\.io\/.*$/gm
			],
			qualify: [
			    /^http.?:\/\/.*10.124.1.75:\d{4}\/ivy.*$/gm,
			    /^(?!http.?:\/\/.*?test).*\.axonivy\.io\/.*$/gm
			]
		},
        banks: {
			acrevis: [
				/^https?:\/\/.*\/ivy\/faces.*acrevis\$\d{1}.*$/gm
			],
			alpha: [
			    /^https?:\/\/.*\/ivy\/faces.*alpha\$\d{1}.*$/gm
			]
		},
        buttons: [{
            id: 'ah1',
            text: 'AH1',
            event: onFirstAccountHolderFillerButtonClick
        }, {
            id: 'ah2',
            text: 'AH2',
            event: onSecondAccountHolderFillerButtonClick
        }, {
            id: 'poa1',
            text: 'POA1',
            event: onPowerOfAttorneyFillerButtonClick
        }, {
            id: 'paying',
            text: 'Paying',
            event: onPayingProductFillerButtonClick
        }, {
            active: false,
            id: 'dc',
            text: 'DC',
            event: onPayingProductFillerButtonClick
        }, {
            active: false,
            id: 'dm',
            text: 'DM',
            event: onPayingProductFillerButtonClick
        }, {
            active: false,
            id: 'approval',
            text: 'Approval',
            event: onPayingProductFillerButtonClick
        }, {
            id: 'elca',
            text: 'Elca',
            event: onElcaButtonClick
        }, {
            id: 'dis',
            text: 'Dis',
            event: onSwisscomDisButtonClick
        }]
    };

    const COB_DATA = {
        accountHolder1: {
            personalData: {
                customSalutation: '1',
                titleForSelectMenu: '1',
                firstName: 'Raymond',
                lastName: 'Reddington',
                nationality: 'CH',
                nationalityItemValue: 'CH',
                birthDate: '23.06.60',
                street: 'Schloessli Schoenegg',
                addressHouseNo: '6004',
                zipCode: '8000',
                city: 'Zürich',
                customMaritalStatus: '1',
                legalStatus: '2'
            },
            communication: {
                landLinePhoneI18n: '+41781234567',
                mobilePhoneI18n: '+41781234567',
                email: "test-email@axonactive.com",
                contactViaEmailAndTelephone: 'checked'
            },
            correspondence: {
                personCorrespondenceLanguage: 'de',
                addressee: 'checked',
                salutation: 1,
                firstName: '',
                lastName: '',
                birthDate: '',
                street: '',
                addressHouseNo: '',
                zipCode: '8000',
                city: 'Zürich',
                validDateFrom: '',
                deliveryType: 1,
                reasonForAddress: ''
            },
            kyc: {
                accountOpeningReason: 'Something...',
                isStillStudent: 'checked'
            },
            customerInfo: {
                isCobMoneyOwner: 'checked',
                isBeneficialOwner: 'checked',
                areThereAnyDoubts: 'checked',
                customerSegment: 'AEB',
                advisorId: _getAdvisorId(),
                contractSigningPlace: 'Switzerland',
                contractSigningBankEmployee: 'Banker'
            },
            identification: {
                identificationMethod: 'checked',
                dateOfIssue: '08.08.17',
                dateOfExpiry: '10.08.18',
                identificationNumber: 123456,
                personalInterviewMethod: 'checked',
                placeOfIssue: 'Switzerland'
            },
            fatca: {
                fatcaComponentPnl: 'checked',
                isHaveAUsCitizen: 'checked',
                isBornInUS: 'checked',
                isAUsResidentAlien: 'checked',
                isPerformedSubstantialPresenceTest: 'checked',
                isSubjectToUnlimitedTaxationInUsaForAnyOtherReason: 'checked',
                isSwissResidentAlien: 'checked',
                isClaimDBA: 'checked',
                isWantToInvestInUSShares: 'checked'
            },
            aia: {
                isExclusiveResidentTaxEdit: 'checked',
                multipleRadioTinNumber: 'checked',
                taxResidency: 1,
                taxIdentificationNumber: '123456'
            }
        },
        accountHolder2: {
            personalData: {
                customSalutation: '1',
                titleForSelectMenu: '1',
                firstName: 'Lizzy',
                lastName: 'Keen',
                nationality: 'CH',
                nationalityItemValue: 'CH',
                birthDate: '22.11.90',
                street: 'Ober Krutzi',
                addressHouseNo: '6005',
                zipCode: '8000',
                city: 'Zürich',
                customMaritalStatus: '1',
                overrideByAnotherAddress: 'checked',
                ahIndexForEmail: 'checked',
                partnerSigning: "SINGLE",
                legalStatus: '2'
            },
            communication: {
                landLinePhoneI18n: '+41781234567',
                mobilePhoneI18n: '+41781234567',
                email: "test-email@axonactive.com",
                contactViaEmailAndTelephone: 'checked'
            },
            correspondence: {
                personCorrespondenceLanguage: 'de',
                addressee: 'checked',
                salutation: 1,
                firstName: '',
                lastName: '',
                birthDate: '',
                street: '',
                addressHouseNo: '',
                zipCode: '8000',
                city: 'Zürich',
                validDateFrom: '',
                deliveryType: 1,
                reasonForAddress: ''
            },
            kyc: {
                accountOpeningReason: 'Something...',
                isStillStudent: 'checked',
                relationshipType: 'Something...'
            },
            customerInfo: {
                isCobMoneyOwner: 'checked',
                isBeneficialOwner: 'checked',
                areThereAnyDoubts: 'checked',
                customerSegment: 'AEB',
                advisorId: _getAdvisorId(),
                contractSigningPlace: 'Switzerland',
                contractSigningBankEmployee: 'Banker'
            },
            identification: {
                identificationMethod: 'checked',
                dateOfIssue: '08.08.17',
                dateOfExpiry: '10.08.18',
                identificationNumber: 123456,
                personalInterviewMethod: 'checked',
                placeOfIssue: 'Switzerland'
            },
            fatca: {
                fatcaComponentPnl: 'checked',
                isHaveAUsCitizen: 'checked',
                isBornInUS: 'checked',
                isAUsResidentAlien: 'checked',
                isPerformedSubstantialPresenceTest: 'checked',
                isSubjectToUnlimitedTaxationInUsaForAnyOtherReason: 'checked',
                isSwissResidentAlien: 'checked',
                isClaimDBA: 'checked',
                isWantToInvestInUSShares: 'checked'
            },
            aia: {
                isExclusiveResidentTaxEdit: 'checked',
                multipleRadioTinNumber: 'checked',
                taxResidency: 1,
                taxIdentificationNumber: '123456'
            }
        },
        powerOfAttorney1: {
            person: {
                salutation: '1',
                firstName: 'Tom',
                lastName: 'Keen',
                birthDate: '11.11.88',
                nationality: 'CH',
                nationalityItemValue: 'CH',
                relationWithMainAccountHolder: 'Son'
            },
            addressAndContact: {
                street: 'Ober Krutzi',
                zipCode: '8000',
                city: 'Zürich',
                houseNo: '6004',
                landLinePhoneI18n: '+41781234567'
            },
            assignmentToProduct: {
                regulationType: '1',
                authorizationType: '1'
            }
        },
        products: [{
            paying: {
                accountType: _app().bank == 'alpha' ? 1 : 2,
                maestro: 1,
                shippingInstructions: 1
            }
        }]
    };

    //*************************************************************************
    // APPLICATION INITIALIZE
    //*************************************************************************

    (function() {
        createApplication();
    })();

    function createApplication() {
        createPanel();
        createButtons();
    }

    function createPanel() {
        _.isEmpty(Cookies.get(config.cookie)) && Cookies.set(config.cookie, 'open', { expires: 90 });
        let display = Cookies.get(config.cookie) == 'open' ? 'in' : 'out';
        let icon = (display == 'in') ? '>>' : '<<';
        $('body').after('<div id="flyover-wrapper" class="flyover-wrapper flyover ' + display + '"><a><span class="flyover-close">' + icon +'</span></a><div class="flyover-box"></div></div>');
        $('span.flyover-close').html(icon);
        $('.flyover-close').click(function() {
            let toggle = Cookies.get(config.cookie) == 'open';
            let icon = toggle ? '<<' : '>>';
            let status = toggle ? 'close' : 'open';

            Cookies.set(config.cookie, status, { expires: 90 });
            $('span.flyover-close').html(icon);
            $('#flyover-wrapper').css({right: Cookies.get(config.cookie) == 'open' ? 0 : -110});
        });
    }

    function createButtons() {
        _.map(config.buttons, (value, key, collection) => {
            if (value.active == false) return;
            createButton(value.id, value.text, value. event);
        });
    }

    function createButton(id, text, event) {
        let template = '<button class="flyover-btn tingle-btn tingle-btn--primary" id="{buttonId}"><span class="btn-text">{buttonText}</span></button>';
        let html = template.replace('{buttonId}', id).replace('{buttonText}', text);
        $('.flyover-box').append(html);
        $("#" + id).click(event);
    }

    //*************************************************************************
    //  BUTTON EVENT
    //*************************************************************************

    function onFirstAccountHolderFillerButtonClick(e) {
        e.preventDefault();
        let randomData = _randomAccountHolderData();
        let accountHolder = COB_DATA.accountHolder1;
        Object.entries(accountHolder).forEach(([key, value]) => value = _.extend(value, randomData[key]));
        formFillerAccountHolder(accountHolder);
    }

    function onSecondAccountHolderFillerButtonClick(e) {
        e.preventDefault();
        if (_getAccountHolders() == 1) return;
        let randomData = _randomAccountHolderData();
        let accountHolder = COB_DATA.accountHolder2;
        Object.entries(accountHolder).forEach(([key, value]) => value = _.extend(value, randomData[key]));
        formFillerAccountHolder(accountHolder);
    }

    function onPowerOfAttorneyFillerButtonClick(e) {
        e.preventDefault();
        if (_getPowerOfAttorneys() == 0) return;
        var randomData = _randomPowerOfAttorneyData();
        var powerOfAttorney = COB_DATA.powerOfAttorney1;
        Object.entries(powerOfAttorney).forEach(([key, value]) => value = _.extend(value, randomData[key]));
        fromFillerPowerOfAttorney(powerOfAttorney);
    }

    function onPayingProductFillerButtonClick(e) {
        e.preventDefault();
        formFillerProduct(COB_DATA.products[0]);
    }

    function onDuplicateCheckFillerButtonClick(e) {
        e.preventDefault();
    }

    function onDocumentManagementFillerButtonClick(e) {
        e.preventDefault();
        formFillerDocumentManagement();
    }

    function onApprovalFillerButtonClick(e) {
        e.preventDefault();
        formFillerApproval();
    }

    function onElcaButtonClick(e) {
        e.preventDefault();
        console.log('Dis clicked');
        return;

        var content = `
        <form class="pure-form pure-form-aligned" style="font-size: 15px" id="elca">
            <fieldset>
                <div class="pure-control-group">
                    <label for="cobId" class="bold">COB ID</label>
                    <input class="pure-input-1-2" type="text" name="cobId" id="cobId" placeholder="e.g. COB000123" />
                </div>

                <div class="pure-control-group">
                    <label for="documentId" class="bold">Document ID</label>
                    <input class="pure-input-1-2" type="text" name="documentId" id="documentId" placeholder="e.g. COBD000000086" />
                </div>

                <div class="pure-control-group">
                    <label for="documentType" class="bold">Document Type</label>
                    <input class="pure-input-1-2" type="text" name="documentType" id="documentType" placeholder="e.g. BV049" />
                </div>

                <div class="pure-control-group">
                    <label for="returnPages" class="bold">Return Pages</label>
                    <select class="pure-input-1-2" name="returnPages" id="returnPages">
                        <option value="1">1</option>
                        <option value="2">2</option>
                    </select>
                </div>

                <div class="pure-control-group">
                    <label for="environment" class="bold">Environment</label>
                    <select class="pure-input-1-2" name="environment" id="environment">
                        <option value="development">Development</option>
                        <option value="test">Test</option>
                        <option value="qualify">Qualify</option>
                        <option value="local">Local</option>
                    </select>
                </div>

                <div class="pure-control-group">
                    <label for="bank" class="bold">Bank</label>
                    <select class="pure-input-1-2" name="bank" id="bank">
                        <option value="alpha">Alpha</option>
                        <option value="acrevis">Acrevis</option>
                    </select>
                </div>
            </fieldset>
        </form>
        `;

        var ftPlaceholder = $('[id$="documentList"]').find('table tbody tr').filter(function(index, item, array) { if ($(item).find('td.ft-doc-type-col span').html() == 'BV049') return item; });
        var ftDocId = $($(ftPlaceholder).find('td.ft-doc-description-col div span.ft-doc-description-text.doc-id'));
        var ftDocType = $($(ftPlaceholder).find('td.ft-doc-type-col span')) || {};

        var data = {
            cobId: typeof Fintech != "undefined" ? Fintech.DataGathering.value.cobId : "",
            documentId: ftDocId.html() ? ftDocId.html().substring(ftDocId.html().lastIndexOf('COBD')) : "",
            documentType: ftDocType.html()
        };

        $.confirm({
            title: 'Elca Return Simulator',
            boxWidth: '20%',
            useBootstrap: false,
            backgroundDismiss: true,
            content: content,
            buttons: {
                formSubmit: {
                    text: 'Submit',
                    btnClass: 'btn-blue',
                    action: function () {
                        var submitedData = {
                            cobId: this.$content.find('#cobId').val(),
                            documentId: this.$content.find('#documentId').val(),
                            documentType: this.$content.find('#documentType').val(),
                            returnPages: this.$content.find('#returnPages').val(),
                            environment: this.$content.find('#environment').val(),
                            bank: this.$content.find('#bank').val()
                        };
                        console.log(submitedData);
                        return;

                        $.ajax({
                            url: "http://localhost:6789/api/elca/feedback",
                            dataType: 'json',
                            type: 'post',
                            contentType: 'application/x-www-form-urlencoded',
                            data: submitedData,
                            success: function(res, status, xhr) {
                                console.log("success");
                                console.log(res)
                            },
                            error: function(xhr, status, error) {
                                console.log("fail");
                                console.log(error);
                            }
                        });
                    }
                },
                cancel: () => {},
            },
            onContentReady: function() {
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click');
                });
            },
            onOpen: function() {
                $('form#elca input#cobId').val(data.cobId);
                $('form#elca input#documentId').val(data.documentId);
                $('form#elca input#documentType').val(data.documentType);
                !_.isEmpty(_app().env) && $('form#elca select#environment').val(_app().env);
                !_.isEmpty(_app().bank) && $('form#elca select#bank').val(_app().bank);
            }
        });
    }

    function onSwisscomDisButtonClick(e) {
        e.preventDefault();
        console.log('Dis clicked')
    }

    function formFillerAccountHolder(accountHolder) {
        _fillHighOrder(accountHolder);
        _fillFatca(accountHolder);
        _fillIdentification(accountHolder);
        _fillPersonalData(accountHolder);
        _fillCommunication(accountHolder);
        _fillKyc(accountHolder);
        _fillCustomerInfo(accountHolder);
        _fillAia(accountHolder);
    }

    function formFillerProduct(product) {
        _fillPaying(product);
    }

    function fromFillerPowerOfAttorney(poa) {
        _fillPerson(poa);
        _fillAddressAndContact(poa);
        _fillAssignmentToProduct(poa);
    }

    function formFillerDocumentManagement() {
        _funqueue('[id*="documentList"]', 'select', 1000, (id, item, index) => {
            $($(id).find(item)[index]).val('DOCUMENT_CORRECT').change();
        });
        $($('[id$="taskGuidelinesInfoSection"]').find('input')[0]).attr('checked', 'checked').change();
    }

    function formFillerApproval() {
        _funqueue('[id$="taskGuidelinesInfoSection"]', 'input', 500, (id, item, index) => {
            $($(id).find(item)[index]).attr('checked', 'checked').change();
        });
    }

    //*************************************************************************
    // PRIVATE METHOD
    //*************************************************************************

    function _funqueue(id, item, timer, action) {
        var funqueue = [];
        var index = 0;
        if ($(id).find(item).length == 0) return;
        _.each($(id).find(item), () => { funqueue.push(() => {
            return $.Deferred(function(dfd) {
                setTimeout(function() {
                    action(id, item, index);
                    dfd.resolve(index);
                    index++;
                }, timer);
            }).promise();
        })});
        _queue(funqueue);
    }

    function _queue(funqueue) {
        var deferred = funqueue.pop();
        return deferred().then(() => {
            return $({}).queue("fun", $.map(funqueue, (fn) => { return (next) => { return fn().then(next) } }))
                        .dequeue("fun")
                        .promise("fun")
                        .then(() => { return "complete" });
        });
    }

    function _randomAccountHolderData() {
        return {
            personalData: {
                customSalutation: chance.character({ pool: '12' }),
                firstName: chance.first(),
                lastName: chance.last(),
                birthDate: chance.birthday({ year: chance.year({ min: 1960, max: 2000 }), string: true, american: false }).replace(/\//g, '.'),
                street: chance.street({ country: 'us' }),
                addressHouseNo: chance.zip()
            },
            communication: {
                landLinePhoneI18n: '+4178' + chance.phone({ formatted: false }).substring(3),
                mobilePhoneI18n: '+4178' + chance.phone({ formatted: false }).substring(3),
                email: chance.email()
            },
            correspondence: {
                salutation: chance.character({ pool: '12' }),
                firstName: chance.first(),
                lastName: chance.last(),
                birthDate: chance.birthday({ year: chance.year({ min: 1960, max: 2000 }), string: true, american: false }).replace(/\//g, '.'),
                street: chance.street({ country: 'us' }),
                addressHouseNo: chance.zip(),
                validDateFrom: chance.date({ year: chance.year({ min: 2019, max: 2022 }), string: true, american: false }).replace(/\//g, '.'),
                reasonForAddress: chance.sentence({ words: 3 }),
                deliveryType: chance.character({ pool: '12' })
            },
            kyc: {
                accountOpeningReason: chance.sentence({ words: 5 })
            },
            customerInfo: {
                contractSigningPlace: chance.address(),
                contractSigningBankEmployee: chance.name()
            },
            identification: {
                identificationNumber: chance.string({ length: 6, pool: '123456789' })
            },
        };
    }

    function _randomPowerOfAttorneyData() {
        return {
            person: {
                salutation: chance.character({ pool: '12' }),
                firstName: chance.first(),
                lastName: chance.last(),
                birthDate: chance.birthday({ year: chance.year({ min: 1960, max: 2000 }), string: true, american: false }).replace(/\//g, '.')
            },
            addressAndContact: {
                street: chance.street({ country: 'us' }),
                houseNo: chance.zip(),
                landLinePhoneI18n: '+4178' + chance.phone({ formatted: false }).substring(3)
            }
        };
    }

	function _detect(patterns, selector, action) {
	    let detects = [];
	    _.each(patterns, (pattern) => {
	        if (selector(pattern)) {
	            detects.push(action(pattern, patterns));
	        }
	    });
	    return detects;
	}

	function _check(patterns) {
	    let selector = pattern => {
	        let matches = _.filter(pattern, (regex) => { return $(location).attr('href').match(regex); })
	        return !_.isEmpty(matches);
	    }
	    let action = (pattern, patterns) => {
	        return (_.invert(patterns))[_.toString(pattern)];
	    }
	    let detected = _detect(patterns, selector, action);

	    return _.isEmpty(detected) ? '' : detected[0];
	}

	function _app() {
		return {
		    env: _check(config.envs),
		    bank: _check(config.banks)
		};
	}

    function _getAccountHolders() {
        return $('[id$="selectAccountHolder_guiFrmInsideUIRepeat"]').length;
    }

    function _getPowerOfAttorneys() {
        return $('[id$="selectPowerOfAttorney_guiFrmInsideUIRepeat"]').length;
    }

    function _getAdvisorId() {
        return $($(config.tabs.accountHolder + '[id$="advisor"]').find('select option')[1]).val();
    }

    function _waiter() {
        return new Promise(resolve => {
            requestAnimationFrame(resolve);
        });
    }

    async function _checkElement(selector) {
        while (document.querySelector(selector) === null) {
            await _waiter();
        }
        return true;
    }

    function _fillHighOrder(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.customerInfo;
        let app = _app();

        if (app.bank == 'alpha') {
            $(tabViewId + '[id$="isOwnerMoney:0"]').attr('checked', data.isCobMoneyOwner).change();
            $(tabViewId + '[id$="isOwnerMoney:1"]').attr('checked', null);

            $(tabViewId + '[id$="isBeneficialOwner:0"]').attr('checked', null);
            $(tabViewId + '[id$="isBeneficialOwner:1"]').attr('checked', data.isBeneficialOwner).change();

            $(tabViewId + '[id$="contractSigningPlace"]').val(data.contractSigningPlace).change();
            $(tabViewId + '[id$="contractSigningBankEmployee"]').val(data.contractSigningBankEmployee).change();
        }
    }

    function _fillPersonalData(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.personalData;

        $(tabViewId + '[id$="personCustomSalutation_input"]').val(data.customSalutation).change();
        $(tabViewId + '[id$="personFirstName"]').val(data.firstName).change();
        $(tabViewId + '[id$="personLastName"]').val(data.lastName).change();
        $(tabViewId + '[id$="personNationality"]').val(data.nationality).change();
        $(tabViewId + '[id$="personNationalityItemValue"]').val(data.nationalityItemValue);
        $($(tabViewId + '[id$="personBirthDate_input"]')[0]).val(data.birthDate).change();
        $(tabViewId + '[id$="addressStreet"]').val(data.street).change();
        $(tabViewId + '[id$="addressHouseNo"]').val(data.addressHouseNo).change();
        $(tabViewId + '[id$="addressZipCode"]').val(data.zipCode).change();
        $(tabViewId + '[id$="addressCity"]').val(data.city).change();

        if (_getAccountHolders() == 2) {
            $(tabViewId + '[id$="overrideByAnotherAddress:0"]').attr('checked', data.overrideByAnotherAddress).change();
            $(tabViewId + '[id$="overrideByAnotherAddress:1"]').attr('checked', null);
            $(tabViewId + '[id$="ahIndexForEmail:0"]').attr('checked', data.ahIndexForEmail).change();
            $(tabViewId + '[id$="ahIndexForEmail:1"]').attr('checked', null);
            $(tabViewId + '[id$="partnerSigning_input"]').val(data.partnerSigning).change();
            $(tabViewId + '[id$="legalStatus_input"]').val(data.legalStatus).change();
        }
    }

    function _fillCommunication(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.communication;
        let app = _app();

        if (app.bank == 'acrevis') {
            $(tabViewId + '[id$="contactViaEmailAndTelephone:0"]').attr('checked', null);
            $(tabViewId + '[id$="contactViaEmailAndTelephone:1"]').attr('checked', data.contactViaEmailAndTelephone).change();
        }

        $(tabViewId + '[id$="landLinePhoneI18n"]').val(data.landLinePhoneI18n).change();
        $(tabViewId + '[id$="mobilePhoneI18n"]').val(data.mobilePhoneI18n).change();
        $(tabViewId + '[id$="email"]').val(data.email).change();
    }

    function _fillCorrespondence(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.correspondence;
        if (_getAccountHolders() == 2) return;

        $(tabViewId + '[id$="Addressee:0"]').attr('checked', 'checked').change();
        $(tabViewId + '[id$="Addressee:1"]').attr('checked', null).change();

        _checkElement('[id$="addressInCorrespondence:addressStreet"]').then((element) => {
            $(tabViewId + '[id$="personSalutation_input"]').val($($(tabViewId + '[id$="personSalutation_input"]').find('option')[data.salutation]).val()).change();
            $(tabViewId + '[id$="personInCorrespondence:personFirstName"]').val(data.firstName).change();
            $(tabViewId + '[id$="personInCorrespondence:personLastName"]').val(data.lastName).change();
            $($(tabViewId + '[id$="personInCorrespondence:personBirthDate_input"]')[0]).val(data.birthDate).change();

            $(tabViewId + '[id$="addressInCorrespondence:addressStreet"]').val(data.street).change();
            $(tabViewId + '[id$="addressInCorrespondence:addressHouseNo"]').val(data.addressHouseNo).change();
            $(tabViewId + '[id$="addressInCorrespondence:addressZipCode"]').val(data.zipCode).change();
            $(tabViewId + '[id$="addressInCorrespondence:addressCity"]').val(data.city).change();
            $($('[id$="validDateFrom_input"]')[0]).val(data.validDateFrom).change();
            $(tabViewId + '[id$="deliveryType_input"]').val($($(tabViewId + '[id$="deliveryType_input"]').find('option')[data.deliveryType]).val()).change();
            $(tabViewId + '[id$="reasonForAddress"]').val(data.reasonForAddress).change();
        });
    }

    function _fillKyc(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.kyc;

        $(tabViewId + '[id$="accountOpeningReason"]').val(data.accountOpeningReason).change();

        if (_getAccountHolders() == 2) {
            $(tabViewId + '[id$="isStillStudent:0"]').attr('checked', null);
            $(tabViewId + '[id$="isStillStudent:1"]').attr('checked', data.isStillStudent).change();
            $(tabViewId + '[id$="relationshipType"]').val(data.relationshipType).change();
        }
    }

    function _fillCustomerInfo(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.customerInfo;

        $(tabViewId + '[id$="isCobMoneyOwner:0"]').attr('checked', data.isCobMoneyOwner).change();
        $(tabViewId + '[id$="isCobMoneyOwner:1"]').attr('checked', null);

        $(tabViewId + '[id$="customerSegment_input"]').val(data.customerSegment).change();
        $(tabViewId + '[id$="advisor_input"]').val(data.advisorId).change();
    }

    function _fillIdentification(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.identification;

        $(tabViewId + '[id$="identificationMethod:0"]').attr('checked', data.identificationMethod);
        $(tabViewId + '[id$="identificationMethod:1"]').attr('checked', null).change();

        _checkElement('[id$="personalInterviewMethod:0"]').then((element) => {
            $(tabViewId + '[id$="personalInterviewMethod:0"]').attr('checked', data.personalInterviewMethod).change();
            $(tabViewId + '[id$="personalInterviewMethod:1"]').attr('checked', null);
            $(tabViewId + '[id$="dateOfIssue_input"]').val(data.dateOfIssue).change();
            $(tabViewId + '[id$="dateOfExpiry_input"]').val(data.dateOfExpiry).change();
            $(tabViewId + '[id$="placeOfIssue"]').val(data.placeOfIssue).change();

            if ($(tabViewId + '[id$="identificationMethod:0"]').attr('checked') != undefined) {
                $(tabViewId + '[id$="identificationType_input"]').val($($(tabViewId + '[id$="identificationType_input"]').find('option')[1]).val()).change();
                $(tabViewId + '[id$="identificationNumber"]').val(data.identificationNumber).change();
            }
        });

    }

    function _fillFatca(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.fatca;
        let app = _app();

        if (app.bank == 'acrevis') {
            $(tabViewId + '[id$="fatcaComponentPnl"]').find('div div:nth-child(3) div:nth-child(1) input').attr('checked', data.fatcaComponentPnl).change();
        }

        if (app.env != 'local') {
            if (app.bank == 'alpha') {
                $(tabViewId + '[id$="isHaveAUsCitizen:0"]').attr('checked', null);
                $(tabViewId + '[id$="isHaveAUsCitizen:1"]').attr('checked', data.isHaveAUsCitizen).change();

                $(tabViewId + '[id$="isBornInUS:0"]').attr('checked', null);
                $(tabViewId + '[id$="isBornInUS:1"]').attr('checked', data.isBornInUS).change();

                $(tabViewId + '[id$="isAUsResidentAlien:0"]').attr('checked', null);
                $(tabViewId + '[id$="isAUsResidentAlien:1"]').attr('checked', data.isAUsResidentAlien).change();

                $(tabViewId + '[id$="isSubjectToUnlimitedTaxationInUsaForAnyOtherReason:0"]').attr('checked', null);
                $(tabViewId + '[id$="isSubjectToUnlimitedTaxationInUsaForAnyOtherReason:1"]').attr('checked', data.isSubjectToUnlimitedTaxationInUsaForAnyOtherReason).change();

                $(tabViewId + '[id$="isWantToInvestInUSShares:0"]').attr('checked', data.isWantToInvestInUSShares).change();
                $(tabViewId + '[id$="isWantToInvestInUSShares:1"]').attr('checked', null);
            }

            if (app.bank == 'acrevis') {
                _checkElement('[id$="isHaveAUsCitizen:0"]').then((element) => {
                    $(tabViewId + '[id$="isHaveAUsCitizen:0"]').attr('checked', null);
                    $(tabViewId + '[id$="isHaveAUsCitizen:1"]').attr('checked', data.isHaveAUsCitizen).change();

                    $(tabViewId + '[id$="isBornInUS:0"]').attr('checked', null);
                    $(tabViewId + '[id$="isBornInUS:1"]').attr('checked', data.isBornInUS).change();

                    $(tabViewId + '[id$="isAUsResidentAlien:0"]').attr('checked', null);
                    $(tabViewId + '[id$="isAUsResidentAlien:1"]').attr('checked', data.isAUsResidentAlien).change();

                    $(tabViewId + '[id$="isPerformedSubstantialPresenceTest:0"]').attr('checked', null);
                    $(tabViewId + '[id$="isPerformedSubstantialPresenceTest:1"]').attr('checked', data.isPerformedSubstantialPresenceTest).change();

                    $(tabViewId + '[id$="isSubjectToUnlimitedTaxationInUsaForAnyOtherReason:0"]').attr('checked', null);
                    $(tabViewId + '[id$="isSubjectToUnlimitedTaxationInUsaForAnyOtherReason:1"]').attr('checked', data.isSubjectToUnlimitedTaxationInUsaForAnyOtherReason).change();

                    $(tabViewId + '[id$="isClaimDBA:0"]').attr('checked', null);
                    $(tabViewId + '[id$="isClaimDBA:1"]').attr('checked', data.isClaimDBA).change();
                });
            }
        }

    }

    function _fillAia(accountHolder) {
        let tabViewId = config.tabs.accountHolder;
        let data = accountHolder.aia;

        $(tabViewId + '[id$="isExclusiveResidentTaxEdit:0"]').attr('checked', 'checked').change();
        $(tabViewId + '[id$="isExclusiveResidentTaxEdit:1"]').attr('checked', null);

        _checkElement('[id$="taxResidency_input"]').then((element) => {
            $(tabViewId + '[id$="taxResidency_input"]').val($($(tabViewId + '[id$="taxResidency_input"]').find('option')[data.taxResidency]).val()).change();
            $(tabViewId + '[id$="taxIdentificationNumber"]').val(data.taxIdentificationNumber).change();
        });
    }

    function _fillPaying(product) {
        if (product.paying == undefined) {
            return;
        }

        let tabViewId = config.tabs.product;
        let data = product.paying;

        if (!$('[href$="payingTab"]').parent().hasClass('ui-state-active')) {
            return;
        }

        if ($(tabViewId + '[id$="accountType_input"]').find('option').length <= 1) {
            alert('[WARNING] empty Account type');
            return;
        }

        $(tabViewId + '[id$="accountType_input"]').val($($(tabViewId + '[id$="accountType_input"]').find('option')[parseInt(data.accountType)]).val()).change();

        _checkElement('[id$="addMaestroCardAtBottomPaying"]').then((element) => {
            $('[id$="addMaestroCardAtBottomPaying"]').find('button').click();
            $(tabViewId + '[id$="maestro_input"]').val($($(tabViewId + '[id$="maestro_input"]').find('option')[1]).val()).change();
            $(tabViewId + '[id$="maestro_label"]').html($($(tabViewId + '[id$="maestro_input"]').find('option')[1]).val()).change();
            $(tabViewId + '[id$="shippingInstructions_input"]').val($($(tabViewId + '[id$="shippingInstructions_input"]').find('option')[1]).val()).change();
            $(tabViewId + '[id$="shippingInstructions_label"]').html($($(tabViewId + '[id$="shippingInstructions_input"]').find('option')[1]).html()).change();
        });
    }

    function _fillPerson(poa) {
        let tabViewId = config.tabs.powerOfAttorney;
        let data = poa.person;

        $(tabViewId + '[id$="personSalutation_input"]').val($($(tabViewId + '[id$="personSalutation_input"]').find('option')[parseInt(data.salutation)]).val()).change();
        $(tabViewId + '[id$="personFirstName"]').val(data.firstName).change();
        $(tabViewId + '[id$="personLastName"]').val(data.lastName).change();
        $(tabViewId + '[id$="personNationality"]').val(data.nationality).change();
        $(tabViewId + '[id$="personNationalityItemValue"]').val(data.nationalityItemValue);
        $(tabViewId + '[id$="personBirthDate_input"]').val(data.birthDate).change();
        $(tabViewId + '[id$="relationWithMainAH"]').val(data.relationWithMainAccountHolder).change();
    }

    function _fillAddressAndContact(poa) {
        let tabViewId = config.tabs.powerOfAttorney;
        let data = poa.addressAndContact;

        $(tabViewId + '[id$="addressStreet"]').val(data.street).change();
        $(tabViewId + '[id$="addressZipCode"]').val(data.zipCode).change();
        $(tabViewId + '[id$="addressCity"]').val(data.city).change();
        $(tabViewId + '[id$="addressHouseNo"]').val(data.houseNo).change();
        $(tabViewId + '[id$="landLinePhoneI18n"]').val(data.landLinePhoneI18n).change();
    }

    function _fillAssignmentToProduct(poa) {
        let tabViewId = config.tabs.powerOfAttorney;
        let data = poa.assignmentToProduct;

        $(tabViewId + '[id$="regulationType_input"]').val($($(tabViewId + '[id$="regulationType_input"]').find('option')[parseInt(data.regulationType)]).val()).change();
        $(tabViewId + '[id$="authorizationType_input"]').val($($(tabViewId + '[id$="authorizationType_input"]').find('option')[parseInt(data.authorizationType)]).val()).change();
    }

/* jshint ignore:start */
]]></>).toString();
var c = Babel.transform(inline_src, { presets: [ "es2015", "es2016" ] });
eval(c.code);
/* jshint ignore:end */