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

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

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


    // === Promotion rules

     $('#entry-promo-group').on('change', function (e) {
        $('.promo-group-wrapper').removeClass('show');
        $('.promo-group-' + $(this).val()).addClass('show');
        $('.promo-type-wrapper').removeClass('show');
        $('.promo-notification-wrapper').html(jsData.text_select_promo_rule);
    });
    $('#entry-promo-group').trigger('change');

    // Select promo rule
     $('.js-promo-rule-type').on('change checked', function (e) {
        var promoType = $(this).val(),
            promoTypeRule = $('#entry-promo-group').val() + '_' + promoType;

        $('.isl-promo-rule-alert').remove();
        if (jsData.promo_id && jsData.setting.item.rule_group + '_' + jsData.setting.item.rule_type != promoTypeRule) {
            $('.isl-promo-rule').before('<div class="isl-promo-rule-alert alert alert-warning fade in">' + jsData.text_promo_rule_alert +'</div>');
        }

        loadNotification(promoType, 0);
        loadRuleType(promoType, promoTypeRule);
    });

    // Toggle customer groups
    $('.isl-js-toggle').on('change', 'input[type=radio]', function (e) {
        var el = this;

        $(el).closest('.isl-js-toggle').find('.isl-toggle-target').hide();
        if ($(el).is(':checked')) {
            $(el).closest('.radio').find('.isl-toggle-target').slideDown('fast');
        }
    });
    setTimeout(function() {
        $('.isl-js-toggle').trigger('change');
    }, 100);

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

    // Override summernotes image manager
    $('[data-isl-summernote]').each(function() {
        applySummernote(this);
    });

    // Reset notification messages
    $('.btn-reset-notification').on('click', function(e) {
        loadNotification($('.js-promo-rule-type:checked').val(), 1);
    });
});

var progressPromoType = '';
function loadRuleType(promoType, promoRule) {
     progressPromoType = promoType;
    $('[data-toggle="tooltip"], .tooltip').tooltip('hide');
    $('.promo-rule-wrapper').html('').removeClass('show');

    setTimeout(function() {
        $('.promo-rule-wrapper.' + promoType).html('<i class="fa fa-spinner fa-spin"></i> ' + jsData.text_loading).addClass('show');
        setTimeout(function() {
            $('.promo-rule-wrapper.' + promoType).load('index.php?route=' + jsData.module.path + '/ruleForm&promo_rule=' + promoRule + '&' + jsData.url_token + '&promo_id=' + jsData.promo_id + '&_='+ new Date().getTime(), function() {
                if (progressPromoType == promoType) {
                    $('.promo-rule-wrapper.' + promoType).addClass('show');
                } else {
                    $('.promo-rule-wrapper').not('.' + progressPromoType).html('').removeClass('show');
                }
            });
        }, 200);
    }, 100);
}

function loadNotification(promoType, reset) {
     $('.save-changes').prop('disabled', true);
    $('.promo-notification-wrapper').html('<i class="fa fa-spinner fa-spin"></i> ' + jsData.text_loading);

    if (reset === undefined) {
        reset = 0;
    }

    setTimeout(function() {
        $('.promo-notification-wrapper').load('index.php?route=' + jsData.module.path + '/notificationEditor&promo_type=' + promoType + '&' + jsData.url_token + '&promo_id=' + jsData.promo_id + '&reset=' + reset + '&_='+ new Date().getTime(), function() {
            $('.save-changes').prop('disabled', false);
        });
    }, 200);
}

function applySummernote(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&' + jsData.url_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();
                }
            }
        });
}

$(document).on('isl.autocomplete', function(e)
{
    /**
     * 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'),
            route = param.type !== 'customer' ? 'catalog/' + param.type : 'customer/customer';

        $(el).autocomplete({
            source: function(request, response) {
                $.ajax({
                    url: 'index.php?route=' + route + '/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();
        });
    });
});

$(document).on('isl.summernote', function(e)
{
     $('[data-isl-summernote-ntf]').each(function() {
        applySummernote(this);
    });
});
