$(document).ready(function() {
    loadDatePicker();
    displayToggleableQuestions();

    /**
     * Hide/show toggleable questions
     */
    $('.question .question-checkbox').on('change', function() {
        var toggleQuestionModules = $(this).attr('data-toggles-qm');
        var elementCurrentlyChecked = $(this).prop('checked');

        if (!toggleQuestionModules || toggleQuestionModules.length < 3) {
            return true;
        }
        toggleQuestionModules = toggleQuestionModules.split(';');
        $.each(toggleQuestionModules, function(i, questionModuleId) {
            if (elementCurrentlyChecked) {
                $('#question-' + questionModuleId).removeClass('hidden');
            } else {
                $('#question-' + questionModuleId).addClass('hidden');
            }
        });
        updateQuestionNumbers();
    });

    /**
     * Toggle toggleable questions on page reload and/or restoring paused application
     * @returns {undefined}
     */
    function displayToggleableQuestions() {
        "use strict";
        $(".question .question-checkbox[data-toggles-qm]").each(function() {
            var questionModuleIds = $(this).attr('data-toggles-qm');
            if (questionModuleIds.length > 3) {
                var elementCurrentlyChecked = $(this).prop('checked');
                var toggleQuestionModules = questionModuleIds.split(';');
                $.each(toggleQuestionModules, function(i, questionModuleId) {
                    if (elementCurrentlyChecked) {
                        $('#question-' + questionModuleId).removeClass('hidden');
                    } else {
                        $('#question-' + questionModuleId).addClass('hidden');
                    }
                });
            }
        });
    }

    /**
     * Update question numbers when hide/show questions.
     * 
     * Only questions without hidden class
     * 
     * @returns {undefined}
     */
    function updateQuestionNumbers() {
        var questionNumber = 1;
        $('.question-nr').each(function() {
            if (!$(this).closest('.question').hasClass('hidden')) {
                $(this).html(questionNumber + '. ');
                questionNumber++;
            }
        });
    }

    $('.question input').on('input onprotertychange change', function() {
        $(this).closest('div.question').removeClass('alert alert-danger');
    });

    $(".question-checkbox").on('click', function(event) {
        var name = $(this).attr('name');
        var value = $(this).is(":checked");
        var type = 'checkbox';
        saveAnswer(name, value, type);
    });

    $(".question-select").on('change', function(event) {
        var name = $(this).attr('name');
        var value = $(this).val();
        var type = 'select';
        saveAnswer(name, value, type);
    });

    $(".question-radio").on('click', function(event) {
        var name = $(this).attr('name');
        var value = $(this).val();
        var type = 'radio';
        saveAnswer(name, value, type);
    });


    $(".question-priority").on('change', function() {
        var name = $(this).attr('name');
        var value = $(this).val();
        var type = 'priority';
        name += '[' + value + ']';

        var selectgroup = $(this).data('selectgroup');
        $(this).closest('.question').removeClass('has-error');

        var changedSelector = this;
        var selected = false;

        $('.' + selectgroup).each(function() {
            if ($(this).val() == value && $(this).attr('id') != $(changedSelector).attr('id') && value != 0) {
                value = 0;
                $(changedSelector).val(value);
                alert('This option has already been chosen');
                return false;
            }
        });

        saveAnswer(name, value, type);
    });

    var timeoutArray = {};
    var textObject = {};

    /**
     * Do not use "change" or "onpropertychange" here. Then it will reload when the user switch alterantive
     */
    $(".question-text").on('input', function() {

        var timeOutKey = $(this).attr('name');

        textObject[timeOutKey] = this;
        $(this).closest('.question').removeClass('has-error');

        clearTimeout(timeoutArray[ timeOutKey ]);

        timeoutArray[ timeOutKey ] = setTimeout(function() {

            var name = $(textObject[timeOutKey]).attr('name');
            var value = $(textObject[timeOutKey]).val();
            var type = 'text';

            if ($(textObject[timeOutKey]).data('type').length > 0) {
                type = $(textObject[timeOutKey]).data('type');
            }

            saveAnswer(name, value, type);
        }, 500);

    });


    /**
     * Old browser fallback for maxlength
     */
    $('textarea[maxlength]').keyup(function() {

        var limit = parseInt($(this).attr('maxlength'));
        var text = $(this).val();
        var chars = text.length;

        // Get parent counter
        $(this).parent().find('.counter').html(chars);


        if (chars > limit) {

            var new_text = text.substr(0, limit);
            $(this).val(new_text);
        }
    });

    $(".question-configurable").on('click', function(event) {
        var name = $(this).attr('name');
        var value = $(this).val();
        var type = 'radio';
        saveAnswer(name, value, type);

        var altOptionId = $(this).data('altoptionid');
        var altOptionGroup = $(this).data('altoptiongroup');

        //-- Hide related textareas in same radiogroup
        $('.' + altOptionGroup).addClass('hidden');

        var altOption = $('#' + altOptionId);

        //-- Show textarea
        if (altOption.length) {
            altOption.removeClass('hidden');
            altOption.focus();
            if (altOption.data('type') === 'text-config') {
                //-- Resave text, incase user switch answers back and fort
                value = altOption.val();
                name = altOption.attr('name');
                type = 'text-config';
                saveAnswer(name, value, type);
            }
        }
    });

    rebindQuestionFilelistLinks();

});

