$(document).ready(function() {
    $('body').addClass('isenselabs-module isl-limitedtimediscount');

    // Main navigation
    $('#mainTabs a:first').tab('show'); // Select first tab
    if (window.localStorage && window.localStorage['ltdCurrentTab']) {
        $('#mainTabs a[href="' + window.localStorage['ltdCurrentTab'] + '"]').tab('show');
    }
    $('#mainTabs a[data-toggle="tab"]').click(function() {
        if (window.localStorage) {
            window.localStorage['ltdCurrentTab'] = $(this).attr('href');
        }
    });

    $('.langTabs').each(function() {
        $(this).find('a:first').tab('show');
    });

    // Checkbox toggle hidden div
    $('[data-isl-toggle]').each(function() {
        var el    = this,
            param = $(el).data('isl-toggle');

        $($(el).closest('div')).on('change', el, function (e) {
            if ($(el).is(':checked')) {
                $(el).closest('div').find('.isl-toggle').slideDown('fast');
            } else {
                $(el).closest('div').find('.isl-toggle').hide('fast');
            }
        });
    });
    setTimeout(function() {
        $('[data-isl-toggle]').trigger('change');
    }, 100);

    // Date chooser
    $('.datepicker').datetimepicker({
        pickTime: false
    });
    $('.datepicker').on('focus', 'input', function(e) {
        $(this).parent().find('button').trigger('click');
    });

    // Minicolors
    $.minicolors.defaults = $.extend($.minicolors.defaults, {
      changeDelay: 200,
      letterCase: 'uppercase',
      theme:      'bootstrap'
    });
    $('input.minicolors').minicolors();

    // IIDE summernote
    $('[data-isl-summernote]').each(function() {
        applyLtdSummernote(this);
    });

    // IIDE Autocomplete
    // usage: data-isl-autocomplete='{"type":"product", "target":"unique_well_class_suffix", "name":"input_name"}'

    $('[data-isl-autocomplete]').each(function() {
        var el    = this,
            param = $(el).data('isl-autocomplete');

        $(el).autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: 'index.php?route=catalog/' + param.type + '/autocomplete&' + jsData.url_token + '&filter_name=' +  encodeURIComponent(request),
                    dataType: 'json',
                    success: function(json) {
                        response($.map(json, function(item) {
                            return {
                                label: item.name,
                                value: item[param.type + '_id']
                            };
                        }));
                    }
                });
            },
            select: function(item) {
                $(el).val('');
                $('.' + param.target + item.value).remove();
                $('.' + param.target).append('<div class="' + param.target + item.value + '"><i class="fa fa-minus-circle pointer"></i> ' + item.label + '<input type="hidden" name="' + param.name + '" value="' + item.value + '" /></div>');
            }
        });

        $('.' + param.target).on('click', '.fa-minus-circle', function() {
            $(this).parent().remove();
        });
    });

});

function applyLtdSummernote(el) {
    var param = $(el).data('isl-summernote');

    $(el).summernote({
        disableDragAndDrop: true,
        height: param !== undefined ? param : 200,
        emptyPara: '',
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'underline', 'italic']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['insert', ['table', 'link', 'image']],
            ['view', ['codeview', 'help']]
        ],
        buttons: {
            image: function() {
                var ui = $.summernote.ui;

                // create button
                var button = ui.button({
                    contents: '<i class="note-icon-picture" />',
                    tooltip: $.summernote.lang[$.summernote.options.lang].image.image,
                    click: function () {
                        $('#modal-image').remove();

                        $.ajax({
                            url: 'index.php?route=common/filemanager&token=' + getURLVar('token'),
                            dataType: 'html',
                            beforeSend: function() {
                                $('#button-image i').replaceWith('<i class="fa fa-circle-o-notch fa-spin"></i>');
                                $('#button-image').prop('disabled', true);
                            },
                            complete: function() {
                                $('#button-image i').replaceWith('<i class="fa fa-upload"></i>');
                                $('#button-image').prop('disabled', false);
                            },
                            success: function(html) {
                                $('body').append('<div id="modal-image" class="modal">' + html + '</div>');

                                $('#modal-image').modal('show');

                                $('#modal-image').delegate('a.thumbnail', 'click', function(e) {
                                    e.preventDefault();

                                    $(el).summernote('insertImage', $(this).attr('href'));

                                    $('#modal-image').modal('hide');
                                });
                            }
                        });
                    }
                });

                return button.render();
            }
        }
    });
}
