var _startTimer = (new Date()).getTime(),
    __scrollPoint = 0,
    Path = {
        'js': '/template/js/'
    },
    Intervals = [],
    stMap = {

        'arbour': ['emoji.js'],
        'photos': ['upload_file.js?2'],
        'id\\d+(\/)?$': ['emoji.js'],
        'id\\d+(\/)?(\\?page=cover)$': ['upload_file.js?2']

    };
function on_screen(elem) {
    try {
        var docViewTop = $(window).scrollTop(), docViewBottom = docViewTop + window.innerHeight;
        if ($(elem) !== undefined) {
            elemTop = $(elem).offset().top;
            var r = ((docViewBottom >= elemTop));
        } else {
            r = false;
        }
    } catch (e) {
        r = false;
    }
    return r;
}
function isFunction(obj) {
    return Object.prototype.toString.call(obj) === '[object Function]';
}
function isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
}
function isEmpty(o) {
    if (Object.prototype.toString.call(o) !== '[object Object]') {
        return false;
    }
    for (var i in o) {
        if (o.hasOwnProperty(i)) {
            return false;
        }
    }
    return true;
}
function eventsList(element) {
    var events = element.data('events');
    if (events !== undefined)return events;
    events = $.data(element, 'events');
    if (events !== undefined)return events;
    events = $._data(element, 'events');
    if (events !== undefined)return events;
    events = $._data(element[0], 'events');
    if (events !== undefined)return events;
    return false;
}
function checkEvent(element, eventname) {
    var events, ret = false;
    events = eventsList(element);
    if (events) {
        $.each(events, function (evName, e) {
            if (evName == eventname) {
                ret = true;
            }
        });
    }
    return ret;
}
$.fn.hasAttr = function (name) {
    return this.attr(name) !== undefined;
};
$.fn.extend({
    insertAtCaret: function (myValue) {
        return this.each(function (i) {
            if (document.selection) {
                this.focus();
                var sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            } else if (this.selectionStart || this.selectionStart == '0') {
                var startPos = this.selectionStart;
                var endPos = this.selectionEnd;
                var scrollTop = this.scrollTop;
                this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
                this.focus();
                this.selectionStart = startPos + myValue.length;
                this.selectionEnd = startPos + myValue.length;
                this.scrollTop = scrollTop;
            } else {
                this.value += myValue;
                this.focus();
            }
        })
    }
});
var Linesoc = {
    countMessages: 0,
    activeWindow: true,
    delNote: function () {
        if ($('.note-error')) {
            $('.note-error').remove();
        }
        if ($('.note-success')) {
            $('.note-success').remove();
        }
    },
    addNote: function (m, e) {
        if (m != "") {
            var n = 'note-' + (e == true ? 'error' : 'success' );
            Linesoc.delNote();
            $(($('#location').text() != undefined ? '#location' : '#main' )).after('<div class="' + n + '">' + m + '</div>');
        }
    },
    ajaxSave: function (a, e) {
        $.ajax({
            url: "",
            data: "",
            type: 'POST',
            beforeSend: function (data) {
                console.log("send..");
            },
            success: function (data) {
                console.log("success!");
            }
        });
    },
    StatusSelect: function (r) {
        with (r) {
            if ($("#select_partner") != undefined) {
                if (options[selectedIndex].value >= 3 && options[selectedIndex].value <= 7) {
                    $("#select_partner").css('display', 'block');
                    $("#select_partner").html('<a href="/anketa?act=anketa/edit&amp;select_partner=1&amp;status=' + options[selectedIndex].value + '" style="padding: 7px;" class="_action-link">Изменить партнёра</a>');
                } else {
                    $("#select_partner").css('display', 'none');
                }
            }
        }
    }
}


var App = {
    taggerData: [],
    toggle: function (x) {
        if ($(x)) {
            var d = $(x).attr('data-id');
            var cl = $(x).attr('data-class');
            if (!$(x).hasClass(cl)) {
                $(x).addClass(cl);
            } else {
                $(x).removeClass(cl);
            }
            $("#" + d).css('display', ($("#" + d).css('display') == 'none' ? 'block' : 'none'));
        }
        event.preventDefault();
    },
    coverSelect: function () {
        $("input[name='cover_cancel']").on('click', function (e) {
            if ($(".cover-page--element")) {
                var el = $(this).attr('data-id');
                $(".cover-page--element").css('background', $("#cover--" + el).css('background'));
                $("input[name='cover']").val(el);
                $(".cover-page--floating").css('display', 'none');
            }
            e.preventDefault();
            return false;
        });
        $(".cover-select--items a").on('click', function (e) {
            var a = $(this).attr('data-src');
            if ($(".cover-page--element")) {
                $(".cover-page--element").css('background', ($(this).attr('data-id') > 0 ? 'url("' + a + '")' : a ));
                $("input[name='cover']").val($(this).attr('data-id'));
                $(".cover-page--floating").css('display', 'inline');
            }
            e.preventDefault();
        });
    },


}