function loadDatePicker() {
    $('body').on('focus', '.datepicker', function(event) {
        if (!$(this).data('DateTimePicker')) {  // Check if DateTimePicker is not already initialized
            $(this).datetimepicker({
                sideBySide: true,
                useCurrent: false,
                locale: window.mnLocale,
                format: 'YYYY-MM-DD',
                widgetPositioning: {
                    horizontal: 'auto',
                    vertical: 'bottom'
                },
                ignoreReadonly: true
            }).on('dp.change focus', function(event) {
                var name = $(this).attr('name');
                var value = $(this).val() ? $(this).val() : '';
                var type = 'date-picker';
                saveAnswer(name, value, type);
            });

            if ($(this).data('maxdate')) {
                $(this).data("DateTimePicker").maxDate($(this).data('maxdate'));
            }
        }
    });
}


function rebindQuestionFilelistLinks()
{
    $('.question .filelist .icon-delete').off('click');
    $('.question .filelist .icon-delete').on('click', function(event) {
        event.preventDefault();
        var row = $(this).closest('.divtable-row');
        var type = $(this).closest('.question').data('type');
        var questionid = $(this).closest('.question').data('id');
        var id = row.data('id');
        row.hide(); //-- Hide first

        var postData = {
            type: type,
            questionid: questionid,
            id: id,
            projectType: applyProcess.getProject().getType(),
            projectId: applyProcess.getProject().getId(),
            formType: applyProcess.getProject().getFormType()
        };

        $.post('/application/delete/question/file/', postData, function(jsonData) {
            if (jsonData.status === 'success') {
                row.remove(); //-- Remove on success
                updateFileAnswer(type + "-" + questionid + "-uploaded", 'subtract');
            } else {
                row.show();
                alert('ERROR_REMOVING_FILE');
            }
        });
    });
}

function saveAnswer(name, value, type)
{
    var postData = {
        name: name,
        value: value,
        type: type,
        projectType: applyProcess.getProject().getType(),
        projectId: applyProcess.getProject().getId(),
        formType: applyProcess.getProject().getFormType()
    };

    $.post("/apply/question/answer", postData).fail(function (xhr) {
        if (typeof xhr.responseJSON.msg !== 'undefined') {
            alert(xhr.responseJSON.msg);
            window.location.reload();
        }
    });
}

/**
 * 
 * @param {type} counterElementId ex.) position_question_module-34234-uploaded
 * @param {type} type = add/subtract
 * @returns {undefined}
 */
function updateFileAnswer(counterElementId, type)
{
    var oldValue = $("#" + counterElementId).html();
    if (type === 'subtract') {
        if (oldValue > 0) {
            oldValue--;
        }
    } else {
        oldValue++;
    }
    $("#" + counterElementId).html(oldValue);
}

