const MONTHES_PER_YEAR = 12; var element_id_counter = 1; function Pred(value) { return value - 1; } function Succ(value) { return value + 1; } function AddLeadingChars(text, length, addingChar) { addingChar = addingChar || "0"; let result = '' + text; while (result.length < length) result = addingChar + result; return result; } function DecodeDate(date) { var result = {}; result.year = date.getFullYear(); result.day = AddLeadingChars(date.getDate(), 2); result.month = AddLeadingChars(date.getMonth() + 1, 2); result.hours = AddLeadingChars(date.getHours(), 2); result.minutes = AddLeadingChars(date.getMinutes(), 2); result.seconds = AddLeadingChars(date.getSeconds(), 2); console.log(result); return result; } function openURLAnalyzePressedButtons(url) { url = url || ""; if (url != "") { var window_flag = "_self"; if (event.ctrlKey) window_flag = "_blank"; window.open(url, window_flag).focus(); } } function FormatDate(date) { const dateInfo = DecodeDate(date); return [dateInfo.day, dateInfo.month, dateInfo.year].join('.'); } function FormatDateEn(date) { const dateInfo = DecodeDate(date); return [dateInfo.year, dateInfo.month, dateInfo.day].join('-'); } function FormatTime(date) { const dateInfo = DecodeDate(date); return [dateInfo.hours, dateInfo.minutes, dateInfo.seconds].join(':'); } function AddStackTrace() { try { // Code throwing an exception throw new Error(); } catch(e) { console.log(e.stack); } } function InRange(value, start, end) { var result = (value >= start); result = result && (value <= end); return result; } function ReadCurrentURLParam(param_name) { return ReadURLParam(location.search, param_name); } function CompareInt(int1, int2) { if (int1 != int2) return (int1 > int2) ? 1 : -1; return 0; } function ReadURLParam(url, param_name) { /*var url = new URL(url_string); return url.searchParams.get(param_name);*/ var name = param_name; name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); var results = regex.exec(url); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } function ChangeCurrentBrowserURL(url) { if (url) window.history.replaceState("", "", url); } function AddURLParameter(url, param, paramVal) { var newAdditionalURL = ""; var tempArray = url.split("?"); var baseURL = tempArray[0]; var additionalURL = tempArray[1]; var temp = ""; if (additionalURL) { tempArray = additionalURL.split("&"); for (var i=0; i 1) param_value = DecodeURIComponentFull(param[1]); // console.log(param_name + ": " + param_value); var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", param_name); hiddenField.setAttribute("value", param_value); form.appendChild(hiddenField); } document.body.appendChild(form); form.submit(); document.body.removeChild(form); } function GetAgePostfix(age) { if ((age <= 4) || (age >= 20)) { var age_leftover = age % 10; switch (age_leftover) { case 1: return "рік"; case 2: case 3: case 4: return "року"; } } return "років"; } function AgeToString(age) { if (age > 0) return age + " " + GetAgePostfix(age); return ""; } function VarAsInt(variable) { var result = parseInt(variable, 10); if (isNaN(result)) result = 0; return result; } function GetSelectBoxValue(select_box) { if (select_box) { var selected_item = $(select_box).children("option:selected"); if (selected_item) return selected_item.attr("value"); } return ""; } function GetSelectBoxText(select_box) { if (select_box) { var selected_item = $(select_box).children("option:selected"); if (selected_item) return selected_item.text(); } return ""; } function GetFileExtension(file_name) { if ((file_name) && (file_name.indexOf('.') >= 0)) { return file_name.split('.').pop(); } return ""; } function SetSelectBoxValue(select_box, value) { if (select_box) { $(select_box).children("option").each(function (index, child) { // alert(child.value); if (child.value == value) $(child).attr('selected', 'selected'); else $(child).removeAttr('selected'); }); } } function GetSelectBoxValueInt(select_box) { var value = GetSelectBoxValue(select_box); if (value != "") return VarAsInt(value); return -1; } function IsSelectBoxFilled(select_box) { var value = GetSelectBoxValue(select_box); return ((value != null) && (value != "")); } function IsTextBoxFilled(text_box) { var value = $(text_box).attr("value"); return ((value != null) && (value != "")); } function GetInputBoxValue(element) { return GetTextBoxValue(element); } function GetTextBoxValue(element) { if (element) { return $(element).attr("value"); } return ""; } function GetElementTagName(element) { if (element) { var jquery_element = $(element); if (jquery_element[0]) return jquery_element[0].tagName.toLowerCase(); } return ""; } function IsInputBox(element) { return (GetElementTagName(element) == "input"); } function IsSelectBox(element) { return (GetElementTagName(element) == "select"); } function IsTextArea(element) { return (GetElementTagName(element) == "textarea"); } function IsCheckBox(element) { var result = IsInputBox(element); if (result) result = ($(element).attr('type').toLowerCase() == "checkbox"); return result; } function GetElementValue(element) { if (IsSelectBox(element)) return GetSelectBoxValue(element); return GetInputBoxValue(element); } function IsAnchor(element) { return (GetElementTagName(element) == "a"); } function IsImage(element) { return (GetElementTagName(element) == "img"); } function IsRadioBox(element) { var result = IsInputBox(element); if (result === true) result &= (element.type.toLowerCase() == "radio"); return result; } function IsInputFilled(element) { if (element) { if (IsRadioBox(element)) return IsRadioBoxFilled(element); else { var value = $(element).attr("value"); return IsTextBoxFilled(element); } } return false; } function IsRadioBoxFilled(radio_box) { var result = false; var parent = $(radio_box).parent(); if (parent) { $(parent).children().each(function (index, child) { if ((IsRadioBox(child)) && (IsTextBoxFilled(child)) && (child.checked === true)) { result = true; return; } }); } return result; } function SetRadioBoxCheckedByNameValue(name, value) { var selector = "input[name='" + name + "']"; $(selector).each(function() { if (this.value == value) { $(this).attr('checked', 'checked'); return; } }); } function GetUniqueElementID(element) { if (element) { if (!$(element).attr('id')) { $(element).attr('id', "id_" + element_id_counter); element_id_counter++; } return ($(element).attr('id')); } return null; } function CreateUniqueString(max_length, alphabet) { var result = ""; alphabet = alphabet || "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; if (!max_length) max_length = 32; for (var i = 0; i < max_length; i++) result += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); return result; } function CreateUniqueFileName(ext, uniqueStringLength) { ext = ext || ""; if (!uniqueStringLength) uniqueStringLength = 8; let currentDate = new Date(); let dateInfo = DecodeDate(currentDate); let result = [dateInfo.year, dateInfo.month, dateInfo.day].join('-') + " " + FormatTime(currentDate); result = result.replace(/:/ig, ""); result = result.replace(/ /ig, "-"); result += "-" + CreateUniqueString(uniqueStringLength, "abcdef0123456789"); if (ext != "") result += "." + ext; return result; } function isObject(val) { return (typeof val === 'object'); } function isNumber(str) { var result = (str != null); result = result && (str.length != 0); result = result && (str.match(/^\d+$/)); return result; } function IsValidPhone(phone) { if (phone) { var phone_regex = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im; if (phone_regex.test(phone)) { return true; } } return false; } function ValidateEmail(email) { const email_reg_ex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return email_reg_ex.test(String(email).toLowerCase()); } function AnalyzeEmailControl(email_control, show_alert) { if ((email_control) && (email_control != "")) { var user_email = GetInputBoxValue(email_control); var result = ValidateEmail(user_email); if (!result) { $(email_control).parent()[0].scrollIntoView({ behavior: 'smooth'}); if (show_alert) { var message_str = "Указан неправильный формат электронной почты\n\n"; message_str += "Укажите правильную электронную почту и повторите попытку"; alert(message_str); } } return result; } return false; } function AnalyzeBooleanCondition(condition, description, errorMessageObject) { var result = condition; if ((!result) && (errorMessageObject) && (!errorMessageObject.error)) { errorMessageObject.error = description; } return result; } function IsJson(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } // JQuery additional functions function JQueryGetOuterHTML(s) { return (s) ? this.before(s).remove() : jQuery("

").append(this.eq(0).clone()).html(); } function JQueryChangeVisibility(visible) { if (visible == true) this.show(); else this.hide(); } function JQueryInsertAtIndex(element, index) { var lastIndex = this.children().size(); if (index < 0) { index = Math.max(0, lastIndex + 1 + index); } this.append(element); if (index < lastIndex) { this.children().eq(index).before(this.children().last()); } return this; } function JQueryRemoveAttributes(except_array) { return this.each(function() { var attributes = $.map(this.attributes, function(item) { return item.name; }); var element = $(this); $.each(attributes, function(i, item) { var should_delete = true; if (except_array) { console.log(except_array); should_delete = should_delete && (except_array.indexOf(item) < 0); console.log(item + ": " + except_array.indexOf(item)); } if (should_delete) element.removeAttr(item); }); }); } function UpdateJQueryAdditionalFunctions() { jQuery.fn.outerHTML = JQueryGetOuterHTML; jQuery.fn.changeVisibility = JQueryChangeVisibility; jQuery.fn.insertAt = JQueryInsertAtIndex; jQuery.fn.removeAttributes = JQueryRemoveAttributes; } function Assigned(variable) { let result = (variable != null); result = result && (typeof variable !== 'undefined'); if (result) { if ((typeof variable === 'string') || (variable instanceof String)) { result = result && (variable != ""); } } return result; } function SetCookie(cookie_name, cookie_value, expire_days) { if (Assigned(cookie_name)) { var expires = ""; if (expire_days > 0) { var date_expire = new Date(); date_expire.setTime(date_expire.getTime() + (expire_days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date_expire.toGMTString(); } document.cookie = cookie_name + "=" + cookie_value + expires + "; path=/"; } } function ClearCookie(cookie_name) { SetCookie(cookie_name, ""); } function GetCookie(cookie_name) { var match = document.cookie.match(new RegExp('(^| )' + cookie_name + '=([^;]+)')); if (match) return match[2]; return ""; } function ExecuteHTTPRequest(url, data, on_request_successed, on_request_finish) { return $.ajax( { url: url, type: 'POST', data: data, success: function(response) { if (on_request_successed) on_request_successed(response); }, complete: function(response) { if (on_request_finish) on_request_finish(response); } }); } function ProcessJsonRequest(server_answer, on_request_successed, on_request_error) { if (server_answer.status == "ok") { if (on_request_successed) on_request_successed(server_answer); return true; } else if (server_answer.status == "error") { if (on_request_error) on_request_error(server_answer); else alert(server_answer.error_desc); return true; } return false; } function ExecuteAjaxRequest(url, data, on_request_successed, on_request_error, on_request_finish) { return ExecuteHTTPRequest(url, data, function(response) { var server_answer = JSON.parse(response); ProcessJsonRequest(server_answer, on_request_successed, on_request_error); }, on_request_finish); } function ExecuteMixedRequest(url, data, on_request_successed, on_request_error, on_request_finish) { return ExecuteHTTPRequest(url, data, function(response) { if (IsJson(response)) { var server_answer = JSON.parse(response); if (server_answer) { if ((!ProcessJsonRequest(server_answer, on_request_successed, on_request_error)) && (on_request_successed)) { on_request_successed(server_answer, true); } } } else if (on_request_successed) on_request_successed(response, false); }, on_request_finish); } function CreateURLFromFile(file) { if (file) return URL.createObjectURL(file); return ""; } function GetFirstDayOfYear(year, day_number) { var result = new Date(year + "-01-01"); while (result.getDay() != 1) result = IncrementDays(result, 1); return result; } function IncrementDays(date, days) { var result = new Date(date.valueOf()); result.setDate(result.getDate() + days); return result; } async function getImageSize(url) { return new Promise(resolve => { var image = new Image(); image.onload = function() { resolve({ width: image.width, height: image.height }); }; image.onerror = function() { resolve({width: 0, height: 0}); }; image.src = url; }); } /** Returns the dimensions of a video asynchrounsly. @param {String} url Url of the video to get dimensions from. @return {Promise} Promise which returns the dimensions of the video in 'width' and 'height' properties. */ async function getVideoMetadataOf(url) { var image_size = await getImageSize(url); return new Promise(resolve => { if ((image_size.height > 0) && (image_size.width > 0)) { resolve({ width: image_size.width, height: image_size.height, duration: 0 }); } // create the video element const video = document.createElement('video'); // place a listener on it video.addEventListener( "loadedmetadata", function () { // retrieve dimensions var height = this.videoHeight; var width = this.videoWidth; if ((height == 0) || (width ==0)) { var image_size = getImageSize(url); width = image_size.width; height = image_size.height; } const duration = this.duration; // send back result resolve({ width: width, height: height, duration: duration }); }, false ); // start download meta-datas video.src = url; }); } function GetFileSizeInStringFormat(file_size) { let BYTES_COUNT = 1024; if (file_size > BYTES_COUNT) { // Receive Free bytes in KB let calc_size = (file_size / BYTES_COUNT); let prefix = "КБ"; // If free space in KB > 1024 - receive free spaces in MB if (calc_size > BYTES_COUNT) { calc_size = (calc_size / BYTES_COUNT); prefix = 'МБ'; } // If free space in MB > 1024 - receive free spaces in GB if (calc_size > BYTES_COUNT) { calc_size = (calc_size / BYTES_COUNT); prefix = 'ГБ'; } // If free space in GB > 1024 - receive free spaces in TB if (calc_size > BYTES_COUNT) { calc_size = (calc_size / BYTES_COUNT); prefix = 'ТБ'; } return calc_size.toFixed(2) + ' ' + prefix; } return file_size + ' байт'; } function base64ToDataUri(base64) { return 'data:image/png;base64,' + base64; } function base64ToDataUri(base64) { return 'data:image/png;base64,' + base64; } async function resizeImage(img, width, height) { return new Promise(resolve => { // create an off-screen canvas var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // set its dimension to target size canvas.width = width; canvas.height = height; // draw source image into the off-screen canvas: ctx.drawImage(img, 0, 0, width, height); // encode image to data-uri with base64 version of compressed image resolve(canvas.toDataURL()); }); } async function resizeImageSrc(image_src, width, height) { return new Promise(resolve => { var image = new Image(); image.onload = function() { resolve(resizeImage(this, width, height)); }; image.onerror = function() { resolve(null); }; image.src = image_src; }); } function getScaledImageSize(original_width, original_height, wanted_width, wanted_height) { if ((original_width > 0) && (original_height > 0) && ((wanted_width > 0) || (wanted_height > 0))) { var side_ratio = (original_width / original_height); var new_width = wanted_width; var new_height = wanted_height; // Receive New size of the picture if ((side_ratio <= 1) && (wanted_height > 0)) { new_width = Math.trunc(wanted_height * side_ratio); if ((wanted_width > 0) && (new_width > wanted_width)) { new_height = new_height - Math.trunc((new_width - wanted_width) / side_ratio); new_width = wanted_width; } } else { new_height = Math.trunc(wanted_width / side_ratio); if ((wanted_height > 0) && (new_height > wanted_height)) { new_width = new_width - Math.trunc((new_height - wanted_height) * side_ratio); new_height = wanted_height; } } return {'width': new_width, 'height': new_height}; } return {'width': original_width, 'height': original_height}; } function FormatInteger(integer, digits) { return (integer).toLocaleString('en-US', {minimumIntegerDigits: digits, useGrouping:false}) } function DecodeEntities(text) { return $('