/**
 * Author - koder_alex
 * ISQ - 669906617
 * VK - https://vk.com/koder_alex
 * It is forbidden to give, sell, modify.
 */

function ce(e, t) {
    var n = document.createElement(e);
    return t && extend(n, t), n
}
function extend() {
    var e = Array.prototype.slice.call(arguments), t = e.shift();
    if (!e.length)return t;
    for (var a = 0, n = e.length; n > a; a++)for (var o in e[a])"layerX" != o && "layerY" != o && (t[o] = e[a][o]);
    return t
}
function cancelEvent(e) {
    return (e = e || window.event) ? (e = e.originalEvent || e, e.preventDefault && e.preventDefault(), e.stopPropagation && e.stopPropagation(), e.cancelBubble = !0, e.returnValue = !1, !1) : !1
}
function isObject(e) {
    return "object" === typeof e
}

function des2num(int, array) {
    var cases = [2, 0, 1, 1, 1, 2];
    return int + array[(int % 100 > 4 && int % 100 < 20) ? 2 : cases[Math.min(int % 10, 5)]]
}
var request = {update: 5E3, limit: 10, page: 2};
(function ($) {
    var interVal = 5e3;
    var timerID = undefined;
    $.fn.AnimateHide = function (interval) {
        var self = this;
        if (interval !== undefined) {
            interVal = interval;
        } else {
            interVal = 5e3;
        }
        if (timerID !== undefined) {
            clearTimeout(timerID);
        }
        timerID = setTimeout(function () {
            return self.remove();
        }, interVal);
    };
})(jQuery);
function messageBox(type, text) {
    $('#service_msg_box').remove();
    var node = $('.vk_mail');
    node.prepend('<div id="service_msg_box" class="service_msg_box"><div class="service_msg service_msg_' + type + '">' + text + '</div></div>');
    $('#service_msg_box').AnimateHide();
    return node;
}
MessagesActions = function () {
    return {
        BoxClose: function (d) {
            d = $(d.parentNode);
            d.slideUp(400, function (e) {
                d.remove();
            })
        },
        actionsOpened: function (t, e) {
            cancelEvent(e);
            $(t.parentNode).toggleClass('head_actions_opened');
        }
    }
}(), mail = function () {
    var interval = (new Date).getTime() + request.update;
    var isLoad = false;
    return {
        keyup: function (e, t) {
            var a = $(e).val() || "";
            (a.length > 0) && (this.myTyping(t))
        },
        myTyping: function (peer_id) {
            var date = (new Date).getTime();
            if (interval <= date) {
                interval = date + 2e3;
                $.post('/mail/?act=dataSend&func=myTyping', {im_ajax: true, peer: peer_id});
                return false
            }
        },
        send: function (t, peer_id) {
            var config = $('#data-text'), text = $('textarea'), n = $('.vk_mail');
            var data = {min: config.attr('data-min'), max: config.attr('data-max'), textLength: text.val().length};
            if (data.textLength < data.min || data.textLength > data.max) {
                messageBox('warning', 'Сообщение должно быть длиной не менее ' + des2num(data.min, ['-го', '-х', '-ти']) + ' и не более ' + des2num(data.max, ['-го', '-х', '-ти']) + ' символов.</div>');
                return false;
            }
            t = $(t);
            t.before(ce('button', {
                className: 'button',
                id: 'nowrite_submit',
                innerHTML: '<span class="button_locked"><b class="button_locked_label">Отправить</b></span>',
                disabled: "disabled"
            }));
            t.hide();
            $.post('/mail/?act=dataSend&func=dialog', {
                im_ajax: true,
                to: peer_id,
                from: 'dialog',
                message: text.val()
            }, function (data) {
                $('#nowrite_submit').remove();
                t.show();
                if (!data.mail) {
                    messageBox('error', 'Неизвестная ошибка.');
                }
                if (data.msg_box && data.type) {
                    messageBox(data.type, data.msg_box);
                }
                if ('ok' == data.type) {
                    text.val('');
                    n = $('#messages');
                    n.find('#show_msg_box').length > 0 && (n.find('#show_msg_box').remove());
                    n.prepend(data.mail);
                    n = n.children();
                    n.first().hide().fadeIn(400);
                    if (request.limit < n.length) {
                        n.not('div.show_more_wrap').last().fadeOut(400, function () {
                            $(this).remove();
                        });
                    }
                }
            }, 'json');
            return false;
        },
        updateMail: function (peer_id) {
            $.post('/mail/?act=dataSend&func=update', {im_ajax: true, peer: peer_id}, function (data) {
                if (isObject(data) === false || data.length === 0)
                    return false;
                var n = $('#messages');
                if (data.typing) {
                    $('.near_btn').addClass('di_typing_now di_typing_animated');
                } else {
                    $('.near_btn').removeClass('di_typing_now di_typing_animated');
                }
                if (data.read) {
                    n.find('.mi_unread').removeClass('mi_unread');
                }
                if (data.message.length > 0) {
                    for (var i = 0; i < data.message.length; i++) {
                        n.prepend($(data.message[i]).hide().fadeIn(400));
                    }
                    n.children().not('div.show_more_wrap').each(function (key, item) {
                        if (request.limit <= key) {
                            $(item).fadeOut(400, function () {
                                $(this).remove();
                            });
                        }
                    });
                    if (data.message.length > 0) {
                        n.find('#show_msg_box').length > 0 && (n.find('#show_msg_box').remove());
                    }
                }
            }, 'json');
        }, updateContact: function () {
            var n = $('#contactUpdate');
            $.post('/mail/?act=dataSend&func=contact', {im_ajax: true, page: n.attr('data-page')}, function (data) {
                if (isObject(data) === false || data.length === 0)
                    return false;
                if (data.contact.length > 0) {
                    n.empty();
                    for (var i = 0; i < data.contact.length; i++) {
                        n.prepend(data.contact[i]);
                    }
                }
            }, 'json');
        }, loadMess: function (peer_id) {
            if (isLoad) {
                return;
            }
            isLoad = true;
            $('#show_more').removeClass('show_more').addClass('show_more_loading').html('<span class="button_locked"></span>');
            var match = location.search.match(/p=(\d+)/i);
            if (match !== null && match[1] !== null)
                request.page = parseInt(match[1]) + 1;
            var node = $('#messages');
            $.ajax({
                url: '/mail/?act=dataSend&func=load_mess',
                type: 'post',
                data: {im_ajax: true, peer: peer_id, page: request.page},
                success: function (data) {
                    if (isObject(data) === false || data.length === 0)
                        return false;
                    if (data.message.length > 0) {
                        $('.show_more_wrap').remove();
                        node.append('<div class="foot">Страница: ' + request.page + '</div>');
                        for (var i = 0; i < data.message.length; i++) {
                            node.append(data.message[i]);
                        }
                        var link = '/mail/?act=show&peer=' + peer_id + '&p=' + request.page;
                        window.history.pushState({path: link}, null, link);
                        request.page++;
                    } else {
                        request.page = 2;
                        var link = '/mail/?act=show&peer=' + peer_id + '&p=' + request.page;
                        window.history.pushState({path: link}, null, link);
                    }
                },
                complete: function () {
                    isLoad = false;
                    $('.show_more_wrap').show();
                }
            })
        }
    }
}();
$(document).ready(function () {
    $('.show_more_wrap').show();
    // Enable infinite scrolling when on desktop
    if (/Mobi/.test(navigator.userAgent) === false) {
        $(window).scroll(function () {
            if ($(window).scrollTop() + $(window).height() == $(document).height()) {
                $('#show_more').click();
            }
        });
    }
    $('.vk_mail .textfield').keypress(function (e) {
        if (e.shiftKey && (10 === e.keyCode || 13 === e.keyCode)) {
            $('#write_submit').click();
            e.preventDefault();
        }
    });
});