var UI = {
    ajaxLoad: '',
    toggleMenu: function (t) {
        var b = $(".toggle-menu:eq(" + $("." + $(t).attr("class")).index(t) + ")");
        if (!b.hasClass("toggle-menu-open")) {
            $(".toggle-menu-open").removeClass("toggle-menu-open");
            b.addClass("toggle-menu-open");
        } else {
            b.removeClass("toggle-menu-open");
        }
    },
    loadTagger: function (t) {
        var h = $(t).height();
        var w = $(t).width();
        var r = 0;
        var p = $(t).attr('data-source');

        var v1, v2, v3, v4;
        if (w > h) {
            r = h;
            v1 = p * (w / 100);
            v2 = 0;
            v3 = v1 + r;
            v4 = r;
        } else {
            r = w;
            v1 = 0;
            v2 = p * (h / 100);
            v3 = r;
            v4 = v2 + r;
        }
        console.log(v1);
        $(t).imgAreaSelect({
            handles: false,
            minWidth: r,
            maxWidth: r,
            minHeight: r,
            maxHeight: r,
            resizable: false,
            disabled: true,
            x1: v1, y1: v2, x2: v3, y2: v4,
            onSelectEnd: function (img, selection) {
                App.taggerData = selection;
                $("#tagger-btn").css('display', 'block');
            }
        });
        $("#tagger-btn input[name='tagger']").on('click', function () {
            var url = $(this).attr('data-url') + "?edit=1&tagger=1";
            event.preventDefault();
            console.log(App.taggerData.y1);
            $.ajax({
                url: url,
                data: {
                    x1: App.taggerData.x1,
                    y1: App.taggerData.y1,
                    x2: App.taggerData.x2,
                    y2: App.taggerData.y2,
                    height: App.taggerData.height,
                    width: App.taggerData.width
                },
                beforeSend: function (s) {
                },
                type: "POST",
                success: function (d) {
                    $("#tagger-btn").css('display', 'none');
                }
            });
        });
    },
    addScript: function (rr) {
        $("*[id='__js-delete']").remove();
        $(".__js-delete").remove();
        for (i in stMap) {
            r = new RegExp("" + i + "");
            if (rr.match(r)) {
                stMap[i].forEach(function (item, i, arr) {
                    obj = document.createElement("script");
                    obj.type = "text/javascript";
                    obj.src = Path.js + item;
                    obj.id = "__js-delete";
                    obj.async = true;
                    $("head").append(obj);
                });
            }
        }
    },
    clearInt: function (arr) {
        for (var i = 0; i < arr.length; i++) {
            clearTimeout(arr[i]);
        }
    },
    delNote: function () {
        if ($('.note-error')) {
            $('.note-error').remove();
        }
        if ($('.note-success')) {
            $('.note-success').remove();
        }
    },
    addNote: function (m, e) {
        if (m != "") {
            var n = 'note-' + (e == true ? 'error' : 'success' );
            UI.delNote();
            $(($('#location').text() != undefined ? '#location' : '#main' )).after('<div class="' + n + '">' + m + '</div>');
        }
    },
    addStylerForm: function () {
        if (!Browser.mobile) {
            $('input[type="radio"],input[type="file"],select,input[type="checkbox"]').not("input[data-nostyle]").styler();
        }
    },
    toTop: {
        hide: function () {
            __scrollPoint = 0;
            $('#scrollup').removeClass('-show');
            $('#scrollup').removeClass('-toCheckPoint');
        },
        __init: function () {
            var header = $("#top");
            var sidebar = $("#sidebar");
            var scrollup = $("#scrollup");
            var scrollPrev = 0;
            var sidebarTop = parseInt(sidebar.css('top'), 10);
            $('#scrollup').on('click', function () {
                x = $(window).scrollTop();
                $(window).scrollTop($(window).scrollTop() > 100 ? 0 : __scrollPoint);
                if (x > 0) {
                    $('#scrollup').addClass('-toCheckPoint');
                    __scrollPoint = x;
                } else {
                    $('#scrollup').removeClass('-toCheckPoint');
                    __scrollPoint = 0;
                }
            });
            if (!Browser.mobile) {
                $(window).scroll(function () {
                    var scr = $(this).scrollTop();
                    if (scr > 100) {
                        $('#scrollup').addClass('-show');
                        $('#scrollup').removeClass('-toCheckPoint');
                    } else {
                        $('#scrollup').removeClass('-show');
                    }
                    if (scr > scrollPrev) {
                        if (scr > 30) {
                            header.css({"top": "-" + header.height() + "px"});
                            sidebar.css({"top": 10 + "px"});
                            scrollup.css({"top": "0px"});
                        }
                    } else {
                        header.css({"top": "0px"});
                        sidebar.css({"top": (header.height() + 10) + "px"});
                        scrollup.css({"top": header.height() + "px"});
                    }
                    scrollPrev = scr;
                });
            }


        }

    },
    formFocus: function (e) {
        $(e).focus();
        return false;
    },
    mouseEnter: function () {
        /*
         if(!Browser.mobile) {
         var d = $("*[data-mouseenter]");
         d.mouseenter(function() {$($( this ).attr( "data-mouseenter" )).show().css('opacity',1);
         }).mouseleave(function() {
         $($( this ).attr( "data-mouseenter" )).hide().css('opacity',0);
         }).mouseleave();
         }*/
    },
    sidebarToggle: function () {
        var b = $("body");
        if (b.hasClass("__js-sidebar-show")) {
            b.removeClass("__js-sidebar-show");
        } else {
            b.addClass("__js-sidebar-show");
        }
    },
    status: {
        url: '',
        Toggle: function (click, event) {
            event.preventDefault();
            this.url = click.attr('href');
            var b = ($('*[data-role="status-out"]'));
            if ($(".p-status").hasClass("app-dropdown-arrow")) {
                b.hide();
                $(".p-status").removeClass("app-dropdown-arrow");
            } else {
                b.show();
                $(".p-status").addClass("app-dropdown-arrow");
                var test = $.trim($('span[id=data-emoji]').text());
                var t = (test != '' ? $.trim($('.curr_status').text()) : '' );
                $('#status-input').val(test).focus();
            }
        },
        Save: function () {
            $.ajax({
                'url': this.url,
                'type': 'POST',
                'data': {'status-text': $('#status-input').val(), 'access': USER.access},
                'dataType': "json",
                'success': function (data) {
                    var b = ($('*[data-role="status-out"]'));
                    $('span[id=data-emoji]').html($.trim(data.text));
                    data = ($.trim(data.text).length > 0 ? $.trim(data.emoji) : 'изменить статус');
                    $('.curr_status').html(data);
                    b.hide();
                    $(".p-status").removeClass("app-dropdown-arrow");
                }
            });
        }
    }
}
$(function () {
    UI.toTop.__init();
    UI.addStylerForm();
    $(window).bind('focus', function () {
        Linesoc.activeWindow = true;
        $('title').html(USER.title);
    });
    $(window).bind('blur', function () {
        Linesoc.activeWindow = false;
    });
});

    function Sound() {
        "use strict";
        var i = !1, a = this, r = void 0;
        try {
            r = ce("audio"), i = !!r.canPlayType, "no" != r.canPlayType("audio/mpeg") && "" != r.canPlayType("audio/mpeg")
        } catch (s) {
        }

            r.src = '/template/notification/not.mp3';
            var c = !1;
            r.addEventListener("ended", function () {
                c = !0
            }, !0), r.load(), this.playSound = function () {
                c && (r.currentTime = .01), r.load(), r.play(), c = !1
            }
    }

