jQuery(document).ready(function () { /** * Селектор кол-ва элементов на странице */ $(".page-limit").change(function () { page_limit($(this)); }); /** * Формы входа */ var secret_input = $(""); $("#top_login").append(secret_input); $("#page_login").append(secret_input.clone()); initSpoilers(); /** * Smiles */ $(".text-emoticon.popup").mouseenter(function () { $(this).css("z-index", "999"); $(this).css("transform", "scale(2.5)"); }) .mouseleave(function () { $(this).css("z-index", "0"); $(this).css("transform", "scale(1)"); }); /** * Error-tooltip */ $(".alert.alert-error-box").hover(function () { var clone = $(this).find(".error-tooltip").clone(); clone.addClass("error-tooltip-clone").css({display: "inline-block"}); $("body").append(clone); var top = $(this).offset().top - clone.outerHeight() - 10; var delta = 0; if ($(this).outerWidth() < clone.outerWidth()) { delta = -(clone.outerWidth() - $(this).outerWidth()) / 2; } if ($(this).outerWidth() > clone.outerWidth()) { delta = +($(this).outerWidth() - clone.outerWidth()) / 2; } var left = $(this).offset().left + delta; clone.offset({top: top, left: left}); }, function () { $(".error-tooltip-clone").remove(); }); }); // проверка блоков, которые могут содержать баннеры, на попадание во viewport $.event.special.load = { postDispatch: function () { prepareBannerData(); if (typeof advertData === 'object' && Object.keys(advertData).length > 0) { searchShownBanners(); $(document).on("resize scroll touchmove MSPointerMove pointermove", function () { searchShownBanners(); }); } } }; $('iframe[name="content_frame"]').on('load', function () { if (!$.isArray(advertData) && Object.keys(advertData).length > 0) { searchShownBanners(); } }); function prepareBannerData() { if (typeof advertData !== 'undefined' && advertData.length > 0) { // if not context let advertElements = {}; // load elements $.each(advertData, function (index, value) { let element = $("a[data-id='" + value + "']"); if (element.length > 0) { advertElements[value] = element.closest('div'); } }); advertData = advertElements; } } /** * Спойлер */ function initSpoilers() { $(".spoiler .title").click(function () { if ($(this).data('open') == '1') { $(this).parent().find(" > .data").hide(); $(this).data('open', '0'); $(this).find(" > .icon").html(''); } else { $(this).parent().find(" > .data").show(); $(this).data('open', '1'); $(this).find(" > .icon").html(''); } }); } /** * Ckeditor presets */ var ckeditor_adv_desc = { language: 'ru', toolbar: [ {name: 'clipboard', items: ['Undo', 'Redo']}, {name: 'styles', items: ['Format', 'TextColor', 'BGColor']}, {name: 'basicstyles', groups: ['basicstyles', 'cleanup'], items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {name: 'paragraph', groups: ['list', 'indent', 'align'], items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']}, {name: 'links', items: ['Link', 'Unlink']}, {name: 'insert', items: ['Image', 'Table', 'quote_btn', 'spoiler_btn', 'user_btn', 'smile_btn']}, {items: ['Source']}, ] }; var ckeditor_slim = { language: 'ru', toolbar: [ {name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat']}, {name: 'paragraph', groups: ['list', 'indent', 'align'], items: ['NumberedList', 'BulletedList']}, {name: 'links', items: ['Link', 'Unlink']}, {name: 'insert', items: ['Image', 'quote_btn', 'spoiler_btn', 'user_btn', 'smile_btn']} ] }; /** * Перезагружает страницу с добавлением выбранного per_page * @param select */ function page_limit(select) { var url = window.location.href.urlQueryParameter('page_limit', select.val()); url = url.urlQueryParameter('page', '1'); window.location.href = url; } /** * Показывает скрывает блок */ function toggleThis(data) { var item = $(data); if (item.attr('data-toggle') == '1') { item.show().attr('data-toggle', '0'); return true; } else { item.hide().attr('data-toggle', '1'); return false; } } /** * Вставляет прелоадер в указанный jquery элемент с указанным типом * * @param item * @param type */ function set_preloader(item, type) { if (type == 'loading-spinner-blue') { item.html('Загрузка'); } if (type == 'input-spinner') { item.html('Загрузка'); } if (type == 'fa-refresh') { item.html(''); } } /** * Проверяет есть ли у какого нибудь родителя (и у себя) указанный id или class * * @param item * @param val * * @returns {Boolean} */ function is_have_in_tree(item, val) { //проверим его самого if (item.hasClass(val) || item.attr('id') == val) { return true; } //првоерим родителя var parent = item.parent(); if (parent.length > 0) { if (parent.hasClass(val) || parent.attr('id') == val) { return true; } } //если у родителя есть родитель то в рекурсию if (parent.parent().length > 0) { return is_have_in_tree(parent, val); } return false; } /** * Добавляет параметр к url * * @param key * @param value * * @returns {String} */ String.prototype.urlQueryParameter = function (key, value) { var uri = this; if (uri instanceof String || typeof uri == 'string') { var regEx = new RegExp("([?|&])" + key + "=.*?(&|$)", "i"); var separator = uri.indexOf('?') !== -1 ? "&" : "?"; if (uri.match(regEx)) { uri = uri.replace(regEx, '$1' + key + "=" + value + '$2'); } else { uri = uri + separator + key + "=" + value; } } return uri; }; /** * Выдаёт нужный варинт в зависимости от числа * * @param amount * @param variants */ function choose_plural(amount, variants) { amount = Math.abs(amount); var mod10 = amount % 10; var mod100 = amount % 100; var variant = 0; if (mod10 == 1 && mod100 != 11) { variant = 0; } else if (mod10 >= 2 && mod10 <= 4 && !(mod100 > 10 && mod100 < 20)) { variant = 1; } else { variant = 2; } return variants[variant]; } /** * Simple implementation based on $.extend() from jQuery * * @returns {Object} */ function merge() { var obj, name, copy, target = arguments[0] || {}, i = 1, length = arguments.length; for (; i < length; i++) { if ((obj = arguments[i]) != null) { for (name in obj) { copy = obj[name]; if (target === copy) { continue; } else if (copy !== undefined) { target[name] = copy; } } } } return target; } function poll_vote(poll_id, variant) { //запрос $.post("/misc.ajax?act=poll_vote", { poll_id: poll_id, variant: variant }, function (data) { //сообщение if (data.status == 'fail') { toastr.error(data.text, 'Ошибка!'); } //сообщение if (data.status == 'success') { toastr.success(data.text, 'Успех!'); var poll = $("#poll-" + poll_id); //откроем результаты poll.find(".results").show(); poll.find(".vars").hide(); //выставим значения for (var key in data.vars) { poll.find(".results .result-" + key + " .fill").css({width: data.vars[key]['percent_of_max'] + '%'}); poll.find(".results .result-" + key + " .count").html(data.vars[key]['count']); poll.find(".results .result-" + key + " .percent").html(data.vars[key]['percent'] + "%"); } poll.find(".all-count").html(data.vote_count); poll.find(".vote-text").html(choose_plural(data.vote_count, ['проголосовал', 'проголосовало', 'проголосовали'])); poll.find(".user-text").html(choose_plural(data.vote_count, ['пользователь', 'пользователя', 'пользователей'])); } }, "json"); } function addslashes(str) { return (str + '') .replace(/[\\"']/g, '\\$&') .replace(/\u0000/g, '\\0'); } var variable = { 'data': {}, 'set': function (key, val) { variable.data[key] = val; }, 'get': function (key) { if (variable.data[key] === undefined) { return false; } else { return variable.data[key]; } }, 'update': function () { for (var index in variable.data) { $("[variable-id='" + index + "']").html(variable.data[index]); } }, 'updateMailCount': function () { //обновим все цифры if (variable.get("menu_count_new_mail") < 0) { variable.set("menu_count_new_mail", 0); } if (variable.get("menu_count_new_talk") < 0) { variable.set("menu_count_new_talk", 0); } variable.update(); //если 0 в главной цифре if (variable.get("menu_count_new_talk") == 0) { //скроем цифру вообще $("#menu_count_new_talk").hide(); } else { //покажем $("#menu_count_new_talk").show(); } //если ноль в любых других var variable_class = $("[variable-id='menu_count_new_mail']").attr('variable-class'); if (variable.get("menu_count_new_mail") == 0) { $("[variable-id='menu_count_new_mail']").removeClass(variable_class).addClass("badge-default"); } else { $("[variable-id='menu_count_new_mail']").removeClass("badge-default").addClass(variable_class); } variable_class = $("[variable-id='menu_count_new_mail_dialogue']").attr('variable-class'); if (variable.get("menu_count_new_mail_dialogue") == 0) { $("[variable-id='menu_count_new_mail_dialogue']").removeClass(variable_class).addClass("badge-default"); } else { $("[variable-id='menu_count_new_mail_dialogue']").removeClass("badge-default").addClass(variable_class); } }, 'updateWorkCount': function () { //обновим все цифры variable.update(); //если 0 в главной цифре if (variable.get("menu_count_new_work") == 0) { //скроем цифру вообще $("#menu_count_new_work").hide(); } else { //покажем $("#menu_count_new_work").show(); } //если 0 доработки заданий if (variable.get("menu_count_rework_task") == 0) { //скроем цифру вообще $("#menu_count_rework_task").hide(); } else { //покажем $("#menu_count_rework_task").show(); } }, 'updateAdvertCount': function () { //обновим все цифры variable.update(); //если 0 в главной цифре if (variable.get("menu_count_new_advert") == 0) { //скроем цифру вообще $("#menu_count_new_advert").hide(); } else { //покажем $("#menu_count_new_advert").show(); } } }; /** * Слежка за материалом */ function make_sub(object_id, object_type) { //запрос $.post("/misc.ajax?act=make_sub", { object_id: object_id, object_type: object_type }, function (data) { //сообщение if (data.status == 'fail') { toastr.error(data.text, 'Ошибка!'); } //сообщение if (data.status == 'success') { if (data.state == 'on') { $("#sub-box-" + object_id + " .state-on").show(); $("#sub-box-" + object_id + " .state-off").hide(); } else { $("#sub-box-" + object_id + " .state-on").hide(); $("#sub-box-" + object_id + " .state-off").show(); } } }, "json"); } function unserialize(data) { var that = this, utf8Overhead = function (chr) { // http://phpjs.org/functions/unserialize:571#comment_95906 var code = chr.charCodeAt(0); if (code < 0x0080) { return 0; } if (code < 0x0800) { return 1; } return 2; }; error = function (type, msg, filename, line) { throw new that.window[type](msg, filename, line); }; read_until = function (data, offset, stopchr) { var i = 2, buf = [], chr = data.slice(offset, offset + 1); while (chr != stopchr) { if ((i + offset) > data.length) { error('Error', 'Invalid'); } buf.push(chr); chr = data.slice(offset + (i - 1), offset + i); i += 1; } return [buf.length, buf.join('')]; }; read_chrs = function (data, offset, length) { var i, chr, buf; buf = []; for (i = 0; i < length; i++) { chr = data.slice(offset + (i - 1), offset + i); buf.push(chr); length -= utf8Overhead(chr); } return [buf.length, buf.join('')]; }; _unserialize = function (data, offset) { var dtype, dataoffset, keyandchrs, keys, contig, length, array, readdata, readData, ccount, stringlength, i, key, kprops, kchrs, vprops, vchrs, value, chrs = 0, typeconvert = function (x) { return x; }; if (!offset) { offset = 0; } dtype = (data.slice(offset, offset + 1)) .toLowerCase(); dataoffset = offset + 2; switch (dtype) { case 'i': typeconvert = function (x) { return parseInt(x, 10); }; readData = read_until(data, dataoffset, ';'); chrs = readData[0]; readdata = readData[1]; dataoffset += chrs + 1; break; case 'b': typeconvert = function (x) { return parseInt(x, 10) !== 0; }; readData = read_until(data, dataoffset, ';'); chrs = readData[0]; readdata = readData[1]; dataoffset += chrs + 1; break; case 'd': typeconvert = function (x) { return parseFloat(x); }; readData = read_until(data, dataoffset, ';'); chrs = readData[0]; readdata = readData[1]; dataoffset += chrs + 1; break; case 'n': readdata = null; break; case 's': ccount = read_until(data, dataoffset, ':'); chrs = ccount[0]; stringlength = ccount[1]; dataoffset += chrs + 2; readData = read_chrs(data, dataoffset + 1, parseInt(stringlength, 10)); chrs = readData[0]; readdata = readData[1]; dataoffset += chrs + 2; if (chrs != parseInt(stringlength, 10) && chrs != readdata.length) { error('SyntaxError', 'String length mismatch'); } break; case 'a': readdata = {}; keyandchrs = read_until(data, dataoffset, ':'); chrs = keyandchrs[0]; keys = keyandchrs[1]; dataoffset += chrs + 2; length = parseInt(keys, 10); contig = true; for (i = 0; i < length; i++) { kprops = _unserialize(data, dataoffset); kchrs = kprops[1]; key = kprops[2]; dataoffset += kchrs; vprops = _unserialize(data, dataoffset); vchrs = vprops[1]; value = vprops[2]; dataoffset += vchrs; if (key !== i) { contig = false; } readdata[key] = value; } if (contig) { array = new Array(length); for (i = 0; i < length; i++) { array[i] = readdata[i]; } readdata = array; } dataoffset += 1; break; default: error('SyntaxError', 'Unknown / Unhandled data type(s): ' + dtype); break; } return [dtype, dataoffset - offset, typeconvert(readdata)]; }; return _unserialize((data + ''), 0)[2]; } /** * Неугодные браузеры */ function isBadBrowser() { if ($.browser.opera && parseFloat($.browser.version) < 15) { return true; } if ($.browser.msie && parseFloat($.browser.version) < 8) { return true; } if ($.browser.mozilla && parseFloat($.browser.version) < 3.6) { return true; } } /** * Yandex browser * * @type Boolean */ function isYandex() { var agent = navigator.userAgent; if (agent.search(/YaBrowser/i) == -1) { return false; } else { return true; } } /** * Content claim open */ var current_claim_object_type = false; var current_claim_object_id = false; function content_claim(type, object_id) { current_claim_object_type = type; current_claim_object_id = object_id; var content_claim_box = $("#content-claim-" + object_id); var last_html = content_claim_box.html(); //загрузка set_preloader(content_claim_box, 'fa-refresh'); //запрос $.post("/misc.ajax?act=content_claim", { object_id: object_id, object_type: type }, function (data) { //сообщение if (data.status == 'fail') { toastr.error(data.text, 'Ошибка!'); } //сообщение if (data.status == 'success') { //откроем форму $("#contentClaimModal").modal(); //форма сама $("#contentClaimModal .modal-body").html(data.html); Metronic.handleUniformIn("#contentClaimModal"); //выборка если была content_claim_type_select(); } //вернём кнопку content_claim_box.html(last_html); }, "json"); } /** * Content claim send */ function content_claim_send() { //прогрессбар $("#contentClaimModal .send-btn").button('loading'); //запрос $.post("/misc.ajax?act=content_claim_send", { object_id: current_claim_object_id, object_type: current_claim_object_type, claim_type: $("#content-claim-type-selector option:selected").val(), task_type: $("#content-claim-task-type option:selected").val(), description: $("#content-claim-description").val() }, function (data) { //сообщение if (data.status == 'fail') { $("#contentClaimModal .response-box").html('
\ Ошибка! ' + data.text + '\
'); } //сообщение if (data.status == 'success') { $("#contentClaimModal .response-box").html('
\ Успех! ' + data.text + '\
'); //закроем окно через пол секунды setTimeout(function () { $('#contentClaimModal').modal('hide'); }, 1000); } //прогрессбар $("#contentClaimModal .send-btn").button('reset'); }, "json"); } /** * Select type */ function content_claim_type_select() { var object_type = $("#claim-object-type").val(); var claim_type = $("#content-claim-type-selector option:selected").val(); $("#content-claim-task-type-place").hide(); $("#content-claim-desc-place").show(); $("#content-claim-description-text").html('Опишите жалобу подробнее:'); if (object_type == 'task') { if (claim_type == 'cant_done') { $("#content-claim-description-text").html('Опишите, что конкретно не выполнимо в задании:'); } if (claim_type == 'action_before') { $("#content-claim-description-text").html('Укажите, что автор задания просит выполнить до нажатия кнопки:'); } if (claim_type == 'big_reject') { $("#content-claim-description-text").html('Автор задания действительно отказал вам оплате? Опишите подробнее:'); } if (claim_type == 'wrong_type') { $("#content-claim-description-text").html('Укажите правильный раздел по вашему мнению:'); $("#content-claim-task-type-place").show(); $("#content-claim-desc-place").hide(); } if (claim_type == 'low_pay') { $("#content-claim-description-text").html('Сколько денег требуется потратить в процессе выполнения:'); } if (claim_type == 'no_18') { $("#content-claim-description-text").html('Почему вы считаете, что сайт для взрослых:'); } if (claim_type == 'fishing') { $("#content-claim-description-text").html('На какой сайт это подделка и что пытаются украсть:'); } if (claim_type == 'virus') { $("#content-claim-description-text").html('Приложите ссылку на скриншот вашего антивируса или virustotal.com:'); } if (claim_type == 'negative') { $("#content-claim-description-text").html('Какие негативные действия требует выполнить рекламодатель:'); } } if (object_type == 'mail') { } if (object_type == 'visit' || object_type == 'letter' || object_type == 'surfing' || object_type == 'quiz') { if (claim_type == 'fishing') { $("#content-claim-description-text").html('На какой сайт это подделка и что пытаются украсть:'); } if (claim_type == 'virus') { $("#content-claim-description-text").html('Приложите ссылку на скриншот вашего антивируса или virustotal.com:'); } } } /** * Get selected text * * @returns {String} */ function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; } /** * Seconds to time */ function secToTime(sec) { var sec_num = parseInt(sec, 10); var days = Math.floor(sec_num / 86400); var hours = Math.floor((sec_num - (days * 86400)) / 3600); var minutes = Math.floor((sec_num - (days * 86400 + hours * 3600)) / 60); var seconds = sec_num - (days * 86400 + hours * 3600 + minutes * 60); if (days < 10) { days = "0" + days; } if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } if (seconds < 10) { seconds = "0" + seconds; } var text = days + " д., " + hours + " ч., " + minutes + " м., " + seconds + " с."; return text; }