window.addEventListener('load', function () { StatisticsModule.runerPage('pg', '$biblia$'); StatisticsModule.runer(); }); var StatisticsModule = (function () { var PROJECT = 'biblia'; // !!! // var ON_DEBUG = false; var START_RATE_INDEX = 0; var RATING_VOTED = false; var votes5 = 'голосов'; var votes2 = 'голоcа'; var vote1 = 'голос'; var voted = 'Вы уже проголосовали'; var price = ["худо", "слабо", "сносно", "достойно", "чудесно"]; var options = {}; options.expires = 60 * 60 * 24; options.path = window.location.pathname; var URL_BATCH_QUERY = 'https://stat.azbyka.ru/batch-query/'; var URL_COUNTER = 'https://stat.azbyka.ru/counters/'; var URL_RATE = 'https://stat.azbyka.ru/rate/'; var URL_SCORE = 'https://stat.azbyka.ru/item-score/'; var URL_WEBSOCKET = 'wss://stat.azbyka.ru/realtime-view/'; var URL_UPDATE_SOCKET = 'wss://stat.azbyka.ru/updates'; var URL_UPDATE_SOCKET_TIMEOUT = 3000; // мс var _runerPage = function (type1, id1, type2, id2) { var selected = type1 && id1; if (selected) { _addOneCounter(type1, id1, type2, id2); request = URL_WEBSOCKET + _getQuString(type1, id1, type2, id2, false, '/'); try { var socket = new ReconnectingWebSocket(request, null, { timeoutInterval: 10000, reconnectInterval: 5000, maxReconnectAttempts: 20 }); socket.onopen = function () { if (ON_DEBUG) console.log(" Соединение установлено: " + request); }; if (ON_DEBUG) { socket.onerror = function (error) { console.log("Ошибка " + error.message); }; socket.onclose = function (event) { if (event.wasClean) { console.log('Соединение закрыто чисто: ' + request); } else { console.log('Обрыв соединения: ' + request); } console.log('Код: ' + event.code + ' причина: ' + event.reason); }; } } catch (e) { console.error(e.name + ': ' + e.message); } } }; var _runer = function () { var counters = []; var countersx = []; var counters_lst = []; $('.abc-counter').each(function () { var el = $(this); var type1 = el.attr('data-type-1'); var id1 = el.attr('data-id-1'); var type2 = el.attr('data-type-2'); var id2 = el.attr('data-id-2'); var key = _getQuString(type1, id1, type2, id2, true, ':'); var keyx = _getQuString(type1, id1, type2, id2, true, '/'); counters.push(key); countersx.push(keyx); counters_lst.push({ 'key': key, 'keyx': keyx, 'type1': type1, 'id1': id1, 'type2': type2, 'id2': id2, }); }); if (ON_DEBUG) console.log(counters); if (ON_DEBUG) console.log(counters_lst); _getAllCountersX(counters, counters_lst); var request = URL_UPDATE_SOCKET; if (URL_UPDATE_SOCKET_TIMEOUT) { request = request + "?time=" + URL_UPDATE_SOCKET_TIMEOUT; } var updatesocket = new ReconnectingWebSocket(request, null, { timeoutInterval: 10000, reconnectInterval: 5000, maxReconnectAttempts: 20 }); updatesocket.onopen = function() { if (ON_DEBUG) console.log(" Соединение установлено: " + request); updatesocket.send(JSON.stringify(countersx)); }; updatesocket.onmessage = function(e) { if (ON_DEBUG) console.log(" Пришло сообщение: " + e.data); var countersMy = JSON.parse(e.data); if (ON_DEBUG) console.log(countersMy); $.each( countersMy, function( k, v ) { $.each( counters_lst, function( kl, vl ) { if (vl.keyx === k) { $('.abc-counter').filter(function() { if ($(this).attr("data-project") === PROJECT && $(this).attr("data-type-1") === vl.type1 && $(this).attr("data-id-1") === vl.id1 && $(this).attr("data-type-2") === vl.type2 && $(this).attr("data-id-2") === vl.id2) { $(this).find('.abc-counter-now').text( (v).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') ); return true; } }); return false; } }); }); }; if (ON_DEBUG) { updatesocket.onerror = function (error) { console.log("Ошибка " + error.message); }; updatesocket.onclose = function (event) { if (event.wasClean) { console.log('Соединение закрыто чисто: ' + request); } else { console.log('Обрыв соединения: ' + request); } console.log('Код: ' + event.code + ' причина: ' + event.reason); }; } }; /** увеличивает счетчик на 1 **/ var _addOneCounter = function (type1, id1, type2, id2) { var request = URL_COUNTER + _getQuString(type1, id1, type2, id2, false, '/'); console.log('GQS', _getQuString(type1, id1, type2, id2, false, '/')); var xhr = new XMLHttpRequest(); xhr.open("POST", request, true); if (ON_DEBUG) console.log('GET REQUEST: ' + request); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { if (xhr.responseText) { var response = JSON.parse(xhr.responseText); if (response.success) { if (ON_DEBUG) console.log(JSON.stringify(response.data)); _setViewCount(type1, id1, type2, id2, response.data.value, // total (response.data.now + 1)); // now } else { if (ON_DEBUG) console.log('GET REQUEST: ' + request + ' ERROR: ' + response.error); } } } }; xhr.send(); }; /** Отображает значения счетчика на странице **/ var _setViewCount = function (type1, id1, type2, id2, total = '', now = '') { $('.abc-counter').filter(function() { if ($(this).attr("data-project") === PROJECT && $(this).attr("data-type-1") === type1 && $(this).attr("data-id-1") === id1 && $(this).attr("data-type-2") === type2 && $(this).attr("data-id-2") === id2) { if (!total) total=0; if (!now) now=0; if (total) { $(this).find('.abc-counter-views').text(_counterNumberFormat(total)); $(this).find('.abc-counter-views').attr('title', 'Всего просмотров: ' + (total).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ')); } if (now) $(this).find('.abc-counter-now').text( (now).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') ); } }); }; var _getQuString = function (type1, id1, type2, id2, add_slash, delim) { var ret = ""; if (add_slash) ret = "/"; ret = ret + 'project' + delim + PROJECT; if (id1 && type1) { ret = ret + "/" + type1 + delim + id1; if (id2 && type2) { ret = ret + "/" + type2 + delim + id2; } } return ret; }; /** Добавляет разделитель тысяч **/ var _addDelimiter = function (nStr, dlm) { if (!nStr) nStr = '0'; if (!dlm) dlm = '\xa0'; nStr += ''; var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + dlm + '$2'); } return x1 + x2; }; var _counterNumberFormat = function (num) { num = parseFloat(num); if (num > 1000000.0) { num = num / 1000000; num = num.toFixed(1) + "М"; } else if (num > 10000.0) { num = num / 1000; num = num.toFixed() + "К"; } else if (num > 1000.0) { num = num / 1000; num = num.toFixed(1) + "К"; } else { num = _addDelimiter(num); } return num; }; var _getAllCountersX = function (counters, counters_lst) { $.ajax({ type: "POST", url: URL_BATCH_QUERY, data: JSON.stringify(counters), success: function(data) { var counters = JSON.parse(JSON.stringify(data)); if (ON_DEBUG) console.log(counters); $.each( counters, function( k, v ) { $.each( counters_lst, function( kl, vl ) { if (vl.key === k) { $('.abc-counter').filter(function() { if ($(this).attr("data-project") === PROJECT && $(this).attr("data-type-1") === vl.type1 && $(this).attr("data-id-1") === vl.id1 && $(this).attr("data-type-2") === vl.type2 && $(this).attr("data-id-2") === vl.id2) { if (!v.viewCounter) v.viewCounter=0; if (!v.onlineCounter) v.onlineCounter=0; $(this).find('.abc-counter-views').text(_counterNumberFormat(v.viewCounter)); $(this).find('.abc-counter-views').attr('title', 'Всего просмотров: ' + (v.viewCounter).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ')); $(this).find('.abc-counter-now').text( (v.onlineCounter).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') ); return true; } }); return false; } }); }); } }); }; ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// var _runerRating = function (type1, id1, type2, id2) { StatisticsModule.getAllRates(); if (!id1) return; if (jQuery("div").is(".abc_counter_rating") === false) return; // нет счетчика StatisticsModule.set_start_rate_index( parseFloat(jQuery("#abc_counter_score").html()) ); StatisticsModule.set_rating_voted( (jQuery("#abc_counter_score").attr("data-voted") == 'true') ? true : false ); StatisticsModule.getRate(type1, id1, type2, id2); jQuery(".abc_counter_rating").show(); var abc_counter_rate_box_li = jQuery("#abc_counter_rate_box li"); abc_counter_rate_box_li.mouseover(function () { if (!StatisticsModule.get_rating_voted()) { var index = jQuery(this).index(); StatisticsModule.iniRatingState(index + 1, StatisticsModule.get_rating_voted()); jQuery('#abc_counter_popup_help').text(price[index]); } else { jQuery('#abc_counter_popup_help').text(voted); } jQuery('#abc_counter_popup_help').show(); }); jQuery("#abc_counter_rate_box").mouseout(function () { if (!StatisticsModule.get_rating_voted()) { StatisticsModule.iniRatingState( StatisticsModule.get_start_rate_index(), StatisticsModule.get_rating_voted()); } jQuery('#abc_counter_popup_help').hide(); }); abc_counter_rate_box_li.click(function () { if (!StatisticsModule.get_rating_voted()) { StatisticsModule.set_rating_voted(true); abc_counter_rate_box_li.css('cursor', 'default'); var sIndex = jQuery(this).index() + 1; StatisticsModule.sendRate(type1, id1, type2, id2, sIndex); } }); }; var _iniRatingState = function (parIndex, parVoted) { if (ON_DEBUG) console.log("_iniRatingState: parIndex=" + parIndex + ", parVoted=" + parVoted); var abc_counter_rate_box_li = jQuery("#abc_counter_rate_box li"); if (abc_counter_rate_box_li.length) { if (!parVoted) { abc_counter_rate_box_li.css('cursor', 'pointer'); } else { abc_counter_rate_box_li.css('cursor', 'default'); } var star = parseInt(abc_counter_rate_box_li.css('height')); // star height abc_counter_rate_box_li.css('background-position', '0px ' + star + 'px'); abc_counter_rate_box_li.each(function (index) { var n = parIndex - parIndex % 1; if (index 0) { var p = star * (Math.round(4 * (parIndex - index)) + 1); jQuery(this).css('background-position', '0px ' + p + 'px'); } }); } }; /********************************************************************************* GET /item-score/ Возвращает рейтинг и количество голосов отдельно взятого объекта - score. Также возвращается флаг, голосовал ли уже данный пользователь. Пример запроса: GET /item-score/project/test/author/1 Пример ответа: {"success": true, "data": {"alreadyVoted":true, "score": 3.7142857142857144, "votes": 7}} Если объект не существует, возвращает success: false и data: null. **********************************************************************************/ var _getRate = function (type1, id1, type2, id2) { var request = URL_SCORE + _getQuString(type1, id1, type2, id2, false, '/'); var xhr = new XMLHttpRequest(); xhr.open("GET", request, true); if (ON_DEBUG) console.log('GET REQUEST: ' + request); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (xhr.responseText) { var response = JSON.parse(xhr.responseText); if (response.success) { if (ON_DEBUG) console.log(JSON.stringify(response.data)); m = response.data.votes % 10; j = response.data.votes % 100; var txt_votes = ''; if (m == 0 || m >= 5 || (j >= 10 && j = 2 && m Увеличивает сумму оценок объекта на указанную величину (от 1 до 5) и количество голосов на 1. Возвращает новый рейтинг и количество голосов. Рейтинг рассчитывается по формуле: новый рейтинг = сумма оценок / количество голосов; REQUEST: POST /rate/project/test/author/1/book/3 BODY: {"rating": 4} Пример RESPONSE: {"success": true, "data": {"score": 4.0625, "votes": 16}} **********************************************************************************/ var _sendRate = function (type1, id1, type2, id2, number) { var request = URL_RATE + _getQuString(type1, id1, type2, id2, false, '/'); var xhr = new XMLHttpRequest(); xhr.open("POST", request, true); if (ON_DEBUG) console.log('POST REQUEST: ' + request); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { if (xhr.responseText) { var response = JSON.parse(xhr.responseText); if (response.success) { if (ON_DEBUG) console.log(JSON.stringify(response.data)); m = response.data.votes % 10; j = response.data.votes % 100; var txt_votes = ''; if (m == 0 || m >= 5 || (j >= 10 && j = 2 && m

Shar-ya 3 Com.stormx.xteam 193 Bagulnik-bolotnyj-lechebnye-i-yadovitye-svojstva