function reloadQuestionFileAnswer(questionPrefix, questionId, projectType, projectId, formType)
{
    var questionType = $('#' + questionPrefix + '-' + questionId).data('type');
    var postData = {
        id: questionId,
        type: questionType,
        projectType: projectType,
        projectId: projectId,
        formType: formType
    };

    $.getJSON('/apply/getattachedquestionfiles/', postData, function(jsondata) {

        var content = '';
        jsondata = jsondata.files;

        for (var i = 0; i < jsondata.length; i++) {
            var obj = jsondata[i];
            var template = $('#template-attached-filelist-question-' + questionId).html();
            $.each(obj, function(k, v) {
                var regex = new RegExp('{{' + k + '}}', "gi");
                template = template.replace(regex, v);
            });
            template = template.replace('href="#"', 'href="' + obj.file_link + '"');
            content += template;
        }

        $('#question-file-answer-' + questionId + ' .divtable-body').html(content);
        rebindQuestionFilelistLinks();
    });

}
/**
 * OBS! Since this function select first form-group which has name property equals to error message key, make sure that the view "entire page"
 * do NOT have another form-group with same name value.
 * @param  {JQuery.jqXHR.DoneCallback | null} response
 */
const formResponseHandler = function (response) {
    if (response && response?.status === 'error') {
        if (typeof response.msg === "object") {
            Object.entries(response.msg).forEach(([inputName, errorMessage]) => {
                const formElement = $('.form-group').has(`[name="${inputName}"]`).first();
                formElement.addClass('has-error');
                formElement.find('.help-block').first().removeClass('hidden').html(errorMessage)
            });
        } else {
            alert(response.msg);
            window.location.reload();
        }
    }
}

function saveFilesToProfile() {
    const isStoreFilesChecked = $('#store-files-to-profile').is(':checked');
    const postData = {
        projectType: applyProcess.getProject().getType(),
        projectId: applyProcess.getProject().getId(),
        formType: applyProcess.getProject().getFormType(),
        saveFilesToProfile: isStoreFilesChecked
    };
    $.post('/apply/savequickapplytosession/', postData, formResponseHandler);
}

/**
 * Prevent formvalidation on "enter" keydown
 * Will not work with login
 */
