require(['jquery', 'domReady', 'cla_select2'], function (jQuery, domReady) {

    // This function will also be used by skill_endorsements_xajax_server.php to bind the show_endorsers
    // to the content generated via the Ajax call.
    bindShowEndorsers = function() {
        jQuery('.js-profile-skill-data').on('click', show_endorsers);
    };

    getUrlVar = function(key){
        var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
        return result && result[1] || "";
    };

    check_char_limit = function(id, max_length) {
        if(id.indexOf('#') != 0) { id = "#" + id; }
        // Shows a red border to the input box if the max char length is reached.
        jQuery(id).toggleClass('message-too-long', (jQuery(id).val().length >= max_length));
    };

    show_endorsers = function() {
        var skill = jQuery(this).data();
        xajax_get_endorsers(skill.endorsee_id, skill.skill_id);

        // Allows the content of the endorsements modal to load before the modal display
        setTimeout(function(){
            jQuery('#Endorsers').modal('show');
        }, 1200);
    };

    edit_skill = function(skill_id) {
        var curr_skill_name = jQuery('a[data-skill-id="' + skill_id + '"]').text();
        var edit_panel = jQuery('#EditSkill');
        jQuery('#edit_skill_name').val(curr_skill_name);
        jQuery('#edit_skill_id').val(skill_id);
        jQuery(edit_panel).modal().show();
    };

    delete_skill = function(skill_id) {
        if (confirm(lmsg("common.areyousure"))) {
            xajax_delete_skill(skill_id);
        }
        return false;
    };

    remove_skill_row = function(data_id) {
        jQuery("#endorsements_common_list_table").find("a[data-skill-id='" + data_id + "']").closest('tr').remove();
    };

    /**
     * Removes endorsements to a particular skill from the user's own profile.
     * @param endorsee_id - Id of the user from which the endorsement should be removed.
     * @param skill_id - Id of the skill related to the endorsement.
     * @returns {boolean}
     */
    remove_endorsement_from_profile = function(endorsee_id, skill_id) {
        if (!confirm(lmsg('endorsements.general.remove_endorsement_alert')) == true) {
            return false;
        }

        xajax_remove_endorsement_from_profile(endorsee_id, skill_id);
        jQuery('#Endorsers').modal('hide');
    };


    domReady(function(){

        bindShowEndorsers();

        jQuery("#add_skills").select2({
            placeholder: lmsg('endorsements.general.add_skill'),
            maximumInputLength: 50
        });

        jQuery("#search_skills").select2({
            placeholder: lmsg('endorsements.general.search_endorsements') + '...',
            width: '100%'
        });

        jQuery("#select2_skills").select2({
            allowNewValues: true,
            width: '260px',
			maximumInputLength: 50
        });

        // Pre-loads the search box with the previous selected skills.
        if (jQuery('#current-search-filter').length>0 && jQuery('#current-search-filter').val().length>0) {
            var filter = (jQuery.parseJSON(jQuery('#current-search-filter').val()));
            for (var i= 0; i<filter.length; i++)
            {
                $('#search_skills option').each(function(){
                    if ($(this).val() == filter[i].id) {
                        $(this).attr('selected', '');
                    }
                });
            }
            jQuery('#search_skills').change();
        }

        jQuery("#endorse_skill_names").select2({
            separator: "|",
            tokenSeparators: ['|'],
            maximumInputLength: 50,
            createSearchChoice:function(term, data) { if (jQuery(data).filter(function() {

                    // Forces the new skills to be created to have a max length of 50 characters
                    if (data.length == 1 && data[0].text == term) {
                        term = (term.substring(0, 50));
                        data[0].id = term;
                        data[0].text = term;
                    }

                    return this.text.localeCompare(term)===0; }).length===0) {
                return data.length > 0 ? {id:term, text:term} : '';
            }
            },
            placeholder: lmsg('endorsements.general.endorse_user'),
            multiple: true,
            ajax: {
                url: "/intranet/people/skill_endorsements_picker_server.php",
                dataType: 'json',
                quietMillis: 250,
                data: function (params) {

                    return {
                        id: getUrlVar("id"),
                        page: params.page,
                        is_endorsements: jQuery('#expertise_selector').length ? false : true, // Skills or endorsements
                        q: params.term
                    };
                },
                processResults: function (data) {
                    return { results: data };
                },
                cache: true
            },
            width: "100%",
            formatNoMatches: function () { return lmsg('common.select2.no_matches_found') ; }
        });

        jQuery('#select2_skills').on("change", function(e) {
            var select2_data = jQuery('#select2_skills').select2('data');
            jQuery( "#merge_skill_btn" ).toggleClass( 'disabled', (select2_data.length < 2) );
        });


        jQuery(".js-remove-skill").click(function(e) {
            e.preventDefault();
            jQuery(this).closest('.js-skill-selector').remove();
            jQuery(".tooltip").hide();
        });

        jQuery('#mergeSkill').on('show.bs.modal', function (e) {
            var select2_data = jQuery('#select2_skills').select2('data');

            if (select2_data.length > 1) {
                var el = jQuery('#skill2merge');
                // Clears the content of the modal popup before appending the skills entered by the user.
                el.empty();

                // Appends a text field to allow merging skills into a new one.
                el.append('<div class="form-group d-flex"><div class="form-check d-flex align-items-center"><input class="form-check-input " name="skill_id" type="radio" id="merge_to_new" value="0" onclick="$(&quot;[name=skill_name]&quot;,$(this).parent()).focus()" /> </div><input type="text" class="form-control ml-2" name="skill_name" onclick="$(&quot;#merge_to_new&quot;).click();" /></div>');

                for (var idx=0; idx < select2_data.length; idx++) {
                    var id = select2_data[idx]['id'];
                    var name = select2_data[idx]['text'];

                    // Appends the skills entered by the user as options in the modal popup.
                    el.append('<div class="form-check"><input class="form-check-input" name="skill_id" type="radio" value="' + id + '" /> <label class="form-check-label">' + $('<div></div>').text(name).html() + '</label></div>');
                }

                // Selects the first option.
                jQuery("input:radio[name=skill_id]:first").attr('checked', true);

            }
        });

        jQuery(".btn").click(function(e) {
            if (jQuery(this).hasClass('disabled')) {
                e.preventDefault();
                return false;
            }
        });

        jQuery("#s2id_endorse_skill_names :input").focusout(function() { jQuery(this).removeClass('select2-active'); });

        jQuery('#search-skill-action').click(function(e) {
            var select2_data = jQuery('#search_skills').select2('data');
            if (select2_data.length <= 0) {
                e.preventDefault();
                alert(lmsg('endorsements.skill.empty_search'));
            }
        });

    });
});
