jQuery(document).ready(function () {
    custom_switch_merchants();
    setSortableList();
});

function custom_switch_merchants() {
    $('#switch-merchant select').change(function () {
        $('#switch-merchant form').submit();
    });
}

function setSortableList() {

    $('.lc-sortable tbody').sortable({
        placeholder: "ui-state-highlight"
    });

    $('.lc-sortable tbody').on("sortupdate", function (event, ui) {

        prototype = $('#form_entities').data('prototype');

        $('.lc-sortable tr.lc-draggable').each(function (index, li) {
            // instead be a number based on how many items we have
            var newForm = prototype.replace(/__name__/g, index);

            // Replace '__name__' in the prototype's HTML to
            //$(li).find('div:last-child').remove();

            $(li).append(newForm);
            $(li).find('#form_entities_' + index + '_id').val($(li).data('id'));
            if ($('.lc-sortable').data('parent-position') !=='') val = $('.lc-sortable').data('parent-position') + '_' + index
            else val = index;

            log($(li).find('#form_entities_' + index + '_position'));

            $(li).find('#form_entities_' + index + '_position').val(val);
        });

    });

}