$(document).ready(function() {
    let isSubmitting = false;
    $('#form-quickapply input').not('#cover-letter').keydown(function(event) {
        if (event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });

    $('.btn-submit-application').on('click', function(event) {
        isSubmitting = true;
        event.preventDefault();
        let href = $(this).data('href');
        window.location.replace(href);
        return false;
    });

    var timeoutArray = {};
    var textObject = {};

    $(".field-member").on('input change onpropertychange', function() {

        var timeOutKey = $(this).attr('name');

        textObject[timeOutKey] = this;
        $(this).closest('.form-group').removeClass('has-error');

        clearTimeout(timeoutArray[ timeOutKey ]);

        timeoutArray[ timeOutKey ] = setTimeout(function() {

            var inputname = $(textObject[timeOutKey]).attr('name');

            var data = {
                projectType: applyProcess.getProject().getType(),
                projectId: applyProcess.getProject().getId(),
                formType: applyProcess.getProject().getFormType()
            };

            if (inputname === 'year' || inputname === 'month' || inputname === 'day') {
                data['birthdate'] = $('#year').val() + '-' + $('#month').val() + '-' + $('#day').val();
            } else {
                data[inputname] = $(textObject[timeOutKey]).val();
            }

            // If a change event occurs at the same time the submit button is clicked
            if (isSubmitting) {
                return;
            }
            $.post("/apply/savequickapplytosession/", data, formResponseHandler);
        }, 1000);

    });

    $('#member-terms').on('change', function() {

        var data = {
            projectType: applyProcess.getProject().getType(),
            projectId: applyProcess.getProject().getId(),
            formType: applyProcess.getProject().getFormType(),
            memberterms: false
        };

        if ($(this).prop('checked')) {
            if ($(this).data('termsid')) {
                data.memberterms = $(this).data('termsid');
            }
            else {
                data.memberterms = true;
            }
        }

        $.post("/apply/savequickapplytosession/", data, formResponseHandler);

    });

    $('#swedish-citizenship').on('change', function() {
        if ($(this).prop('checked')) {
            $("#soc-line").removeClass('hidden');
            $("#inputsoc").removeClass('hidden');  // checked
        } else {
            $("#soc-line").addClass('hidden');
            $("#inputsoc").addClass('hidden');
        }
    });

    $("#confirm-email").on('change', function() {
        compareEmails();
    });

    $( "#confirm-email" ).on( "paste", function(e) {
        alert('Please type your e-mail to avoid errors');
    });

    function compareEmails() {
        var confirmEmail = $("#confirm-email").val().trim();
        var email = $("#email").val().trim();
        if (confirmEmail !== email) {
            $.topAlert('E-mail addresses do not match', { type: 'danger'});
        }
    }

    $('#smsRecovery').on('click', function() {
        $.topAlert('A new password has been sent to the number registrered on account with email ' + $('#email').val(), {timeout: 3500});
    });

    $('#gdpr-application').change(function(){
        var termsId = $(this).is(':checked') ? $(this).data().termsid : false;
        var postData = {
            projectType: applyProcess.getProject().getType(),
            projectId: applyProcess.getProject().getId(),
            formType: applyProcess.getProject().getFormType(),
            gdpr_application : termsId
        };
        $.post('/apply/savequickapplytosession/', postData, formResponseHandler);
    });
    $('#phone').on('input change onpropertychange', function () {
        $(this).val($(this).val().replaceAll(" ", ""));
    });

    saveFilesToProfile();
    $('#store-files-to-profile').on('change', saveFilesToProfile);
});
$(function () {
    "use strict";

    if ($("#profile_countdown").length) {
        remainingApplicationTimeCountdown("#profile_countdown");
    }
});

function remainingApplicationTimeCountdown(containerId) {
    var containerElement = $(containerId);

    var applicationTimerIntervalId = setInterval(function () {
        var secondsLeft = containerElement.attr('data-remainingApplicationTimeInSeconds');
        if (secondsLeft < 0) {
            clearInterval(applicationTimerIntervalId);
            containerElement.html("Last date of application has expired.");
            $('.btn-submitapplication').hide(500);
            return false;
        }

        containerElement.attr('data-remainingApplicationTimeInSeconds', (secondsLeft - 1));

        secondsLeft = secondsLeft % 86400;
        var hours = parseInt(secondsLeft / 3600);
        secondsLeft = secondsLeft % 3600;
        var minutes = parseInt(secondsLeft / 60);
        var seconds = parseInt(secondsLeft % 60);

        containerElement.html(": " + hours + "h " + minutes + "m " + seconds + "s");

    }, 1000);


}

function printJob(id, lang)
{
    var url = '/cv/generatead/id:' + id + '/candidate:1/';

    if (lang !== null) {
        url += ('lang:' + lang + '/');
    }

    window.open(
            url,
            'printpdf',
            'left=50,top=50,width=1024,height=768,toolbar=0,resizable=1,status=0,menubar=0,scrollbars=1');
}

"use strict";

$(function() {
    /* fix upload in facebook in app browsers */
    document.addEventListener('DOMContentLoaded', function() {
        var ua = navigator.userAgent || navigator.vendor || window.opera;
        if (ua.indexOf('FBAN') > -1 || ua.indexOf('FBAV') > -1 || ua.indexOf('Instagram') > -1) {
            if (document.querySelector('input[accept]') !== null) {
                document.querySelectorAll('input[accept]').forEach(function(el) {
                    el.removeAttribute('accept');
                });
            }
        }
    });

    // Clear modal content after close or else the content want change when used for different purpose
    $('body').on('hidden.bs.modal', '.modal', function () {
        $(this).removeData('bs.modal');
    });

    $('.btn-submitapplication').on('click', function(event) {

        $('.btn-submitapplication').unbind('click');

        $('.btn-submitapplication').bind('click', function(e) {
            e.preventDefault();
        });

    });

    $("#link-cancel-application, .navbar-btn-cancel").on('click', function(event) {
        event.stopPropagation();
        if (confirm('Your application will be removed.')) {
            return true;
        }
        event.preventDefault();
    });

    $(".navbar-btn-cancel-update").on('click', function(event) {
        event.stopPropagation();
        if (confirm('Cancel update?')) {
            return true;
        }
        event.preventDefault();
    });

    $(".navbar-btn-cancel-supplement").on('click', function(event) {
        event.stopPropagation();
        if (confirm('Do you want to cancel the supplement to the application?')) {
            return true;
        }
        event.preventDefault();
    });


    /* There is no form as of now, so just hand click on button */
    var submitInProgress = false;
    $('#link-submit-application, .btn-submitapplication a').on('click', function(event) {
        event.preventDefault();
        if (!submitInProgress) {
            submitInProgress = true;
            window.location.replace($(this).attr('href'));
        }
        return false;
    });

    $('.navbar-btn-submit-supplement a, #submit-supplement-form input[type="submit"]').on('click', function (event) {
        event.stopPropagation();
        event.preventDefault();
        if (!submitInProgress) {
            submitInProgress = true;
            $('#submit-supplement-form').trigger('submit');
        }
    });

    $('#swedish-citizenship').on('change', function() {
        if ($(this).prop('checked')) {
            $("#soc-line").removeClass('hidden');
            $("#inputsoc").removeClass('hidden');  // checked
        } else {
            $("#soc-line").addClass('hidden');
            $("#inputsoc").addClass('hidden');
        }
    });

    $(".citizenship").on('change', function() {
        $('#upload-citizenship-document').removeClass('hidden');

    });

    $('#section-uploaded_cv textarea').on('autoSaved', function() {
        $('#section-uploaded_cv, #section-jobs, #section-education').removeClass('alert alert-danger');
    });

    $('#section-personal_letter textarea').on('autoSaved', function() {
        $('#section-personal_letter').removeClass('alert alert-danger');
    });

    $('.swedish-social-security-number').on('change', function() {

        if ($(this).val() === "2") {
            $('#social_security_number').val("");
            $('#social_security_number').trigger("change");
            $("#no-swedish-social-security-number").removeClass('hidden');
            $("#citizenshipselector").removeClass('hidden');
        } else {
            $("#no-swedish-social-security-number").addClass('hidden');
            $("#citizenshipselector").addClass('hidden');
        }
    });

    if ($("#inputsoc").length) {
        var socialSecurityNumberInput = $('#inputsoc');

        if (socialSecurityNumberInput.length) {
            socialSecurityNumberInput.on('input', function () {
                var help = $('#social_security_number_help');
                var contents = $('#inputsoc').val();

                if (contents.length > 0) {
                    help.removeClass('hidden');
                } else {
                    help.addClass('hidden');
                }
            });

            var help = $('#social_security_number_help');
            if (socialSecurityNumberInput.val().length > 0) {
                help.removeClass('hidden');
            } else {
                help.addClass('hidden');
            }
        }
    }

    $('#socsec-not-available input').on('change', function() {
        var input = $('#inputsoc');
        var help = $('#social_security_number_help');

        input.prop('disabled', $(this).prop('checked'));
        if (input.val() !== '') {
            input.val('');
            input.trigger('change');
        }
        help.addClass('hidden');
    });

    $('.field-citizen').on('change', function() {
        var postData = {
            projectType: applyProcess.getProject().getType(),
            projectId: applyProcess.getProject().getId(),
            formType: applyProcess.getProject().getFormType(),
            field: $(this).attr('name'),
            value: $(this).val()
        };
        $.post("/apply/savecitizen/", postData);
    });

    /* Save GDPR acceptance in apply */
    $('#gdpr-application-accept').change(function(){
        var termsId = $(this).data().termsid;
        var status = $(this).is(':checked') ? 1 : 0;
        var postData = {
            id : termsId,
            status : status,
            projectType: applyProcess.getProject().getType(),
            projectId: applyProcess.getProject().getId(),
            formType: applyProcess.getProject().getFormType()
        };

        $.post('/apply/savegdpr/', postData, function(data) {});
    });

    /* Save skip social security number */
    $('#socsec-not-available input').on('change',function(){
        var status = $(this).is(':checked') ? 1 : 0;
        var postData = {
            status : status,
            projectType: applyProcess.getProject().getType(),
            projectId: applyProcess.getProject().getId(),
            formType: applyProcess.getProject().getFormType()
        };

        $.post('/apply/skipsocialsecuritynumber/', postData, function(data) {});
    });


    var timeoutArray = {};
    $("#last-job-title, #current-job-title, #current_employment_percentage, #desired_employment_percentage, #las_days").on('input change onpropertychange', function() {

        var caller = $(this);
        var timeOutKey = caller.attr('name');

        clearTimeout(timeoutArray[timeOutKey]);

        timeoutArray[timeOutKey] = setTimeout(function() {

            var postData = {
                projectType: applyProcess.getProject().getType(),
                projectId: applyProcess.getProject().getId(),
                formType: applyProcess.getProject().getFormType()
            };
            postData[ caller.attr('name') ] = caller.val();

            $.post("/apply/SavePrecedenceinput", postData);
        }, 1000);

    });

    $('#current_employment_percentage, #desired_employment_percentage').on('change keyup', function() {
        // Remove invalid characters
        var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
        // Remove non-leading minus signs
        sanitized = sanitized.replace(/(.)-+/g, '$1');
        // Remove the first point if there is more than one
        sanitized = sanitized.replace(/\.(?=.*\.)/g, '');
        // Update value
        $(this).val(sanitized);
    });

    // Bind attach
    bindAttachedFilesDelete();

    $('#attached-files-other').on('filelist.updated', function() {
        bindAttachedFilesDelete();
    });

    saveFilesToProfile();
    $('#store-files-to-profile').on('change', saveFilesToProfile);
});

function bindAttachedFilesDelete()
{
    $('#attached-files-other .icon-delete').on('click', function(event) {
        event.preventDefault();
        var id = $(this).closest('.divtable-row').data('id');
        var postData = {
            projectType: applyProcess.getProject().getType(),
            projectId: applyProcess.getProject().getId(),
            formType: applyProcess.getProject().getFormType(),
            id: id
        };

        $.post('/application/delete/other/file/', postData, function() {
            reloadFilelist("attached-files-other");
        });
    });
}

function saveFilesToProfile() {
    const isStoreFilesChecked = $('#store-files-to-profile').is(':checked');
    const postData = {
        projectType: applyProcess.getProject().getType(),
        projectId: applyProcess.getProject().getId(),
        formType: applyProcess.getProject().getFormType(),
        saveFilesToProfile: isStoreFilesChecked
    };
    $.post('/apply/savequickapplytosession/', postData, formResponseHandler);
}
"use strict";

function allowAnotherFileupload(formId) {
    if (formId.indexOf('fileupload-question-') < 0) {
        return true; //Only run for filueupload-questions
    }
    var questionId = formId.replace(/[^0-9]+/g, '');
    var maxNumerOfUploadedFiles = $('#question-' + questionId).attr('data-limit');
    var currentNumberOfUploadedFiles = $('#attached-filelist-question-' + questionId + ' > div').length;

    if (currentNumberOfUploadedFiles >= maxNumerOfUploadedFiles) {
        alert('The maximum number of files has been reached. If you can\'t see your uploaded files, then please reload the page.');
        return false;
    }
    return true;
}

function isFileSizeAndTypeAccepted(formId, data) {
    
    var maxAcceptedFilesize = parseInt($('#' + formId).data('maxFileSize'));
    var currentFilesize = parseInt(data.originalFiles[0].size,10); 
    
    /* if (Number.isNaN(currentFilesize)){ //Number.isNaN NOT working in IE9 */
    if (isNaN(currentFilesize)){
        currentFilesize = 0;
    }
    /*if (Number.isNaN(maxAcceptedFilesize)){ */
    if (isNaN(maxAcceptedFilesize)){
        maxAcceptedFilesize = 0;
    }
    
    if ( (maxAcceptedFilesize > 0) && (currentFilesize > maxAcceptedFilesize) ) {
        alert('File too big. Max size is: ' +  Math.round((maxAcceptedFilesize/1024)/1024) + 'MB');
        return false;
    }
    
    /* Here we could check for type. We only get 'document', 'image' and so on from:
     * console.log($('#' + formId).data('acceptedFileTypeGroup'));
     * but in :
     * console.log(data.originalFiles[0].type);
     * We have mime, like application/pdf 
     * so that would need translation.
    */

    return true;
}function reloadFilelist(filelistid)
{
    var url = $('#' + filelistid).data('source');

    if (url != '') {

        $.getJSON(url, {}, function (jsondata) {

            var content = '';
            jsondata = jsondata.files;

            for (var i = 0; i < jsondata.length; i++) {
                var obj = jsondata[i];
                var template = $('#template-' + filelistid).html();
                $.each(obj, function (k, v) {
                    var regex = new RegExp('{{' + k + '}}', "gi");
                    template = template.replace(regex, v);
                });

                template = template.replace('href="#"', 'href="' + obj.file_link + '"');
                content += template;
            }
            $('#' + filelistid).html(content);
            $('#' + filelistid).triggerHandler('filelist.updated');
        });

    }
}"use strict";

$(function() {
    $(document).on('change', '#country-select-country', function(e) {
        /* e.preventDefault(); */
        if ($('#country-select-subdivisions').length > 0) {
            $.get("/localeinfo/getcounties?country=" + $(this).val(), function(data) {
            let toAppend = "<option>---</option>";
                $.each(data.counties, function(index, county) {
                    toAppend += "<option value='" + index + "'>" + county + "</option>";
                });
                $('#country-select-subdivisions')
                .find('option')
                .remove()
                .end()
                .append(toAppend)
                .prop('disabled', false)
                .trigger('change');
            })
            .fail(function(data) {
                $('#country-select-subdivisions')
                .html('<option value="">---</option>')
                .prop('disabled', true)
                .trigger('change');
            });
        }
    });
});
var textEditor = (function () {
    var commonConfiguration = {
        language : 'en_GB',
        entity_encoding : "raw",
        menubar : false,
        contextmenu: false,
        statusbar : true, // Required by license
        cache_suffix: '?v=4.9.3',
        browser_spellcheck : true,
        relative_urls : false,
    };

    var standard = function(selector, initCallback, customConfig) {
        var config = {
            selector: selector,
            toolbar: 'formatselect | undo redo | bold italic | superscript | bullist numlist | link | removeformat pastetext',
            plugins: 'paste,link,lists',
            block_formats: 'Paragraph=p;Header 1=h1;Header 2=h2;Header 3=h3;Header 4=h4;Header 5=h5;Header 6=h6',
            paste_word_valid_elements: "b,strong,i,em,h1,h2,h3,h4,a,p,br",
            content_style: 'body {font-size: 11pt;}',
            init_instance_callback: initCallback
        };

        if (typeof customConfig !== 'undefined') {
            config = $.extend(config, customConfig);
        }

        initTinyMCE(config);
    };

    var minimal = function(selector) {
        var config = {
            selector : selector,
            toolbar: 'bold italic',
            plugins: 'paste',
            paste_word_valid_elements : "b,strong,i,em",
            forced_root_block: false
        };

        initTinyMCE(config);
    };

    var landingpage = function(selector, height) {
        var config = {
            selector : selector,
            height: height,
            remove_script_host : false,
            plugins: [
                'advlist lists autolink link media image lists charmap hr anchor pagebreak',
                'searchreplace wordcount visualblocks visualchars fullscreen insertdatetime nonbreaking',
                'save table contextmenu directionality template paste code'
            ],
            style_formats: [
                { title: 'Headings', items: [
                    { title: 'Heading 1', format: 'h1' },
                    { title: 'Heading 2', format: 'h2' },
                    { title: 'Heading 3', format: 'h3' },
                    { title: 'Heading 4', format: 'h4' },
                    { title: 'Heading 5', format: 'h5' },
                    { title: 'Heading 6', format: 'h6' }
                ]},
                { title: 'Blocks', items: [
                        { title: 'Paragraph', format: 'p' },
                        { title: 'Div', format: 'div' },
                ]},
                { title: 'Buttons', items: [
                    {title: 'Knapp', inline: 'a', classes: ['btn', 'btn-default']},
                    {title: 'Knapp primär', inline: 'a', classes: ['btn btn-primary']},
                    {title: 'Knapp grön', inline: 'a', classes: ['btn btn-success']}
                ]},
            ],
            content_css: '/assets/css/bootstrap.css,/assets/css/landingpage.css',
            toolbar: 'undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media hr | code',
            entity_encoding : "raw"
        };

        initTinyMCE(config);
    };

    var initTinyMCE = function(config) {
        tinymce.init($.extend(config, commonConfiguration));
    };

    var remove = function(id) {
        var editor = tinyMCE.get(id);
        if (editor) {
            editor.remove();
        }
    };

    return {
        standard: standard,
        minimal: minimal,
        landingpage: landingpage,
        remove: remove
    };
})();
