(function ($) {

    
    var smiles = [
        ':bowtie:',
        ':smile:',
        ':laughing:',
        ':blush:',
        ':smiley:',
        ':relaxed:',
        ':smirk:',
        ':heart_eyes:',
        ':kissing_heart:',
        ':kissing_closed_eyes:',
        ':flushed:',
        ':relieved:',
        ':satisfied:',
        ':grin:',
        ':wink:',
        ':stuck_out_tongue_winking_eye:',
        ':stuck_out_tongue_closed_eyes:',
        ':grinning:',
        ':kissing:',
        ':kissing_smiling_eyes:',
        ':stuck_out_tongue:',
        ':sleeping:',
        ':worried:',
        ':frowning:',
        ':anguished:',
        ':open_mouth:',
        ':grimacing:',
        ':confused:',
        ':hushed:',
        ':expressionless:',
        ':unamused:',
        ':sweat_smile:',
        ':sweat:',
        ':disappointed_relieved:',
        ':weary:',
        ':pensive:',
        ':disappointed:',
        ':confounded:',
        ':fearful:',
        ':cold_sweat:',
        ':persevere:',
        ':cry:',
        ':sob:',
        ':joy:',
        ':astonished:',
        ':scream:',
        ':neckbeard:',
        ':tired_face:',
        ':angry:',
        ':rage:',
        ':triumph:',
        ':sleepy:',
        ':yum:',
        ':mask:',
        ':sunglasses:',
        ':dizzy_face:',
        ':imp:',
        ':smiling_imp:',
        ':neutral_face:',
        ':no_mouth:',
        ':innocent:',
        ':alien:',
        ':yellow_heart:',
        ':blue_heart:',
        ':purple_heart:',
        ':heart:',
        ':green_heart:',
        ':broken_heart:',
        ':heartbeat:',
        ':heartpulse:',
        ':two_hearts:',
        ':revolving_hearts:',
        ':cupid:',
        ':sparkling_heart:',
        ':sparkles:',
        ':star:',
        ':star2:',
        ':dizzy:',
        ':boom:',
        ':collision:',
        ':anger:',
        ':exclamation:',
        ':question:',
        ':grey_exclamation:',
        ':grey_question:',
        ':zzz:',
        ':dash:',
        ':sweat_drops:',
        ':notes:',
        ':musical_note:',
        ':fire:',
        ':shit:',
        ':+1:',
        ':thumbsup:',
        ':-1:',
        ':thumbsdown:',
        ':ok_hand:',
        ':punch:',
        ':facepunch:',
        ':fist:',
        ':v:',
        ':wave:',
        ':hand:',
        ':raised_hand:',
        ':open_hands:',
        ':point_up:',
        ':point_down:',
        ':point_left:',
        ':point_right:',
        ':raised_hands:',
        ':pray:',
        ':point_up_2:',
        ':clap:',
        ':muscle:',
        ':metal:',
        ':fu:',
        ':runner:',
        ':running:',
        ':couple:',
        ':family:',
        ':dancer:',
        ':dancers:',
        ':ok_woman:',
        ':no_good:',
        ':information_desk_person:',
        ':raising_hand:',
        ':bride_with_veil:',
        ':person_with_pouting_face:',
        ':person_frowning:',
        ':bow:',
        ':couplekiss:',
        ':couple_with_heart:',
        ':massage:',
        ':haircut:',
        ':nail_care:',
        ':boy:',
        ':girl:',
        ':woman:',
        ':man:',
        ':baby:',
        ':older_woman:',
        ':older_man:',
        ':person_with_blond_hair:',
        ':man_with_gua_pi_mao:',
        ':man_with_turban:',
        ':construction_worker:',
        ':cop:',
        ':angel:',
        ':princess:',
        ':smiley_cat:',
        ':smile_cat:',
        ':heart_eyes_cat:',
        ':kissing_cat:',
        ':smirk_cat:',
        ':scream_cat:',
        ':crying_cat_face:',
        ':joy_cat:',
        ':pouting_cat:',
        ':japanese_ogre:',
        ':japanese_goblin:',
        ':see_no_evil:',
        ':hear_no_evil:',
        ':speak_no_evil:',
        ':guardsman:',
        ':skull:',
        ':feet:',
        ':lips:',
        ':kiss:',
        ':droplet:',
        ':ear:',
        ':eyes:',
        ':nose:',
        ':tongue:',
        ':love_letter:',
        ':bust_in_silhouette:',
        ':busts_in_silhouette:',
        ':speech_balloon:',
        ':thought_balloon:',
        ':feelsgood:',
        ':finnadie:',
        ':goberserk:',
        ':godmode:',
        ':hurtrealbad:',
        ':rage1:',
        ':rage2:',
        ':rage3:',
        ':rage4:',
        ':suspect:',
        ':trollface:'
    ];


    //Global variables to handle last used emojies and stickers in all forms instances
    var lastEmojies = [];
    var lastStickers = [];


    var $sendSettingForm = $('<div />')
        .append($('<p />')
            .text('Настройка отправки')
        )
        .append($('<div />')
            .append($('<label />')
                .append($('<input />')
                    .attr('type', 'radio')
                    .addClass('send-def-opt')
                )
                .append($('<strong />')
                    .text('Enter')
                )
                .append('&mdash; отправка сообщения<br>')
                .append($('<strong />')
                    .text('Shift + Enter')
                )
                .append('&mdash; перенос строки')
            )
            .addClass('radio')
        )
        .append($('<div />')
            .append($('<label />')
                .append($('<input />')
                    .attr('type', 'radio')
                    .addClass('send-alt-opt')
                )
                .append($('<strong />')
                    .text('Ctrl + Enter')
                )
                .append('&mdash; отправка сообщения<br>')
                .append($('<strong />')
                    .text('Enter')
                )
                .append('&mdash; перенос строки')
            )
            .addClass('radio')
        )
        .addClass('send-settings')


    function pasteHtmlAtCaret(html) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();

                // Range.createContextualFragment() would be useful here but is
                // only relatively recently standardized and is not supported in
                // some browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerHTML = html;
                var frag = document.createDocumentFragment(),
                    node, lastNode;
                while ((node = el.firstChild)) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);

                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    range.collapse(true);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.type != "Control") {
            // IE < 9
            document.selection.createRange().pasteHTML(html);
        }
    }

    function placeCaretAtEnd(el) {
        el.focus();
        if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(false);
            textRange.select();
        }
    }



    /*
     Function that returns attachment item
     url - link to attachment image
     index - file index
     fileName - attachment filename
     */
    function makeAttachmentItem(url, index, fileName) {

        var $item = $('<div class="limg-preview" data-id="' + index + '" />').attr('style', 'background: url(' + url + ')').append(
            $('<div class="limg-preview-inner" />').append('<div class="img-progress" data-img-id="' + index + '" />').append('<i class="remove-prw fa fa-times" aria-hidden="true" data-file-id="' + index + '"></i>').append($('<span />').text(fileName)));

        return $item;

    }



    function makeStickersTabItem(elementName, iconLink, additionalClass) {

        var $tabElement = $('<li />')
            .append($('<a />')
                .append($('<img />')
                    .attr('src', iconLink)
                )
                .attr('href', '#' + elementName)
                .attr('aria-controls', elementName)
                .attr('role', 'tab')
                .attr('data-toggle', "tab")
            )
            .attr('role', 'presentation')
            .addClass(additionalClass)

        return $tabElement;
    }

    var methods = {
        init: function (options) {

            var defaults = {
                startText: '',
                placeholderText: 'Пишите здесь',
                allowEdit: true,
                senderAvatarURL: '',
                prefixAttachment: 'comments',
                sendSettingHideDelay: 500,
                sendSettingShowDelay: 1500,
                emojiListShowDelay: 500, //
                emojiListHideDelay: 500,
                availableStickers: [],
                showCancelButton: false,
                showSendSettings: false,
                showPremiumCheckbox: false
            };

            //copy defualt options for non-setted parameters
            options = $.extend(defaults, options);


            var showEmojiList = false;
            var showSendSettings = false;


            return this.each(function () {

                var self = $(this);

                var formTimestamp = (new Date()).getTime();


                var $stickers = $();
                var $stickersTabs = $();


                var $lastStickersItems = $();

                for (var i = 0; i < lastStickers.length; i++) {

                    $lastStickersItems = $lastStickersItems.add($('<div />')
                        .append($('<div />')
                            .attr('style', 'background: url(/icons/stickers/' + lastStickers[i].group + '/' + lastStickers[i].sticker + '.png)')
                            .attr('data-sticker-group',lastStickers[i].group)
                            .attr('data-sticker', lastStickers[i].sticker)
                            .addClass('sticker')
                        )
                        .addClass('stickers-wrap__item'));
                }

                $stickers = $stickers
                    .add($('<div />')
                        .append($('<div />')
                            .append(smiles.join(' '))
                            .addClass('emoji-wrap')
                        )
                        .attr('role', 'tabpanel')
                        .attr('id', 'emoji-' + formTimestamp)
                        .addClass('tab-pane')
                        .addClass('fade')
                        .addClass('in')
                        .addClass('active')
                    )
                    .add($('<div />')
                        .append($('<div />')
                            .append($lastStickersItems)
                            .addClass('stickers-wrap')
                            .attr('data-sticker-group','last')
                        )
                        .attr('role', 'tabpanel')
                        .attr('id', 'last-' + formTimestamp)
                        .addClass('tab-pane')
                        .addClass('fade')
                    )




                $stickersTabs = $stickersTabs.add(makeStickersTabItem('emoji-' + formTimestamp, 'https://cont.ws/messages/images/icon__smiles.png', 'active'));
                $stickersTabs = $stickersTabs.add(makeStickersTabItem('last-' + formTimestamp, 'https://cont.ws/messages/images/icon__last_stickers.png'));

                for (var stickerGroup in options.availableStickers) {

                    $stickersTabs = $stickersTabs.add(makeStickersTabItem('sticker-group-' + stickerGroup + '-' + formTimestamp, '/icons/stickers/' + stickerGroup + '/64x64.png'));


                    var $stickerList = $('<div />')
                        .append($('<div />')
                            .addClass('stickers-wrap')
                            .attr('data-sticker-group',stickerGroup)
                        )
                        .attr('role', 'tabpanel')
                        .attr('id', 'sticker-group-' + stickerGroup + '-' + formTimestamp)
                        .addClass('tab-pane')
                        .addClass('fade');

                    for (var stickerID in options.availableStickers[stickerGroup]) {

                        $stickerList.find('.stickers-wrap')
                            .append($('<div />')
                                .append($('<div />')
                                    .attr('style', 'background: url(/icons/stickers/' + stickerGroup + '/' + options.availableStickers[stickerGroup][stickerID] + '.png)')
                                    .attr('data-sticker-group', stickerGroup)
                                    .attr('data-sticker', options.availableStickers[stickerGroup][stickerID])
                                    .addClass('sticker')
                                )
                                .addClass('stickers-wrap__item')
                            )


                    }

                    $stickers = $stickers.add($stickerList);
                }

                var $imageLoadContainer = $('<div />').addClass('images-load-container');

                var $avatarArea = $('<div />')
                    .append($('<figure />')
                        .append($('<img />')
                            .attr('src', options.senderAvatarURL)
                        )
                    )
                    .addClass('media-left')
                    .addClass('input_form_send_ava')

                var $placeHolderElement = $('<div />')
                    .text(options.placeholderText)
                    .addClass('text-muted')
                    .addClass('input_form__placeholder');

                var $textArea = $('<div />')
                    .addClass('form-control')
                    .addClass('input_form__textarea')
                    .attr('contentEditable', options.allowEdit)
                    .html(options.startText)

                var $smilesButton = $('<li />')
                    .append($('<a />')
                        .append($('<i />')
                            .addClass('fa')
                            .addClass('fa-fw')
                            .addClass('fa-smile-o')
                        )
                        .addClass('input_form-show-emoji')
                        .attr('href', '#')
                    )


                $(this)
                    .append($('<div />')
                        .append($imageLoadContainer)
                        .append($('<div></div>')
                            .append($avatarArea)
                            .append($('<div></div>')
                                .append($('<div />')
                                    .append($('<div />')
                                        .append($stickers)
                                        .addClass('tab-content')
                                    )
                                    .append($('<ul />')
                                        .append($stickersTabs)
                                        .append('<div class = "clearfix"></div>')
                                        .addClass('nav')
                                        .addClass('nav-pills')
                                    )
                                    .addClass('input-form__smiles')
                                )
                                .append($('<form />')
                                    .append($('<div></div>')
                                        .append($textArea)
                                        .append($placeHolderElement)
                                        .append($('<ul></ul>')
                                            .append($smilesButton)
                                            .append($('<li></li>')
                                                .append($('<label></label>')
                                                    .append($('<i></i>')
                                                        .addClass('fa')
                                                        .addClass('fa-fw')
                                                        .addClass('fa-camera')
                                                    )
                                                    .addClass('attach-image')
                                                    .attr('for', 'hidden-image-input-' + formTimestamp)
                                                )
                                                .append($('<input />')
                                                    .attr('id', 'hidden-image-input-' + formTimestamp)
                                                    .addClass('hidden-image-input')
                                                    .attr('type', 'file')
                                                    .attr('accept', 'image/jpeg,image/png')
                                                    .attr('name', 'mimages')
                                                    .prop('multiple', true)
                                                )
                                            )
                                            .addClass('input_form__icons')
                                        )
                                        .append($('<div />')
                                            .addClass('alert')
                                            .addClass('alert-danger')
                                            .css('display', 'none')
                                        )
                                        .append($('<div />')
                                            .append($('<div />')
                                                .append($('<ul />')
                                                    .append($('<li />')
                                                        .append($('<button />')
                                                            .append('Отправить')
                                                            .append($('<img />')
                                                                .addClass('input_form-preloader')
                                                                .attr('src', '/images/cont-preloader.svg')
                                                                .css('display', 'none')
                                                            )
                                                            .attr('type', 'button')
                                                            .addClass('btn')
                                                            .addClass('btn-primary')
                                                            .addClass('btn-sm')
                                                            .addClass('input_form-send-button')
                                                        )
                                                    )
                                                    .append(options.showPremiumCheckbox ?  
                                                            $('<li class="premium-thread-checkbox"><span>Премиум ветка</span><div class="round-checkbox"><input type="checkbox" id="premium_thread_checkbox_' + formTimestamp + '"><label for="premium_thread_checkbox_' + formTimestamp  + '"></label></div></li>') : $())
                                                    .append(options.showCancelButton ?
                                                        $('<li />').append($('<button />')
                                                            .text('Отмена')
                                                            .addClass('btn')
                                                            .addClass('btn-default')
                                                            .addClass('btn-sm')
                                                            .attr('type', 'button')
                                                            .addClass('input_form-cancel-button')) : $()
                                                    )
                                                    .addClass('list-inline')
                                                    .addClass('input_form-buttons')
                                                )
                                                .append(options.showSendSettings ? $sendSettingForm.clone() : $())
                                                .addClass('media-left')
                                            )
                                            .append($('<div />')
                                                .addClass('media-middle')
                                                .addClass('media-body')
                                                .addClass('emoji-last')
                                                .css('width', 'auto')
                                            )
                                            .addClass('media')
                                        )
                                        .addClass('form-group')
                                    )
                                )
                                .addClass('media-body')
                            )
                            .addClass('media')
                        )
                        .addClass('input_form')
                    );

                if (options.startText) {

                    self.find('.input_form__placeholder').hide();
                    placeCaretAtEnd($(this).find('.input_form__textarea')[0]);
                }

                if (!options.allowEdit) {
                    self.find('.input_form-show-emoji').hide();
                    self.find('.attach-image').hide();
                    self.find('.emoji-last').hide();
                }

                lastEmojies.forEach(function (emoji) {

                    self.find('.emoji-last').append(emoji);

                });

                $(this).find('.input_form__textarea').blur(function () {

                    if ($(this).html() == '')
                        $(this).next('.input_form__placeholder').show();
                });

                $(this).find('.input_form__textarea').keydown(function () {

                    $(this).next('.input_form__placeholder').hide();

                    var atBottom = false;

                    if ($(this).scrollTop() + $(this).innerHeight() == $(this).prop('scrollHeight')) atBottom = true;

                    if (atBottom) $(this).scrollTop($(this).prop('scrollHeight'));

                });

                $(this).find('.input_form-show-emoji').mouseenter(function () {
                    showEmojiList = true;
                    self.find('.input-form__smiles').fadeIn('fast');
                });

                $(this).find('.input_form-show-emoji').mouseleave(function () {

                    showEmojiList = false;

                    setTimeout(function () {
                        if (!showEmojiList) {
                            self.find('.input-form__smiles').fadeOut('fast');
                        }
                    }, 500);

                });

                $(this).find('.input-form__smiles').mouseenter(function () {
                    showEmojiList = true;
                    $(this).fadeIn('fast');
                });

                $(this).find('.input-form__smiles').mouseleave(function () {

                    showEmojiList = false;

                    setTimeout(function () {
                        if (!showEmojiList) {
                            self.find('.input-form__smiles').fadeOut('fast');
                        }
                    }, 500);
                });


                $(this).find('.input_form-send-button').click(function () {


                    if (self.data('cont.widgets.inputform.sending')) return;



                    self.data('cont.widgets.inputform.sending', true);

                    var textArea = self.find('.input_form__textarea').clone();

                    var usedEmojies = [];

                    //last emoji saving
                    textArea.find('.emoji').each(function (index, item) {

                        var emojiCode = $(item).attr('alt');

                        $(item).replaceWith(' ' + emojiCode + ' ')

                        if (!~usedEmojies.indexOf(emojiCode)) {

                            usedEmojies.push(emojiCode);
                        }


                    });


                    //trim new lines
                    textArea.contents().each(function () {
                        if (this.nodeType == 3) this.nodeValue = this.nodeValue.replace(/(\r\n|\n|\r)/gm, "");

                    });

                    textArea[0].normalize();

                    //wrap all text nodes to tags, for regexp
                    textArea.contents().filter(function () {
                        return this.nodeType === 3 && $.trim(this.nodeValue) !== '' && this.nextSibling && this.nextSibling.tagName == 'DIV';
                    }).after($('<br />'));


                    //unwrap divs
                    textArea.find('div, p').append($('<br />')).contents().unwrap();


                    //trim new lines
                    textArea.contents().each(function () {
                        if (this.nodeType == 3) this.nodeValue = this.nodeValue.replace(/(\r\n|\n|\r)/gm, "");
                        ;
                    });

                    textArea[0].normalize();

                    var text = textArea.html();

                    text = text.replace(/<\s*br\s*\/?>/ig, '\r\n').replace(/<[^>]*>/ig, '');


                    $(this).children('img').show();

                    var attachments = $imageContainer.find('.limg-preview').map(function (index, element) {
                        return $(element).attr('data-url');
                    }).toArray();


                    self.trigger('cont.widgets.inputform.send', [$.trim(text), attachments, usedEmojies]);

                });

                emojify.run(self[0]);

                $(this).find('.emoji-wrap img').click(function () {

                    self.find('.input_form__textarea').focus();

                    var emojiCode = $(this).attr('alt');
                    var emojiTag = emojify.replace($(this).attr('alt'));
                    pasteHtmlAtCaret(emojiTag);
                    self.find('.input_form__placeholder').hide();

                });

                $(this).on('click', '.emoji-last img', function (evt) {

                    self.find('.input_form__textarea').focus();

                    var emojiCode = $(this).attr('alt');
                    var emojiTag = emojify.replace($(this).attr('alt'));
                    pasteHtmlAtCaret(emojiTag);
                    self.find('.input_form__placeholder').hide();

                });

                if (options.showSendSettings) {

                    $(this).find('.input_form-send-button').mouseenter(function () {

                        showSendSettings = true;

                        setTimeout(function () {

                            if (showSendSettings) {
                                self.find('.send-settings').fadeIn('fast');
                            }

                        }, 1500);

                    });

                    $(this).find('.input_form-send-button').mouseleave(function () {

                        showSendSettings = false;

                        setTimeout(function () {

                            if (!showSendSettings) {
                                self.find('.send-settings').fadeOut('fast');
                            }

                        }, 500);

                    });

                }


                $(this).find('.stickers-wrap .sticker').click(function () {

                    self.trigger('cont.widgets.inputform.send-sticker', [$(this).attr('data-sticker-group'), $(this).attr('data-sticker')]);

                });

                $(this).find('.input_form__textarea').on('paste', function (e) {

                	var clipboardData = e.clipboardData || e.originalEvent.clipboardData || window.clipboardData;
   					var pastedData = clipboardData.getData('text');

                	pasteHtmlAtCaret(pastedData.replace(/<(?!br).*?>/g, '').replace(/\n/g, "<br />"));
                    

                    return false;
                })

                var $imageContainer = self.find('.images-load-container');

                $('#hidden-image-input-' + formTimestamp).fileupload({
                    url: '/handlers/input-form-img-upload.php',
                    formData: {
                        module: 'comments'
                    },
                    fileInput: $('#hidden-image-input-' + formTimestamp),
                    dataType: 'json',
                    dropZone: self,
                    pasteZone: self.find('.input_form__textarea'),
                    limitMultiFileUploads: 6,
                    autoUpload: false
                }).on('fileuploadadd', function (e, data) {

                    var fc = self.data('cont.widgets.inputform.fc') || 0;

                    if (fc === 6) {
                        data.files.length = 0;
                        return;
                    }

                    $.each(data.files, function (index, file) {

                        var reader = new FileReader;

                        reader.onload = function (e) {

                            //set file upload ID
                            file.uploadID = self.data('cont.widgets.inputform.fileIndex') || 0;

                            self.data('cont.widgets.inputform.fileIndex', file.uploadID + 1);

                            file.name = file.name || 'clipboard image';

                            if (self.find('.images-load-container').children().length >= 2) {
                                if (!self.find('.images-load-container').children('.clearfix').length)
                                    self.find('.images-load-container').children().eq(2).after('<div class="clearfix" />');

                            }

                            var $item = $('<div class="limg-preview" data-id="' + file.uploadID + '" />').attr('style', 'background: url(' + e.target.result + ')').append(
                                $('<div class="limg-preview-inner" />').append('<div class="img-progress" data-img-id="' + file.uploadID + '" />').append('<i class="remove-prw fa fa-times" aria-hidden="true" data-file-id="' + index + '"></i>').append($('<span />').text(file.name.substr(0, 15)))
                            );

                            $item.find('.img-progress').circleProgress({
                                value: 0,
                                size: 40,
                                fill: {
                                    color: '#fff'
                                },
                                emptyFill: 'rgba(255, 255, 255, .2)'
                            });


                            $item.find('i').off('click').on('click', function () {
                                var elem = $(this);
                                data.files.length = 0;
                                self.data('cont.widgets.inputform.uploading', false);
                                fc--;

                                if (fc < 3) {

                                    self.find('.images-load-container').find('.clearfix').remove();
                                }

                                elem.parent().parent().fadeOut('fast', function () {
                                    elem.parent().parent().remove();
                                    if (!self.find('.images-load-container').children().length) {
                                        self.find('.images-load-container').fadeOut('fast');
                                    }

                                    if (fc < 6) self.find('.images-load-container').removeAttr('disabled');

                                });
                            });

                            $imageContainer.append($item);
                            $imageContainer.css('top',-($imageContainer.height() + 30 + 10));
                            $imageContainer.fadeIn('fast');

                        }
                        reader.readAsDataURL(file);

                        if (fc >= 5) {
                            self.find('.images-load-container').attr('disabled', 'disabled');
                        } else {
                            self.find('.images-load-container').removeAttr('disabled');
                        }

                        fc++;

                        self.data('cont.widgets.inputform.fc', fc);
                    });

                    data.submit();

                }).on('fileuploaddone', function (e, data) {
                    self.find('.images-load-container').find('[data-img-id="' + data.files[0].uploadID + '"]').attr('style', 'visibility: hidden');
                    self.find('.images-load-container').find('[data-id="' + data.files[0].uploadID + '"]').attr('data-url', data.result.response);
                    data.files.length = 0;
                    self.data('cont.widgets.inputform.uploading', false);
                }).on('fileuploadprogress', function (e, data) {
                    var progress = parseInt(data.loaded / data.total * 100, 10) / 100;
                    try {
                        self.find('.images-load-container').find('[data-img-id="' + data.files[0].uploadID + '"]').circleProgress('value', progress);
                    } catch (e) {
                    }
                }).on('fileuploadprogressall', function (e, data) {

                    self.data('cont.widgets.inputform.uploading', true);

                }).on('fileuploadfail', function (e, data) {
                    console.log('file upload failed');
                    console.log(e);
                });

                $(this).find('.input_form-cancel-button').click(function () {

                    self.trigger('cont.widgets.inputform.cancel', []);

                });


            });


        },

        addAttachmentByURL: function (URL, filename) {

            var $commentForm = $(this);
            var $attachmentsContainer = $commentForm.find('.images-load-container');

            //getting form data
            var fileCount = $commentForm.data('cont.widgets.inputform.fc') || 0;
            var fileIndex = $commentForm.data('cont.widgets.inputform.fileIndex') || 0;

            //set classes based on file count
            if (fileCount < 3) {

                $attachmentsContainer.addClass('count-few').removeClass('count-many');

            } else {

                $attachmentsContainer.removeClass('count-few').addClass('count-many');

            }

            //append clearfix
            if (fileCount == 2) {

                $attachmentsContainer.append($('<div />').addClass('clearfix'));

            }


            var $attachmentElement = makeAttachmentItem(URL, fileIndex++, filename).attr('data-url', URL);

            //append element
            $attachmentsContainer.append($attachmentElement);

            //set event handler
            $attachmentElement.find('i').on('click', function () {

                var fileCount = $commentForm.data('cont.widgets.inputform.fc') || 0;
                var elem = $(this);

                if (fileCount < 3) {

                    $attachmentsContainer.addClass('count-few').removeClass('count-many');
                    $attachmentsContainer.find('.clearfix').remove();

                } else {

                    $attachmentsContainer.removeClass('count-few').addClass('count-many');

                }

                $commentForm.data('cont.widgets.inputform.fc', --fileCount);

                elem.parent().parent().fadeOut('fast', function () {

                    elem.parent().parent().remove();

                    if (!$attachmentsContainer.children().length) {
                        $attachmentsContainer.fadeOut('fast');
                    }

                    if (fileCount < 6) $attachmentsContainer.removeAttr('disabled');

                });
            });


            //set data
            $commentForm.data('cont.widgets.inputform.fc', ++fileCount);
            $commentForm.data('cont.widgets.inputform.fileIndex', fileIndex);


            //show attachment box
            $attachmentsContainer.fadeIn('fast');

        },
        clearForm: function () {

            $(this).find('.input_form__textarea').html('');
            $(this).find('.input_form__placeholder').show();
            $(this).find('.input_form-send-button').children('img').hide();
            $(this).find('.images-load-container').children().remove();

            $(this).data('cont.widgets.inputform.fc', 0);
            $(this).data('cont.widgets.inputform.fileIndex', 0);
            $(this).data('cont.widgets.inputform.sending', false);


        },
        showError: function (text, sendingStatus) {

            //set error text
            $(this).find('.alert.alert-danger').text(text).show();
            //remove sending
            $(this).find('.input_form-send-button').children('img').hide();


            $(this).data('cont.widgets.inputform.sending', false);


        },
        getSendingStatus: function () {

            return $(this).data('cont.widgets.inputform.sending');

        },
        destroy: function () {

            $(this).remove();
        }
    };

    $.fn.inputForm = function (method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('No method found!');
        }

    };

    $.setLastEmojies = function (newLastEmojies) {

        lastEmojies = newLastEmojies;
    };


    $.inputFormUtils = {

        addLastEmojies: function (emojies) {

            //merge new emojies
            lastEmojies = emojies.concat(lastEmojies);

            //filter duplicates
            lastEmojies = lastEmojies.filter(function (item, index) {

                return lastEmojies.indexOf(item) == index;
            });

            //trim emojies
            lastEmojies = lastEmojies.slice(0, 8);

            var $lastEmojiesElements = $();

            for (var i = 0; i < lastEmojies.length; i++) {

                //add emoji view
                $lastEmojiesElements = $lastEmojiesElements.add($(emojify.replace(lastEmojies[i])));
            }

            //add to elements
            $(document).find('.emoji-last').each(function (index, element) {

                $(element).children().remove();

                $(element).append($lastEmojiesElements.clone());

            });

        },
        addLastSticker: function (stickerData) {

            for(var i = 0; i < lastStickers.length; i++) {

                if(lastStickers[i].group === stickerData.group && lastStickers[i].sticker == stickerData.sticker) {
                    lastStickers.splice(i,1);
                }
            }

            lastStickers.unshift(stickerData);

            var $lastStickersItems = $();

            for (var i = 0; i < lastStickers.length; i++) {

                $lastStickersItems = $lastStickersItems.add($('<div />')
                    .append($('<div />')
                        .attr('style', 'background: url(/icons/stickers/' + lastStickers[i].group + '/' + lastStickers[i].sticker + '.png)')
                        .attr('data-sticker-group',lastStickers[i].group)
                        .attr('data-sticker', lastStickers[i].sticker)
                        .addClass('sticker')
                    )
                    .addClass('stickers-wrap__item'));
            }

            $('.input_form .stickers-wrap[data-sticker-group="last"]').empty().append($lastStickersItems);




        }

    };


    $.setLastStickers = function (newLastStickers) {

        lastStickers = newLastStickers;
    }

})(jQuery);