Sound.prototype = {
        play: function () {
            try {
                this.playSound()
            } catch (e) {
            }
        }
};
var $LP = {
    mailContactMessages: null,
    mailContactMessagesCount: 0,
    thisStatus: 0,
    status: {
        CLOSED: 0,
        RECONNECT: 1,
        CONNECT: 2
    },
    sound: new Sound(),
    statuschange: function (s) {
        switch (s) {
            case $LP.status.CLOSED:
                debLog('LongPolling: disconnected');
                break;
            case $LP.status.RECONNECT:
                debLog('LongPolling: sending request..');
                break;
            case $LP.status.CONNECT:
                debLog('LongPolling: connection');
                break;
        }
        $LP.thisStatus = s;
    },
    update: function (d) {
        $LONG = $.ajax({
            type: 'GET',
            'async': true,
            url: '/ajax?act=update',
            data: {data: d},
            'dataType': 'JSON',
            success: function (data) {
                if(data.isPlay == true) {
                    $LP.sound.playSound();
                }
                if (data.count_mail > 0) {
                    $("#update_msg_head_wap").find('.head-count').show().text(data.count_mail);
                    $("#update_msg_head_web").find('.sidebar--count').show().text(data.count_mail);
                } else {
                    $("#update_msg_head_wap").find('.head-count').hide().text(data.count_mail);
                    $("#update_msg_head_web").find('.sidebar--count').hide().text(data.count_mail);
                }
                if (data.count_notice > 0) {
                    $("#update_notice_head_wap").find('.head-count').show().text(data.count_notice);
                    $("#update_notice_head_web").find('.sidebar--count').show().text(data.count_notice);
                } else {
                    $("#update_notice_head_wap").find('.head-count').hide().text(data.count_notice);
                    $("#update_notice_head_web").find('.sidebar--count').hide().text(data.count_notice);
                }
                return true;
            },
            error: function (e) {
                $LP.statuschange($LP.status.RECONNECT);
                return false;
            }
        });
        return true;
    },
    __init: function () {
        TimerVisibl.every(5000, function(){
            $LP.update([]);
        });
    }
};

