/**
 * Created by Ong Chinh on 7/20/2016.
 */

'use strict';
(function ($) {
    $.fn.kdMedia = function (opts) {
        var $self = $(this),
            defaults = {
                parent: '',
                title: 'My Photos',
                button: 'Sellect',
                multiple: true,
                imageSize: 'thumbnail',
                init: function(){},
                select: function() {}
            },
            options = $.extend(defaults, $self.data(), opts);

        var $insert = '';
        var kdMedia = {
            $el: $self,
            options: options,
            $button: $('.kd-button', $self),
            $input: $('.kd-media-value', $self),
            template: '<li class="kd-image"><img src="" alt=""/><div class="kd-control-wrap"><i class="kd-edit dashicons dashicons-edit"></i><i class="kd-close dashicons dashicons-no-alt"></i></div></li>',
            $showImage: '',
            media: null,
            init: function () {
                var _this = this;
                _this.createHTML();
                _this.setMedia();
                _this.events();
            },
            createHTML: function () {
                var _this = this, $parent;

                if (_this.options.parent == '') {
                    $parent = _this.$el;
                }
                else {
                    if ($(_this.options.parent).length) {
                        $parent = $(_this.options.parent)
                    }
                    else {
                        $parent = _this.$el;
                    }
                }
                if (!$('ul.list-kd-image-media', $parent).length) {
                    $parent.prepend('<ul class="list-kd-image-media"></ul>');
                }
                _this.$showImage = $('.list-kd-image-media', $parent);
            },
            events: function () {
                var _this = this;

                _this.$input.change( function () {
                    var listID = [];
                    _this.$showImage.children('.kd-image').each( function () {
                        if ($(this).data('id')) {
                            listID.push($(this).data('id'));
                        }
                    });
                    listID = listID.join(',');
                    _this.$input.val(listID);
                });
                if (_this.options.multiple) {
                    _this.$showImage.sortable({
                        //placeholder: 'kd-sort-placeholder',
                        revert: 200,
                        containment: "parent",
                        update: function () {
                            _this.$input.trigger('change');
                        }
                    });
                }

                _this.$button.click( function (event) {
                    event.preventDefault();
                    $insert = _this.$showImage;
                    _this.media.open();

                });

                _this.$showImage.on('click', '.kd-edit', function (event) {
                    event.preventDefault();
                    $insert = $(this).closest('.kd-image');
                    _this.media.open();
                });

                _this.$showImage.on('click', '.kd-close', function (event) {
                    event.stopPropagation();
                    event.preventDefault();
                    $(this).closest('li').remove();
                    _this.$input.trigger('change', {action: 'remove'});
                });
                _this.media.on('select', function () {
                    var selection  = _this.media.state().get('selection'),
                        attachments = [];
                    selection.each (function (attachment, id) {
                        attachment = attachment.toJSON();
                        var $image = $(_this.template).attr('data-id', attachment.id),
                            url = attachment.sizes && attachment.sizes[_this.options.imageSize] && attachment.sizes[_this.options.imageSize].url ? attachment.sizes[_this.options.imageSize].url: attachment.url;
                        attachments.push(attachment);
                        $('img', $image).attr('src', url);
                        // Select in case multiple set is true
                        if (_this.options.multiple) {

                            // Add images
                            if ($insert.hasClass('list-kd-image-media'))
                            {
                                $insert.append($image);
                            }
                            // Change image
                            else {
                                if (id == 0) {
                                    $insert.attr('data-id', attachment.id);
                                    $('img', $insert).attr('src', url);
                                }
                                else {
                                    $insert.after($image);
                                }
                            }
                        }
                        // Select in case multiple set is false
                        else {
                            _this.$showImage.empty().append($image);
                        }
                    });
                    _this.$input.trigger('change', {attachments : attachments});
                });

            },
            setMedia: function () {
                var _this = this;

                _this.media = wp.media({
                    title: options.title,
                    button: {
                        text: options.button
                    },
                    multiple: options.multiple
                });
            }
        };

        return kdMedia.init();
    };

    $.fn.kdMailChimp = function () {
        var $self = $(this),
            $widget = $(this).closest('.widget');

        if (!$widget.length) {
            $widget = $(this).closest('.editwidget');
        }

        $self.on('click', function (event) {

            event.preventDefault();

            var apiKey = $('.widefat', $widget).eq(0).val();

            if (apiKey != '') {
                $self.addClass('kd-ajax-loading');
                $.ajax({
                    url: ajaxurl,
                    type: "POST",
                    dataType: 'html',
                    data: {action: 'kd_get_list_mailchimp', api_key: apiKey},
                    success: function(response) {
                        $('.kd-mailchimp-list p', $widget).empty().append(response);

                        var listID = $('.widefat[type=hidden]', $widget).val();

                        $('.kd-mailchimp-list select', $widget).val(listID);
                    },
                    complete: function () {
                        $self.removeClass('kd-ajax-loading');
                    }
                });
            }
            else {
                alert('API key not empty, please try again');
            }
        });

        $widget.on('change', '.kd-mailchimp-list select', function () {
            var selected = $(this).val();
            $('.widefat[type="hidden"]', $widget).val(selected);
        });

        $('.widefat[type="hidden"]', $widget).on('change', function () {
            var listID = $(this).val();
            if (listID != '') {
                $('.kd-mailchimp-list select', $widget).val(listID);
            }
        }).trigger('change');

    };

    $(document).on('ready', function(){
        $('.widget', '.widget-liquid-right').each( function () {
            $(this).kdWidget();
        });
    });
    $(document).on('widget-updated widget-added', function(event, $widget){
        $widget.kdWidget();
    });
    $.fn.kdWidget = function() {
        var $self = $(this);

        $self.unbind('kdWidgetInit').on('kdWidgetInit', function () {
            $('.kd-upload', $self).each( function () {
                var $this = $(this);
                $this.kdMedia();

                $this.on('change', '.kd-media-value', function () {
                    var src = [];
                    $('img', $this).each( function () {
                        if ($(this).attr('src') != '') {
                            src.push($(this).attr('src'));
                        }
                    });
                    src = src.join(',');
                    $('.kd-media-input', $this).val(src);

                });
            });
            $('.kd-colorpicker', $self).each( function () {
                $(this).wpColorPicker();
            });
        }).trigger('kdWidgetInit');

        $('.kd-images-description', $self).each( function() {
            $(this).magnificPopup({
                delegate: 'a', // child items selector, by clicking on it popup will open
                type: 'image',
                gallery: {
                    enabled: true
                }
            });
        });

        if ($('.kd-getlist-mailchimp', $self).length) {
            $('.kd-getlist-mailchimp', $self).kdMailChimp();
        }
    }
})(jQuery);