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

'use strict';

(function ($){

    $.fn.kdMediaPopup = 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 KDMediaPopup = {
            $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 KDMediaPopup.init();
    };

    $.fn.kdValidationVideo = function (opts) {
        var $self = $(this),
            defaults = {

            },
            options = $.extend(defaults, $self.data(), opts);

        var PiValidation = {
            $el : $self,
            options: options,
            $notice: null,
            $showImage: null,
            init: function () {
                var _this = this;

                _this.createHTML();
                _this.events();

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

                // Append element show notice
                if (!_this.$el.next('.kd-show-notice').length) {
                    _this.$el.after('<ul class="kd-show-notice"><li class="kd-notice-button kd-url-pass"><i class="dashicons dashicons-yes"></i></li><li class="kd-notice-button kd-url-not-pass"><i class="dashicons dashicons-no"></i></li></ul>')
                }
                _this.$notice = _this.$el.next('.kd-show-notice');

                // Append element show image preview
                if (!_this.$notice.next('.kd-show-image').length) {
                    _this.$notice.after('<div class="kd-show-image"><img src="" alt=""/></div>');
                }
                _this.$imageShow = _this.$notice.next('.kd-show-image');
            },
            events : function () {
                var _this = this;

                _this.$el.change( function () {
                    var url = $(this).val(), id = '', type = '';

                    if (url.indexOf('youtube') !=-1) {
                        var url = url.match('(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})');
                        if (url && url[1]) {
                            id = url[1];
                            type = 'youtube';
                        }
                    }
                    else if (url.indexOf('vimeo') != -1) {
                        url = url.match('(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*');
                        if (url && url[5]) {
                            id = url[5];
                            type = 'vimeo';
                        }
                    }
                    else {
                        type = '';
                    }

                    $('.kd-notice-button',_this.$notice).removeClass('active');
                    _this.$imageShow.removeClass('kd-ajax-loading').hide();
                    if (type != '') {
                        $('.kd-url-pass',_this.$notice).addClass('active');
                        var src = '';
                        if (type == 'youtube') {
                            src = 'http://img.youtube.com/vi/' + id +'/0.jpg';
                            $('img', _this.$imageShow).attr('src', src);
                            _this.$imageShow.show();
                        }
                        else if (type == 'vimeo'){
                            _this.$imageShow.addClass('kd-ajax-loading');
                            $.ajax({
                                type:'GET',
                                url: 'http://vimeo.com/api/v2/video/' + id + '.json',
                                jsonp: 'callback',
                                dataType: 'jsonp',
                                success: function(data){
                                    if (_this.$imageShow.hasClass('kd-ajax-loading')) {
                                        var thumbnail_src = data[0].thumbnail_large;
                                        _this.$imageShow.removeClass('kd-ajax-loading');
                                        $('img', _this.$imageShow).attr('src', thumbnail_src);
                                    }
                                    _this.$imageShow.show();
                                }
                            });
                        }
                    }
                    else {
                        if ($(this).val() != '') {
                            $('.kd-url-not-pass',_this.$notice).addClass('active');
                        }
                    }
                });
            }
        }
        return PiValidation.init();
    };

    $.fn.kdFormatUI = function (opts) {
        var defaults = {
                init: function () {},
                active: function () {}
            },
            options = $.extend(defaults, opts),
            $self = $(this);

        var KDFormatUI = {
            $el: $self,
            $controls: $('#kd-controls-post-format', $self),
            $handles : $('#kd-handle-post-format', $self),
            media: null,
            options: options,
            init: function () {
                var _this = this;

                _this.$el.show(200);
                _this.setMedia();
                _this.events();

                var format = _this.$controls.data('format');

                if (format == '') {
                    format = 'standard';
                }
                $('li[data-format="'+ format +'"]', _this.$controls).trigger('click');
            },

            events: function () {
                var _this = this;

                $('li', _this.$controls).click( function (event) {
                    event.preventDefault();
                    var href = $('a', this).attr('href'),
                        $handle = $(href),
                        format = $(this).data('format');

                    if ($handle.length) {
                        $handle.trigger('click');
                    }
                    $('li', _this.$controls).removeClass('active');
                    $(this).addClass('active');
                    // Show handle of post format
                    _this.$handles.children().hide();
                    var $format = $('#kd-post-format-' + format);
                    $format.show();

                    /* Focus element */
                    var $focus = '';
                    switch (format) {
                        case 'video':
                            $focus = $('#kd-video-field-url', $format);
                            break;
                        case 'audio':
                            $focus = $('#kd-audio-field-url', $format);
                            break;
                        case 'quote':
                            $focus = $('#kd-quote-field-content', $format);
                            break;
                    }
                    
                    if ($focus.length) {
                        $focus.focus();
                        var thisVal = $focus.val();
                        $focus.val('').val(thisVal)
                    }

                    /* Trigger Click Format Of Post */
                    var idFormat = '#post-format-' + format;
                    if (format == 'standard') {
                        idFormat = '#post-format-0';
                    }
                    $(idFormat, '#formatdiv').trigger('click');
                });

                /* Gallery */
                var $gallery = $('#kd-post-format-gallery'),
                    $typeGallery = $('.kd-type-gallery', $gallery);

                $typeGallery.change( function () {
                    var val = $(this).val(),
                        $select = $(this).prev();

                    $select.val(val);
                }).trigger('change');
                $typeGallery.prev().change( function () {
                    $typeGallery.val($(this).val());
                });

                /* Video */
                var $videoUrl = $('#kd-video-field-url');
                $videoUrl.kdValidationVideo();
                if ($videoUrl.val() != '') {
                    $videoUrl.trigger('change');
                }
            },
            setMedia: function () {
                var _this = this;
                $('.kd-button-media', _this.$handles).each( function() {
                    $(this).kdMediaPopup();
                });
            }
        };
        return KDFormatUI.init();
    };

    $(document).ready( function () {
        $('#kd-handle-post-format').kdFormatUI();
    });
})(jQuery);