jQuery(document).ready(function () {
    if ($("textarea[data-focus='1']")) {
        UI.formFocus($("textarea[data-focus='1']"));
    }
    if (USER.id > 0) {
        $LP.__init();
    }
    if (Browser.iphone || Browser.ipad || Browser.ipod) {
        $("body").css({webkitTextSizeAdjust: 'none'});
    }
});

function debLog(msg) {
    try {
        var t = '[' + (((new Date()).getTime() - _startTimer) / 1000) + '] ';
        if (window.console && console.log) {
            var args = Array.prototype.slice.call(arguments);
            args.unshift(t);
            if (Browser.msie || Browser.mobile) {
                console.log(args.join(' '));
            } else {
                console.log.apply(console, args);
            }
        }
    } catch (e) {
    }
}

if (!window._ua) {
    var _ua = navigator.userAgent.toLowerCase();
}
var Browser = {
    version: (_ua.match(/.+(?:me|ox|on|rv|it|era|opr|ie|edge)[\/: ]([\d.]+)/) || [0, '0'])[1],
    opera: (/opera/i.test(_ua) || /opr/i.test(_ua)),
    vivaldi: /vivaldi/i.test(_ua),
    msie: (/msie/i.test(_ua) && !/opera/i.test(_ua) || /trident\//i.test(_ua)) || /edge/i.test(_ua),
    msie6: (/msie 6/i.test(_ua) && !/opera/i.test(_ua)),
    msie7: (/msie 7/i.test(_ua) && !/opera/i.test(_ua)),
    msie8: (/msie 8/i.test(_ua) && !/opera/i.test(_ua)),
    msie9: (/msie 9/i.test(_ua) && !/opera/i.test(_ua)),
    msie_edge: (/edge/i.test(_ua) && !/opera/i.test(_ua)),
    mozilla: /firefox/i.test(_ua),
    chrome: /chrome/i.test(_ua) && !/edge/i.test(_ua),
    safari: (!(/chrome/i.test(_ua)) && /webkit|safari|khtml/i.test(_ua)),
    iphone: /iphone/i.test(_ua),
    ipod: /ipod/i.test(_ua),
    iphone4: /iphone.*OS 4/i.test(_ua),
    ipod4: /ipod.*OS 4/i.test(_ua),
    ipad: /ipad/i.test(_ua),
    android: /android/i.test(_ua),
    bada: /bada/i.test(_ua),
    mobile: /iphone|ipod|ipad|opera mini|opera mobi|iemobile|android/i.test(_ua),
    msie_mobile: /iemobile/i.test(_ua),
    safari_mobile: /iphone|ipod|ipad/i.test(_ua),
    opera_mobile: /opera mini|opera mobi/i.test(_ua),
    opera_mini: /opera mini/i.test(_ua),
    mac: /mac/i.test(_ua),
    search_bot: /(yandex|google|stackrambler|aport|slurp|msnbot|bingbot|twitterbot|ia_archiver|facebookexternalhit)/i.test(_ua)
};
var $NOTIFER = {};
var Tick = function () {
    var IDTimers = [];
    var IDCallFuncTick = [];
    var Time = 5e3;

    var t = function iv() {
        var t = {
            i : -1,
            change : function (e) {
            if (!t.isSupported()) return !1;
            t.i += 1;
            var n = t.i;
            return t._callbacks[n] = e, t._listen(), n
        },hidden : function () {
            return !(!t._doc.hidden && !t._doc.webkitHidden)
        },state : function () {
            return t._doc.visibilityState || t._doc.webkitVisibilityState || "visible"
        },isSupported : function () {
            return !(!t._doc.visibilityState && !t._doc.webkitVisibilityState)
        },_doc : document || {},
            _callbacks : {},_change : function (e) {
            var i = t.state();
            for (var n in t._callbacks) t._callbacks[n].call(t._doc, e, i)
        }, _listen : function () {
            if (!t._init) {
                var e = "visibilitychange";
                t._doc.webkitVisibilityState && (e = "webkit" + e);
                var i = function () {
                    t._change.apply(t, arguments)
                };
                t._doc.addEventListener ? t._doc.addEventListener(e, i) : t._doc.attachEvent(e, i), t._init = !0
            }
        },_timers : {}, _time : function () {
            t._timed || (t._timed = !0, t._wasHidden = t.hidden(), t.change(function () {
                t._stopRun(), t._wasHidden = t.hidden()
            }))
        },_run : function (i, n) {
            var r, d = t._timers[i];
            if (t.hidden()) {
                if (null === d.hidden) return;
                r = d.hidden
            } else r = d.visible;
            var a = function () {
                d.last = new Date, d.callback.apply(null, d.args)
            };
            if (n) {
                var o = new Date, c = o - d.last;
                r > c ? d.delay = setTimeout(function () {
                    d.id = setInterval(a, r), a()
                }, r - c) : (d.id = setInterval(a, r), a())
            } else d.id = setInterval(a, r)
        }, _stop : function (e) {
            var i = t._timers[e];
            clearInterval(i.id), clearTimeout(i.delay), delete i.id, delete i.delay
        }, _stopRun : function (e) {
            var i = t.hidden(), n = t._wasHidden;
            if (i && !n || !i && n) for (var r in t._timers) t._stop(r), t._run(r, !i)
        }
    };
        return {
            every: function ev(e, n, r, args) {
                t._time(), r || (r = n, n = null), t.i += 1;
                var d = t.i;
                return t._timers[d] = {
                    visible: e,
                    hidden: n,
                    callback: r,
                    args: args
                }, t._run(d, !1), t.isSupported() && t._listen(), d
            }, stop : function st(e) {
                return !!t._timers[e] && (t._stop(e), delete t._timers[e], !0)
            }
        }
    }();

    return {
        setTick: function (func) {
            var r = Array.prototype.slice.call(arguments);
            r.shift();
            if ((typeof func).toLowerCase() != 'function') {
                return false;
            }
            var key = func.name;
            if (key == undefined || key == '') {
                return false;
            }

            if (IDCallFuncTick[key] == undefined) {
                var idT = t.every(Time, null, func, r);
                if (typeof idT != 'undefined') {
                    IDTimers.push(idT);
                    IDCallFuncTick[key] = idT;
                    return true;
                }
            }
            Time = 5e3;
            return false;
        }, clearTick: function () {
            for (var i = 0; i < IDTimers.length; i++) {
                t.stop(IDTimers[i]);
            }
            IDTimers = [];
            IDCallFuncTick = [];
        }, setTime: function (t) {
            Time = t;
            return true;
        }, stopTick: function (e) {
            if(IDCallFuncTick[e] === undefined)
                return false;
            t.stop(IDCallFuncTick[e]);
            IDTimers.splice(IDTimers.indexOf(IDCallFuncTick[e]), 1);
            delete IDCallFuncTick[e];
            return true;
        }
    }
}();
var Emotions = function e(){
    var isOpen = false;
    $(document).on("click", "span[id=emotions]", function (event) {
        $('div.emoji_tt_wrap').toggleClass('emoji_tt_shown');
        isOpen = !isOpen;
    });

    var dataLast = "";
    function s(t) {
        t = $(t);
        var data = t.attr('data-emotions');
        if(data == dataLast || /^([0-9]{1,3}_[0-9]{1,3})$/.test(data) === false)
            return;
        $('.emoji_smile_cont.emoji_smile_selected').removeClass('emoji_smile_selected')
        $('.cover-page--avatar').attr('data-emotions', (data == '0_0' ? '' : data));
        $('.emoji_smile_cont[data-current]').attr('data-emotions', (data == '0_0' ? '' : data));
        t.addClass('emoji_smile_selected');
        dataLast = (data == '0_0' ? '' : data);
        Tick.stopTick('setEmotions');
        Tick.setTime(1e3);
        Tick.setTick(setEmotions);
    }
    function setEmotions(){
        $.post('/ajax/?act=emotions', {emo:dataLast});
        Tick.stopTick('setEmotions');
    }
    return {
        selected: s,
        toggle: function() {
            if(isOpen === true) {
                var n = $('div.emoji_tt_wrap');
                if (n.hasClass('emoji_tt_shown'))
                    n.removeClass('emoji_tt_shown');
                isOpen = false;
            }
        }
    }
}();