var html = document.querySelector('.no-js');
html.classList.remove('no-js');
html.classList.add('js');
document.getElementById('openMenu').addEventListener('click', function() {
    document.querySelector('body').classList.toggle('menu-open');
});
function readAndShowImage(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('.image-upload-img').attr('src', e.target.result);
        }                        
        reader.readAsDataURL(input.files[0]);
    }
}

$(".image-upload-input").change(function(){
    readAndShowImage(this);
});
$('.custom-file-input').on('change',function(){
    var fileName = $(this).val().split('\\').pop();
    $(this).next('.custom-file-label').addClass("selected").html(fileName);
});
$('.slider').slick();
$('.lightbox').on('click', function(){
    var e = this;
    $(this).next().addClass('active');
});

$('.lightbox-close').on('click', function(){
    var e = this;
    $(this).parent().removeClass('active');
});

$('.lightbox-target').on('click', function(){
    var e = this;
    $(this).removeClass('active');
});
$(function () {
    $('[data-toggle="tooltip"]').tooltip();
});
$(window).on('ajaxInvalidField', function(event, fieldElement, fieldName, errorMsg, isFirst) {
    $(fieldElement).closest('.form-group').addClass('has-error');
});

$(document).on('ajaxPromise', '[data-request]', function() {
    $(this).closest('form').find('.form-group.has-error').removeClass('has-error');
});
var inverseArray = [];

$(document).ready(function(){
    $('body').on("keyup", ".data-table-input", function() {
        var value = $(this).val().toLowerCase();
        $("#" + $(this).data('table-id') + " tr").filter(function() {
            if (!$(this).parent('thead').length) {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            }
        });
    });

    $('.sortable-header').append(' <span class="fa fa-sort sortable-icon text-muted"/>');

    $(document).on('DOMNodeInserted', function(e) {
        if ( $(e.target).hasClass('dataTable') ) {
            $(e.target).children('thead').children('tr').children('.sortable-header').append(' <span class="fa fa-sort sortable-icon text-muted"/>')
        }

        if ($(e.target).children().hasClass('dataTable')) {
            $(e.target).children('*').children('thead').children('tr').children('.sortable-header').append(' <span class="fa fa-sort sortable-icon text-muted"/>')
        }
    });

    $('body').on('click','.sortable-header', function () {

        var th = $(this),
            thIndex = th.index(),
            inverse;

        if (inverseArray[thIndex] !== undefined) {
            inverse = inverseArray[thIndex];
        } else {
            inverse = inverseArray[thIndex] = false;
        }

        $(this).parent('tr').children('.sortable-header').children('.sortable-icon').addClass('text-muted fa-sort').removeClass('fa-sort-down fa-sort-up');
        $(this).find('.sortable-icon').addClass(inverse ? 'fa-sort-up' : 'fa-sort-down').removeClass('text-muted');
        $(this).closest('table').find('td').filter(function() {

            return $(this).index() === thIndex;

        }).sortElements(function(a, b) {

            return $.text([a]).toLowerCase() > $.text([b]).toLowerCase()
                ? inverse ? -1 : 1
                : inverse ? 1 : -1;

        }, function() {

            // parentNode is the element we want to move
            return this.parentNode;

        });
        inverseArray[thIndex] = !inverseArray[thIndex] ;

    });

});
// Init for page load
$(document).ready(function () {
    initSelect2();
});

// Init for partial rendering
$(window).on('ajaxUpdateComplete', function () {
    initSelect2();
});

// One method to rule them all
function initSelect2() {
    $('.select2').select2({
        theme: 'bootstrap4',
        width: '100%'
    });

    // Display or hide other school input field based on selection
    $("#userRegisterSchool").on("change",function() {
        var val = $(this).find('option:selected').val();
        if(val == 'other') {
            $("#userRegisterSchoolOtherHolder").removeClass('d-none');
        } else {
            $("#userRegisterSchoolOtherHolder").addClass('d-none');
        }
    });

    // Display or hide phone input field based on accounttype selection
    $('input[type=radio][name=user_type]').on("change",function() {
        var val = $('input[name=user_type]:checked').val();
        if(val == '2') {
            $("#userRegisterPhoneHolder").removeClass('d-none');
        } else {
            $("#userRegisterPhoneHolder").addClass('d-none');
        }
    });

}

/**
 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode;
 *   })
 *
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){

    var sort = [].sort;

    return function(comparator, getSortable) {

        getSortable = getSortable || function(){return this;};

        var placements = this.map(function(){

            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,

                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );

            return function() {

                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }

                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);

            };

        });

        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });

    };

})();