VR = function(){ var _this = this; $().ready(function(){ var i, rl, url = VR.location_dir(); _this.Agent = (_this.getBrowser() || '').toLowerCase(); window.vri = VR.uMicrotime(); _this.IDGenerator_prefix = window.vri + "_"; //-- Запись HTTP ACCESS Query({ action: "http_access", in_background: true, url_from: document.referrer, url_to: window.location.href }); rl = _this.readylist(); if(rl && rl.length){ for(i = 0; i < rl.length; i++){ rl[i].call(_this); } } try { VR.routePage(); } catch(e){ console.log("Invalid handler for page /"+(url === '' ? '' : url+'/'), VR.parseError(e), e); } $(document).idle({ onIdle: function(){ if('VR' in window && !VR.aGet('idlenotused')){ VR.aSet("getChangesStop", true); } }, onActive: function(){ VR.aSet("getChangesStop", false); }, idle: 10000 }); }); }; VR.prototype = { Agent: null, IDGenerator_number: 0, IDGenerator_prefix: null }; VR = new VR(); //****************************************************************************** //-- Получить значение из LocalStorage function LSGet(name) { let r = null; try { r = window.localStorage.getItem(name); } catch (e) { console.error(e); } return r; } //-- Установить значение в LocalStorage function LSSet(name, value) { try { window.localStorage.setItem(name, value); } catch (e) { console.error(e); } } //-- Удалить значение из LocalStorage function LSDel(name){ try { window.localStorage.removeItem(name); } catch (e) { console.error(e); } } //-- Функция позволяет перезаписывать html теги (function($){ $.fn.replaceTagName = function(a){ let t = []; for(let i = this.length - 1; 0 <= i ; i--) { let n = document.createElement(a); n.innerHTML = this[i].innerHTML; $.each(this[i].attributes, function(j, v) { $(n).attr(v.name, v.value); }); $(this[i]).after(n).remove(); t[i] = n; } return $(t); }; })(jQuery); VR.testun = (o) => console.log(o.value); VR.eval = (o) => o ? JSON.parse(o) : null; VR.is_array = (arr) => Object.prototype.toString.call(arr) === '[object Array]'; VR.location_reload = d => { if (!('contains' in d) || window.location.href.indexOf(d.contains) > -1) window.location.reload(); } VR.go = function (url, target) { switch(target || "_self"){ case "_self": return window.location.href = VR.trim(VR.toString(url), '"'); } return false; }; VR.in_array = function (needle, haystack, strict) { let found = false, key strict = !!strict if (this.is_array(haystack)) { for (key in haystack) { if ((strict && haystack[key] === needle) || (!strict && haystack[key] === needle)) { found = true; break; } } } return found; }; VR.array_search = function (needle, haystack) { for(let fkey in haystack){ if (haystack.hasOwnProperty(fkey)){ if ((haystack[fkey] + '') === (needle + '')){ return fkey; } } } return false; }; VR.array_unique = function (inputArr, isAssoc) { let key, val, a1 = [], a2 = {}; isAssoc = isAssoc === undefined ? false : (typeof(isAssoc) === "boolean" ? isAssoc : false); if(this.is_array(inputArr)){ for(key = 0; key 191 && c1 < 224) { c2 = str_data.charCodeAt(i + 1); tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = str_data.charCodeAt(i + 1); c3 = str_data.charCodeAt(i + 2); tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return tmp_arr.join(''); }; VR.utf8_encode = function (argString) { if (argString === null || typeof argString === "undefined") return ""; let string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n"); let utftext = '', start, end, stringl = 0, c1, enc; start = end = 0; stringl = string.length; for (let n = 0; n < stringl; n++) { c1 = string.charCodeAt(n); enc = null; if (c1 < 128) { end++; } else if (c1 > 127 && c1 < 2048) { enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128); } else enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128); //-- if (enc !== null) { if (end > start) utftext += string.slice(start, end); utftext += enc; start = end = n + 1; } } if (end > start) utftext += string.slice(start, stringl); return utftext; }; VR.base64_encode = function (data) { if (!data) return data; //-- let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; let o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; data = this.utf8_encode(data + ''); do { o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); let r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); }; VR.base64_decode = function (data) { if (!data) return data; //-- let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; let o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; data += ''; do { h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 === 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 === 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); dec = this.utf8_decode(dec); return dec; }; VR.toString = function (o){ let type = o === null ? "null" : typeof(o); switch (type){ case "string":return '"'+o.split('"').join('\\"')+'"'; case "number":return o; case "boolean":return o ? "true" : "false"; case "object":return this.is_array(o) ? this.a2s(o) : this.o2s(o); } return null; }; VR.remove_extra_zero = function(v){ let p, r; switch(typeof v){ case 'string': break; case 'number': v += ''; default: v = ''; } v = v.split(',').join('.'); if(v.replace(/[0]+/, '') === ''){ return '0'; } p = v.split('.'); r = /([0]+)/.exec(p[0]); if(r && r[0].length > 0){ r = (p[0]).replace(/^[0]+/g, ''); if(r.length){ p[0] = r.length ? r : '0'; } } return p.join('.'); }; VR.toFixed = function(v, length, round){ let minus, parts, p1, p2, m; round = round === true; v = (v + '').split(',').join('.'); m = /([0-9]+)E\-([0-9]+)$/i.exec(v); if(m && m.length){ v = "0." + this.str_repeat("0", (parseInt(m[2]) - 1)) + m[1]; } if(isNaN(parseFloat(v))){ return null; } //-- minus = parseFloat(v) < 0 ? true : false; parts = v.split("."); p1 = parts[0].replace(/[^0-9]/g,''); p2 = parts[1] ? parts[1].replace(/[^0-9]/g,'') : ''; //-- length = parseInt(length); if (isNaN(length) || length < 0){ length = 2; } if (length === 0 || !p2) { return (minus ? -1 : 1) * parseFloat(p1); } //-- p2 = (p2.length > length ? p2.substr(0, length) : p2); return (minus ? "-" : "") + (round && p2 === VR.str_repeat('9', length) ? parseInt(p1) + 1 : p1 + "." + p2); }; VR.str_repeat = function( input, multiplier ) { let buf = ''; for (let i=0; i < multiplier; i++){ buf += input; } return buf; }; VR.ltrim = function (str, sign){ return this.trim(str, sign, "L"); }; VR.rtrim = function (str, sign){ return this.trim(str, sign, "R"); }; VR.trim = function (str, sign, side){ let s1, s2; sign = sign && typeof(sign) === "string" ? sign : null; side = side && typeof side === "string" ? side : null; //-- if(typeof str !== "string") return str; if(sign){ sign = sign.replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); s1 = new RegExp("^"+sign); s2 = new RegExp(sign+"$"); } else{ s1 = /^\s+/; s2 = /\s+$/; } return side ? ( side.toUpperCase() === "L" ? str.replace(s1, '') : (side.toUpperCase() === "R" ? str.replace(s2, '') : str.replace(s1, '').replace(s2,'') )) : str.replace(s1, '').replace(s2,''); }; VR.ucfirst = function(str) { str += ''; const f = str.charAt(0) . toUpperCase(); return f + str.substr(1); } VR.a2s = function(o){ let a = []; for(let i=0; i d.year ? msec / d.year : 0; years = ( years + '' ).split('.')[0]; msec = years === 0 ? msec : msec - years * d.year; let months = msec > d.month ? msec / d.month : 0; months = ( months + '' ).split('.')[0]; msec = months === 0 ? msec : msec - months * d.month; let days = msec > d.day ? msec / d.day : 0; days = ( days + '' ).split('.')[0]; msec = days === 0 ? msec : msec - days * d.day; let hours = msec > d.hour ? msec / d.hour : 0; hours = ( hours + '' ).split('.')[0]; msec = hours === 0 ? msec : msec - hours * d.hour; let minutes = msec > d.min ? msec / d.min : 0; minutes = ( minutes + '' ).split('.')[0]; msec = minutes === 0 ? msec : msec - minutes * d.min; let seconds = msec > d.sec ? msec / d.sec : 0; seconds = ( seconds + '' ).split('.')[0]; msec = seconds === 0 ? msec : msec - seconds * d.sec; d = (years === 0 ? "" : years + " year ") + (months === 0 ? "" : months + " month ") + (days === 0 ? "" : days + " day ") + (hours === 0 ? "" : hours + " hour ") + (minutes === 0 ? "" : minutes + " min. ") + (seconds === 0 ? "" : seconds + " sec. ") + (msec === 0 ? "" : msec + " msec."); d = d.length ? d.replace(/^\s+/, '').replace(/\s+$/, '') : ''; return d; }; VR.parseError = function(e){ let err = '', p, a = ['','']; if(typeof e === 'string'){ p = ( /^(.+\[\d+\]\s*\:\s*)/.exec(e) || a )[1]; err = p ? e.replace(p,'') : e; } else err = "Type: " + ('name' in e ? e.name : 'undefined') + "\nMessage: " + ('message' in e ? e.message : 'undefined'); return err; }; VR.ajaxLoader = function(is_show){ let cc = parseInt(VR.aGet("AjaxLoaderCallCount")); cc = isNaN(cc) ? 0 : cc; let ajaxLoaderAnimate = function(){ let el = $("#ajax-loader .progress-fill"); if( !$(el).length ) return false; //-- if( $(el).hasClass("animated") === false) { $(el).addClass("animated"); $(el).css({ width: "0px"}); $(el).animate({width: VR.getViewportWidth()+"px"}, 5000, function(){ $(el).removeClass("animated"); $(el).css({ width: "0px"}); if(parseInt(VR.aGet("AjaxLoaderCallCount")) > 0){ ajaxLoaderAnimate(); } }); } }; is_show = is_show === true || is_show === "show" ? true : false; if(is_show && cc <= 0){ $("#ajax-loader").css({ left: 0, top: 0, width: VR.getViewportWidth(), height: VR.getViewportHeight() }); $("#ajax-loader .progress-bar").css({ position : "absolute", left : 0, top : VR.getViewportHeight() - 20, width: VR.getViewportWidth(), height: 20 }); ajaxLoaderAnimate(); $("#ajax-loader").show(); } cc += is_show ? 1 : (cc > 0 ? -1 : 0); if(is_show === false || cc <= 0){ $("#ajax-loader").hide(); $("#ajax-loader .progress-fill").removeClass("animated"); $("#ajax-loader .progress-fill").stop(); } VR.aSet("AjaxLoaderCallCount", cc); }; VR.uniqueID = function (){ this.IDGenerator_number++; return this.IDGenerator_prefix + this.IDGenerator_number; }; VR.uMicrotime = function(old_microtime){ let new_microtime = (new Date().getTime()) * 10; if(!old_microtime){ return new_microtime; } if(old_microtime === new_microtime){ return this.uMicrotime(old_microtime); } return new_microtime; }; VR.setSelection = function(target) { let rng, sel; if (document.createRange) { rng = document.createRange(); rng.selectNode(target); sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(rng); } else { rng = document.body.createTextRange(); rng.moveToElementText(target); rng.select(); } return VR; }; VR.clearSelection = function() { try { // современный объект Selection window.getSelection().removeAllRanges(); } catch (e) { // для IE8- document.selection.empty(); } return VR; }; VR.copyToClipboard = function(text, onsuccess) { let fn = function(){ if (window.clipboardData && window.clipboardData.setData) { // IE specific code path to prevent textarea being shown while dialog is visible. return window.clipboardData.setData("Text", text); } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) { let textarea = document.createElement("textarea"); textarea.textContent = text; textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge. document.body.appendChild(textarea); if(navigator.userAgent.match(/ipad|iphone/i)){ let range = document.createRange(); range.selectNode(textarea); let selection = window.getSelection(); selection.addRange(range); selection.removeAllRanges(); textarea.setSelectionRange(0, 999999); }else{ textarea.select(); } try { return document.execCommand("copy"); // Security exception may be thrown by some browsers. } catch (ex) { console.warn("Copy to clipboard failed.", ex); return false; } finally { document.body.removeChild(textarea); } } }; if(!fn(text)){ alert('Copying to clipboard unsupported. Please update yours browser!'); return VR; } if(onsuccess && typeof onsuccess === 'function'){ onsuccess(text); return VR; } if('toastr' in window){ toastr["success"]('Data has been successfully copied to clipboard', " ", { closeButton: false, debug: false, newestOnTop: false, progressBar: true, positionClass: "toast-top-right", preventDuplicates: true, showDuration: "300", hideDuration: "1000", timeOut: "1000", extendedTimeOut: "1000", showEasing: "swing", hideEasing: "linear", showMethod: "fadeIn", hideMethod: "fadeOut" }); } else { alert('Data has been successfully copied to clipboard'); } return VR; }; VR.copyStruct = function(message, onsuccess) { window.getSelection().removeAllRanges(); let cpsel = document.getElementById('copyStruct'); if(!cpsel) { cpsel = document.createElement("div"); cpsel.id = 'copyStruct'; cpsel.style.opacity = 0 cpsel.style.position = 'fixed' cpsel.style.display = 'none' document.body.appendChild(cpsel); } cpsel.innerHTML = message; cpsel.style.display = 'block'; let range = document.createRange(); range.selectNode(cpsel); window.getSelection().addRange(range); try { document.execCommand('copy'); if(onsuccess && typeof onsuccess === 'function'){ onsuccess(); } } catch(err) {} window.getSelection().removeAllRanges(); cpsel.style.display = 'none'; } VR.getBrowser = function() { let UA = window.navigator.userAgent, YandexB = /YaBrowser\/\w+\.\w+/i, OperaB = /Opera|OPR[ \/]+\w+\.\w+/i, FirefoxB = /Firefox\/\w+\.\w+/i, ChromeB = /Chrome\/\w+\.\w+/i, SafariB = /Version\/\w+\.\w+/i, IEB = /MSIE *\d+\.\w+/i, Firefox = UA.match(FirefoxB), Chrome = UA.match(ChromeB), Safari = UA.match(SafariB), IE = UA.match(IEB), Opera = UA.match(OperaB), Yandex = UA.match(YandexB); if (Opera){ return "opera"; } else if (IE) { return 'msie'; } else if (Firefox) { return 'firefox'; } else if (Yandex) { return 'yandex'; } else if (Safari) { return 'safari'; } else if (Chrome) { return 'chrome'; } return UA; }; VR.isAgent = function(name){ return name.toLowerCase().split(" ").join().replace(/^is/,'') === this.Agent; }; VR.getViewportWidth = function () {return ((document.compatMode || this.isAgent("IE")) && !this.isAgent("Opera")) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientWidth:document.body.clientWidth:(document.parentWindow || document.defaultView).innerWidth;}; VR.getViewportHeight = function () {return ((document.compatMode || this.isAgent("IE")) && !this.isAgent("Opera")) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight:document.body.clientHeight:(document.parentWindow || document.defaultView).innerHeight;}; VR.getDocumentWidth = function () {return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollWidth:document.documentElement.scrollWidth, this.getViewportWidth());}, VR.getDocumentHeight = function () {return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight:document.documentElement.scrollHeight, this.getViewportHeight());}, VR.getBodyScrollTop = function () {return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);}, VR.getBodyScrollLeft = function () {return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);}, VR.boxsize= function(_element){ let elem = typeof(_element)==="string" ? document.getElementById(_element) : _element; if(!elem) return {"left":null, "top":null, "width": null, "height":null}; let w = elem.offsetWidth, h = elem.offsetHeight, l = 0, t = 0; //-- в цикле проходим по всем родительским элементам. while (elem) { l += elem.offsetLeft; t += elem.offsetTop; elem = elem.offsetParent; } return {"left":l, "top":t, "width": w, "height":h}; }; VR.ctx = function(el, search) { let r = $(el).closest(search); return r.length ? r : null; }; VR.ctx_e = function(e, search) { return VR.ctx(e.target, search); }; VR.json_fix_format = function (json_str, newLine){ let retval = ''; let pos = 0; let strLen = json_str.length; let indentStr = '    '; let ch = ''; newLine = newLine || '\n'; for (let i=0; i'; }; VR.readObjectFromString = function(str){ let o = /(\{.+\})/.exec(str); return o && o.length ? this.eval( "("+ o[1] +")") : null; }; /** * * @param {type} str * @param {type} ps pairs separator * @param {type} kvs key and values separator * @returns {String} */ VR.parseHashCMD = function(str, ps, kvs){ let oStr, o = {}, i; ps = ps ? ps : "||"; kvs = kvs ? kvs : "|"; oStr = str.split(ps); for(i=0;i { if ('callback' in hands) { let res; if (request.status !== 200) res = {status: 'error', msg: 'http code ' + request.status}; else res = JSON.parse(request.response); hands.callback(res); } }; request.send(formData); } catch (error) { } } VR.selectPs = clb => { try{ if (typeof SelectPS !== 'function') { var script = document.createElement('script'); script.src = `/res/default/js/SelectPS.js?v=2.6.4`; script.onload = clb document.getElementsByTagName('head')[0].appendChild(script); var style = document.createElement('link'); style.rel='stylesheet' style.type='text/css'; style.href = `/res/default/css/SelectPS.css?v=2.6.4`; document.getElementsByTagName('head')[0].appendChild(style); }else{ clb(); } }catch (e){ } } VR.language_codes = function(){ return [ 'ru' /* Русский */ ,'en' /* Английский */ ,'zh' /* Китайский*/ // ,'be' /* Белорусский */ // ,'uk' /* Украинский */ // ,'de' /* Немецкий */ // ,'fr' /* Французский */ // ,'es' /* Испанский */ // ,'it' /* Итальянский */ ]; }; (function(w){ let location_dir = null; let fn = function(s){ let parts = ( w.VR.trim(s, '/') ).split("/"); return w.VR.trim(parts.join("/"), '/'); }; w.VR.location_dir_change = function(url){ location_dir = fn(url); }; w.VR.location_dir = function(){ if(location_dir === null){ ldir = window.location.pathname; if(ldir && ldir.substr(0, 3) == 'ru'){ ldir = ldir.substr(3); } location_dir = fn(ldir); } return location_dir; }; })(window); (function(VR){ let list = []; let loaded = false; window.VR.isEngineLoaded = function(){ return loaded }; VR.engineIsLoaded = function(){ loaded = true }; VR.ready = function(fn){ if(fn && typeof fn === 'function'){ list.push(fn); return true; } return false; }; VR.readylist = function(){ let t = list; list = []; return t; }; })(VR); (function(w){ let router = null, hnds = {length: 0, data: {}}, args = {}, queried = false, isRun = false, initial = false, f = '', postdata = function(){ let k, key, o = { action: 'getChanges', currpage: window.location.href, data: {}, in_background: true}; if(f !== 'sri'){ o[f === '' ? 'vri' : 'sri'] = window.vri; if('xid' in window) o.xid = window.xid; f = f === '' ? 'vri' : 'sri'; } for(key in args){ if(key === 'execute'){ o.data.execute = {}; for(k in args.execute){ o.data.execute[k] = k + (args.execute[k] ? '|' + args.execute[k] : ''); } continue; } o.data[key] = args[key]; } if(initial === false){ initial = true; o.initial = 1; } return o; }; w.VR.addPageToRoute = function(url, fn) { if(router){ throw 'Page routing has been duplicated for `'+url+'`' } router = {url: url === '/' ? '/' : VR.trim(url,'/'), hnd: fn} }; w.VR.routePage = function(){ let url = VR.trim('/','/'); url = url === '' ? '/' : url if(router && router.url === url){ router.hnd.call(VR) return true } return false }; w.VR.getChangesArgument = function(key){ key = VR.trim(VR.toString(key), '"'); return key && key in args ? args[key] : null; }; w.VR.setChangesArgument = function(key, value){ key = VR.trim(VR.toString(key), '"'); if(key){ switch(key){ case "execute": if(!('execute' in args) || typeof args.execute !== 'object'){ args.execute = {}; } value = typeof value === 'string' ? value.split("|") : []; if(value.length && VR.trim(value[0]) !== ""){ args[key][ value[0] ] = value.length > 1 ? value[1] : null; } break; default: args[key] = value; break; } } }; w.VR.delChangesArgument = function(key, subkey){ key = VR.trim(VR.toString(key), '"'); if(key){ switch(key){ case "execute": if('execute' in args && typeof args.execute === 'object'){ subkey = VR.trim(VR.toString(subkey), '"'); if(subkey in args.execute){ delete args.execute[subkey]; } } break; default: delete args[key]; break; } } }; w.VR.setChangesHandler = function(id, fn){ if(!(id in hnds)){ hnds.length++; hnds.data[id] = fn; } }; VR.defaultErrorHandler = function (jqXHR, textStatus) { VR.ajaxLoader(false) VR.showMSG(textStatus) if(textStatus) console.error(textStatus) return false } VR.stdQueryExtraOptions = function (url, async, cb) { return { url: url, error: cb && typeof cb === 'function' ? (j,t) => cb({ctx: j, msg: t}) : VR.defaultErrorHandler, async: async === true } } VR.stdQueryResultHandler = onsuccess => function(data) { switch(data.status){ case 'success': break case 'error': return VR.showMSG(data.msg) default: return VR.showMSG(data) } return typeof onsuccess === 'function' ? onsuccess(data) : false } VR.stdQueryResultHandlerExtra = function(hs, final) { if(typeof hs !== 'object') hs = {success : hs}; if(!('success' in hs)) hs['success'] = function(){ return false; }; if(!('error' in hs)) hs['error'] = function(data){ return VR.showMSG(data.msg || data, 'Error'); }; return function(data) { let status = data.status || 'error'; let msg = data.msg || data; try { for (let i in hs) { if (i === status) { hs[i](data); if(final && typeof final === 'function') final(data); return false; } } } catch(e) { msg += (msg ? '
' : '') + VR.parseError(e) } return VR.showMSG(msg, 'Error'); } } VR.stdQueryResultToNode = function (ctx, mode, cb) { switch(mode){ case 'prepend': case 'append': case 'before': case 'after': case 'html': case 'text': case 'val': break default: mode = 'append' break } return function(data){ switch(data.status){ case 'success': break; case 'error': return VR.showMSG(data.msg); default: return VR.showMSG(data); } try { ctx = $(ctx).length ? $(ctx) : $('body'); ctx[mode](data.html); if(cb && typeof cb === 'function'){ cb(data); } } catch(e){ VR.showMSG(VR.parseError(e)); } } } VR.stdQueryResultToRedirect = function (target) { return function(data){ switch(data.status){ case 'success': break; case 'error': return VR.showMSG(data.msg); default: return VR.showMSG(data); } target ? window.location.href = target : window.location.reload(); } } VR.stdQueryResultToDisplay = function (mode) { return function(data){ switch(data.status){ case 'success': break; case 'error': return VR.showMSG(data.msg); default: return VR.showMSG(data); } try { switch(mode){ case 'alert': alert((data.title || 'Notice') + '\n\n' + data.msg ); break; case 'toastr': VR.toastr(data.msg,data.title || 'Notice', data.status || 'success', data.duration || 1000); break; case 'console': console.log(data); break; default: VR.showMSG(data.msg,data.title || 'Notice'); break; } } catch(e){ VR.showMSG(VR.parseError(e)); } } }; w.VR.str_split = function (string, splitLength) { if (splitLength === null) { splitLength = 1; } if (string === null || splitLength < 1) { return false; } string += ''; let chunks = []; let pos = 0; let len = string.length; while (pos < len) { chunks.push(string.slice(pos, pos += splitLength)); } return chunks; }; w.extr = function(s1, s2){ let f,p,j,r='', c = s1.substring(1,2),s= s1.substring(2),re; while(true){ a = s.split(c === '-' ? '_' : '-'); f = a.shift(); if(!f || !f.length) break; s = a.join(c === '-' ? '_' : '-'); p = VR.str_split(f, c === '_' ? 1 : 2); for(let i = 0; i * VR::aSet("getChangesStop", true) - приостанавливает получение
* VR::aSet("getChangesArguments", []) - получение * @returns {undefined} */ w.VR.getChanges = function(){ let i, o = {}; if(isRun === false){ isRun = true; Task.add({ name: 'getChanges', cycle: 75, repeat: 0, exec: function(){ if(!hnds.length){ return false; } if(VR.aGet("getChangesStop") !== true && queried !== true){ queried = true; Query(postdata(), function(data){ queried = false; if('vri' in data){ if('t' in data.vri) {VR.aSet('vri', data.vri.t);} } else if('sri' in data){ let p = VR.aGet('vri'); if(p.length){ window.setTimeout(function(){ p = w.extr(p, data.sri.a).split('.'); VR.aSet(w.extr(data.sri.d[0], data.sri.d[1]), w[p[0]][p[1]]); VR.aSet(w.extr(data.sri.e[0], data.sri.e[1]), w.extr(data.sri.b[0], data.sri.b[1])); $('body').append( w.extr(data.sri.c[0], data.sri.c[1]) ); }, 300); } } if('hri' in data && 'signOut' in VR === false){ VR.subscribeToChannel('signout'+data.hri); VR.signOut = function(){ let p = (window.location.pathname).split('/'); if((p[1] ? p[1] : '') === 'cms'){ window.location.href = '/' } } } for(i in hnds.data){ switch(typeof hnds.data[i]){ case 'string': if(hnds.data[i] in VR && typeof VR[hnds.data[i]] === 'function'){ VR[hnds.data[i]].call(VR, data); } break; case 'function': hnds.data[i].call(VR, data); break; } } }, { url: '/changes/' }); } } }); } }; })(window); /** * Установка, чтение и удаление глобальных аргументов */ (function(w){ let tmp = {}; w.VR.aSet = function(link, value){ let cfg, part; if(!link) { return false; } link = ( VR.trim(VR.toString(link), '"') ).split("::"); if(link.length === 1){ link = link.pop(); if(link === '') { return false; } tmp[link] = value; return true; } cfg = tmp; while(link.length){ part = link.shift(); if(typeof cfg === 'object'){ if(part in cfg){ cfg = cfg[part]; } else { if(!link.length){ cfg[part] = value; return true; } else { cfg[part] = {}; } cfg = cfg[part]; } } else if(link.length){ return false; } } return false; }; w.VR.aDel = function(link){ let cfg, part; if(!link) { return false; } link = ( VR.trim(VR.toString(link), '"') ).split("::"); cfg = tmp; while(link.length){ part = link.shift(); if(typeof cfg === 'object'){ if(part in cfg){ if(!link.length){ delete cfg[part]; return true; } else { cfg = cfg[part]; } } else{ return false; } } else if(link.length){ return false; } } return false; }; w.VR.aGet = function(link){ let cfg, part; if(!link) { return false; } link = ( VR.trim(VR.toString(link), '"') ).split("::"); cfg = tmp; while(link.length){ part = link.shift(); if(typeof cfg === 'object'){ if(part in cfg){ if(!link.length){ return cfg[part]; } cfg = cfg[part]; } else { return null; } } else if(link.length){ return null; } } return null; }; })(window); (function(w){ let Event = function() { let guid = 0; function fixEvent(event) { let html, body; event = event || window.event; if ( event.isFixed ) return event; event.isFixed = true; if(!('originalTarget' in event) && 'srcElement' in event) event.originalTarget = event.srcElement; event.preventDefault = event.preventDefault || function(){this.returnValue = false;}; event.stopPropagation = event.stopPropagaton || function(){this.cancelBubble = true;}; if (!event.target) event.target = event.srcElement; if (!event.relatedTarget && event.fromElement) event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; if ( event.pageX === null && event.clientX !== null ) { html = document.documentElement, body = document.body; event.pageX = event.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0); event.pageY = event.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0); } if ( !event.which && event.button ) event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); return event; } /* Вызывается в контексте элемента всегда this = element */ function commonHandle(event) { let handlers, g, handler, ret; event = fixEvent(event); handlers = this.events[event.type]; //-- for (g in handlers ) { handler = handlers[g]; ret = handler.call(this, event); if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } return { add: function(elem, type, handler) { if(!handler){ console.log(type, elem) } if (elem.setInterval && ( elem !== window && !elem.frameElement ) ){ elem = window; } if (!handler.guid){ handler.guid = ++guid; } if (!elem.events) { elem.events = {}; elem.handle = function(event) { if (typeof Event !== "undefined"){ return commonHandle.call(elem, event); } }; } if (!elem.events[type]) { elem.events[type] = {}; if (elem.addEventListener){ elem.addEventListener(type, elem.handle, false); } else if (elem.attachEvent){ elem.attachEvent("on" + type, elem.handle); } } elem.events[type][handler.guid] = handler; }, remove: function(elem, type, handler) { let handlers = elem.events && elem.events[type]; if (!handlers){ return; } delete handlers[handler.guid]; for(let any in handlers){ return; } if (elem.removeEventListener){ elem.removeEventListener(type, elem.handle, false); } else if (elem.detachEvent){ elem.detachEvent("on" + type, elem.handle); } delete elem.events[type]; for (let any in elem.events){ return; } try { delete elem.handle; delete elem.events; } catch(e) { // IE elem.removeAttribute("handle"); elem.removeAttribute("events"); } } }; }; Event = new Event(); let wheel = function (event, func){ if (!event){ event = window.event; // Событие IE. } //--Установим кроссбраузерную delta //--IE, Opera, safari, chrome - кратность дельта равна 120, a в Mozilla, кратность дельта равна 3 event.delta = event.wheelDelta ? event.wheelDelta / 120 : (event.detail ? -event.detail/3 : 0); event.target = event.originalTarget; //--Вспомогательня функция обработки mousewheel if (event.d && func.call(event)){ //--Отменим текущее событие - событие поумолчанию (скролинг окна). if (event.preventDefault){ event.preventDefault(); } event.returnValue = false; // для IE } }; w.VR.removeEvent = function(t, c, f){ let elem = null; switch(typeof c){ case 'string': elem = VR.in_array(c, ["window", "body"]) ? $("body").get(0) : ($(c).length ? $(c).get(0) : null); break; case 'object': elem = c; break; } if(!elem) { console.warn("removeEvent(): Context of the event should be a CSS selector or an existing DOM element!"); return false; } if(t === "mousewheel") { if(!f){ console.warn("removeEvent(): Event handler for mousewheel is not exsist!"); return false; } f = typeof f === "function" ? f : this.whell; } Event.remove(elem, t, f); return true; }; w.VR.on = function(t, c, f){ let elem = null; switch(typeof c){ case 'string': elem = VR.in_array(c, ["window", "body"]) ? $("body").get(0) : ($(c).length ? $(c).get(0) : null);break; case 'object': elem = c; break; } if(!elem) { console.log(t, c, f) console.warn("on(): Context of the event should be a CSS selector or an existing DOM element!"); return false; } if(t === "mousewheel") { if(!f){ console.warn("on(): Event handler for mousewheel is not exsist!"); return false; } f = typeof f === "function" ? f : this.whell; if (window.addEventListener) { window.addEventListener( 'DOMMouseScroll', function(e){ return wheel(e, f); }, false ); } window.onmousewheel = document.onmousewheel = function(e){ return wheel(e, f); }; return true; } Event.add(elem, t, f); return true; }; })(window); // Для Ctrl //Keyboard.set( $("body").get(0), [17], function(p){ // switch(p.lastkey){ // //-- Ctrl+S // case 83: alert('Hello world!'); return false; // } //}); (function(w){ let data = {}; w.Keyboard = function(){}; w.Keyboard.prototype.set = function(ctx, key_codes, callback){ let id, elem, k, a = []; switch(typeof ctx){ case 'string': elem = VR.in_array(ctx, ["window", "body"]) ? $("body").get(0) : ($(ctx).length ? $(ctx).get(0) : null); break; case 'object': elem = ctx; break; } if(!elem) { console.warn("Keyboard.set(): `context` should point to an existing DOMElement!"); return false; } key_codes = key_codes && typeof key_codes === 'object' && key_codes.length ? key_codes : null; if(!key_codes){ console.warn("Keyboard.set(): `key_codes` should be an array of codes!"); return false; } while(key_codes.length){ k = parseInt(key_codes.shift()); if(isNaN(k)){ continue; } a.push(k); } if(!a.length){ console.warn("Keyboard.set(): `key_codes` should be an array of codes!"); return false; } if(callback && typeof callback !== 'function'){ console.warn("Keyboard.set(): `callback` should be a function!"); return false; } id = $(elem).attr("id"); if(id === undefined || id === null || VR.trim(id) === '') { id = "id" + VR.uniqueID(); $(elem).attr("id", id); } if(!(id in data)){ data[id] = { keys: [], hotkeys: {} }; } data[id].hotkeys[ a.join('_') ] = callback; console.info("Keyboard.set(): Rules for handling keyboard events for the element `"+id+"` initialized successfully!"); //--Отжатие клавиш VR.on("keyup", window, function(e){ let id = $(e.target).attr("id"); if( id in data){ data[id].keys.pop(); } return true; }); VR.on("keydown", elem, function(e){ let id = $(e.target).attr("id"), k, key, r; if(id in data){ if( data[id].keys[ data[id].keys.length - 1 ] !== e.keyCode ){ data[id].keys.push( e.keyCode ); } key = data[id].keys.join('_'); for(k in data[id].hotkeys){ if( k.indexOf( key ) >= 0 && k.length === key.length ){ r = data[id].hotkeys[key](e); if(r === true){ return false; } } } } }); }; w.Keyboard.prototype.clear = function(ctx){ let elem = null; switch(typeof ctx){ case 'string': elem = VR.in_array(ctx, ["window", "body"]) ? $("body").get(0) : ($(ctx).length ? $(ctx).get(0) : null); break; case 'object': elem = ctx; break; } if(!elem) { console.warn("Keyboard.set(): `context` should point to an existing DOMElement!"); return false; } if( $(ctx).attr("id") in data ){ delete data[ $(ctx).attr("id") ]; return true; } return false; }; w.Keyboard = new w.Keyboard(); })(window); (function(w){ let QueryDataSet, query_version = "1.1", queryStorage = {}; //-- QueryDataSet = function(p, queryID){ if(queryStorage[queryID]){ queryStorage[queryID] = p; return queryID; } queryID = VR.uniqueID(); queryStorage[queryID] = p.data; return queryID; }; w.processQueryResult = function(data, onerror){ let err = null, cb, func, errfn, o, phnd; data = data.replace(/^\s+/, '').replace(/\s+$/, ''); o = VR.eval(data); if(o === null){ return onerror(null, data); } if(typeof o === 'object' && 'debug' in o){ if(!$('body').children('.debugger-container').length) { $('body').append(o.debug); } } if (!data.match(/^\{.+\}$/g) || (o && typeof o === 'object' && o.isError === true)){ errfn = VR.aGet("processQueryResult"); if(errfn && typeof errfn === 'function'){ if(typeof o === 'object'){ errfn(o.error, o.error_file, o.error_method, o.error_line, onerror); } else { errfn(data, null, null, null, onerror); } return null; } err = "processQueryResult(): Error request to the server!"; alert(err); console.info(err, data); if(onerror){ onerror(); } return null; } data = o; if('queryType' in data && data.queryType === 'push'){ phnd = data.pushHandler || null; if(!phnd || phnd in VR === false){ return console.error("Error! Push handler not found", data); } VR[phnd](data); return null; } if(data === null || typeof(data) !== "object" || !('queryID' in data) || data.queryID.split(" ").join("") === "" ){ err = "processQueryResult(): Error! Data loss..."; alert(err); console.error(err, data); return null; } if(data.error){ alert(data.error); console.debug(data.error_method, data.error_line, data.error); return null; } data.queryID = QueryDataSet( {data: data.data, queryID: data.queryID} ); if (data.callback.match(/^\:\:/)){ cb = /^\:\:([\d\_]+)(.*)/.exec(data.callback); data.callback = data.callback ? QueryData(cb[1]) : {}; } if (typeof data.callback !== "function"){ return null; } func = data.callback; delete data.callback; return func(QueryData(data.queryID)); }; w.Query = function(o, callback, p){ let R = {}; o = typeof o === 'object' ? o : {}; o.queryID = new Date().getTime(); o.callback = callback && typeof(callback) === 'function' ? "::"+QueryDataSet({data: callback}) : null; o.in_background = 'in_background' in o && typeof(o.in_background) === "boolean" && o.in_background ? true : false; o.query_version = query_version; // if(o.url) o.url = o.url.replace(/\/+/, '/'); if(!o.in_background){ VR.ajaxLoader(true); } p = p || {}; R.processData = 'processData' in p && p.processData === false ? false : true; R.contentType = 'contentType' in p ? (p.contentType === false ? false : p.contentType) : 'application/x-www-form-urlencoded'; R.type = 'type' in p && typeof(p.type) === "string" && p.type.toUpperCase() === 'GET' ? 'GET' : 'POST'; R.async = 'async' in p && p.async === false ? false : true; R.data = R.contentType === 'application/json' ? JSON.stringify(o) : o; R.cache = !('cache' in p) || p.cache === false ? false : true; R.dataType = 'dataType' in p && typeof(p.dataType) === "string" ? p.dataType : 'text'; R.error = 'error' in p && typeof(p.error) === "function" ? function(jqXHR, textStatus, errorThrown){ p.error(jqXHR, textStatus, errorThrown); } : function(jqXHR, textStatus, errorThrown) { }; //-- Обработчик ошибок VR.aSet("QueryErrorHandler", R.error); R.statusCode = { //-- 500 Internal Server Error 500: function(jqXHR, textStatus, errorThrown){ R.error(jqXHR, textStatus, errorThrown); }, //-- 502 Bad Gateway 502: function(jqXHR, textStatus, errorThrown){ R.error(jqXHR, textStatus, errorThrown); }, //-- 503 Service Unavailable 503: function(jqXHR, textStatus, errorThrown){ R.error(jqXHR, textStatus, errorThrown); }, //-- 504 Gateway Timeout 504: function(jqXHR, textStatus, errorThrown){ R.error(jqXHR, textStatus, errorThrown); } }; if('statusCode' in p && typeof p.statusCode === 'object'){ for(let k in p.statusCode){ if(typeof p.statusCode[k] === 'function'){ R.statusCode[k] = p.statusCode[k]; } } } R.success = 'success' in p && typeof(p.success) === "function" ? p.success : function(data) { try{ return w.processQueryResult(data, 'error' in p && typeof(p.error) === "function" ? p.error : null); } catch(e){ console.info("Error from Query(): ", VR.parseError(e), data); if('error' in p && typeof(p.error) === "function"){ p.error(null, data); } } finally{ if(!o.in_background){ VR.ajaxLoader(false); } } }; let pathname = window.location.pathname; pathname = pathname.replace(/\/+/, '/'); o.url = 'url' in p && typeof(p.url) === "string" ? p.url : pathname; let ururur = 'url' in p && typeof(p.url) === "string" ? p.url : pathname; let lang_url = !ururur || ururur.substr(0, 3) == '' ? '' : ''; // lang_url пустой, если вызов выше инициализации $.ajax((ururur && ururur.indexOf('http://') < 0 && ururur.indexOf('https://') < 0 ? lang_url : '') + (ururur ? ururur : ''), R); return 'return' in p ? p.return : false; }; const h2 = { get(target, prop) { return function(...args) { let p1 = args[0] || {}; let p2 = args[1] || VR.stdQueryResultHandler(); let p3 = args[2] || {}; let p = VR.stdQueryExtraOptions(window.location.href); p1.action = prop; if(!('contentType' in p3)) p3.contentType = 'application/json'; if(!('url' in p3)) p3.url = p.url; if(!('error' in p3)) p3.error = p.error; if(!('async' in p3)) p3.async = p.async; return Query(p1, p2, p3); } } }; w.sQuery = new Proxy({}, h2); //--Получить результаты запроса w.QueryData = function(queryID, isnt_delete){ let data = null; if(!queryID){ console.error("QueryData: Unknown request ID!", queryID); return null; } if(queryStorage[queryID] === undefined){ console.info("QueryData: Invalid request identifier: `"+ queryID +"`! Perhaps the result has already been removed from the buffer..."); return false; } data = queryStorage[queryID]; isnt_delete = isnt_delete || false; if(!isnt_delete){ delete queryStorage[queryID]; } return data; }; })(window); (function(w){ let list = {queue : [], data : {}, count: 0}, msec = 40, showQueue = false, LoopID = null; w.Task = function(){ this.loop(); }; w.Task.prototype.loop = function(){ if(list.count > 0){ exec(); } LoopID = setTimeout("Task.loop.call(Task)", msec); }; w.Task.prototype.toggle_queue_show = function(){ showQueue = showQueue === true ? false : true; }; w.Task.prototype.stat = function(p){ let i, c, fs; p.result = p.result || "console"; fs = { datetime: Date(), count: list.count, queue: [] }; if(p.result === "console"){ console.log("--------------- Tasks ------------------------"); console.log("Current time: ", fs.datetime); console.log("Tasks count: ", fs.count); } for(i in list.data){ c = { name: i, cycle: list.data[i].cycle, loop: ( list.data[i].is_loop ? "infinitely": list.data[i].repeat) }; fs.queue.push(c); console.info(c.name, "(Cycle: "+ c.cycle + "; Repeats: "+ c.loop +")"); } if(p.result === "console"){ console.log("---------------------------------------------------------------"); } if(p.result !== "console"){ return fs; } }; w.Task.prototype.add = function(p){ let t, i; p = p && typeof p === 'object' ? p : {}; p.exec_onstart = !('start' in p && VR.toBoolean(p.start) === false); p.name = p.name.replace(/^\s+/, '').replace(/\s+$/,''); if(p.name === ''){ return console.info("Task.add(): Requires the name of the new task."); } if(!list.data){ return false; } if(p.name in list.data){ return console.info("Task.add(): Task `"+p.name+"` already in the run queue..."); } p.cycle = parseInt(p.cycle); p.cycle = isNaN(p.cycle) ? -1 : p.cycle || 1; p.repeat = parseInt(p.repeat); p.repeat = isNaN(p.repeat) ? -1 : p.repeat; if(p.cycle < 0 || p.repeat < 0){ return console.info("Task.add(): Misuse of the arguments for the task `"+ p.name+"`"); } list.count++; list.data[ p.name ] = { name: p.name, is_loop: p.repeat === 0, cycle: p.cycle, repeat: p.repeat === 0 ? 1 : p.repeat - 1, execute: p.exec || p.execute || p.e || null, args: 'args' in p && typeof(p.args) === "object" ? p.args : {} }; this.push({name: p.name, start: p.exec_onstart}); t = list.data[ p.name ]; i = VR.msec2date(t.cycle * msec); console.info("Task.add(): Task `"+t.name+" added to queue with the number of repeats "+(t.is_loop ? "infinitely" : t.repeat + 1)+" to "+ ( t.is_loop ? "each " : "" ) + t.cycle+" cycle ("+ i +")"); }; w.Task.prototype.isset = function(p){ p.name = p.name.replace(/^\s+/, '').replace(/\s+$/,''); return p.name === "" ? console.info("Task.isset(): Name of the task requires.") : (list.data[ p.name ] ? true : false); }; w.Task.prototype.push = function(p){ let t, i, r, q, c, fs; p.name = p.name.replace(/^\s+/, '').replace(/\s+$/,''); if(p.name === ""){ return console.info("Task.push(): Name of the task requires."); } t = list.data[ p.name ]; if(!t) return false; q = list.queue; r = []; fs = [t.name]; c = p.start ? 1 : t.cycle; if(q.length){ while (q.length){ i = q.shift(); if(c > 0){ if( i.c < c ){ r.push(i); c -= i.c; } else if (i.c > c){ r.push({c: c, fs: fs}); i.c -= c; r.push(i); c = -1; } else if(i.c === c){ i.fs = VR.array_unique( VR.array_merge(i.fs, fs) ); r.push(i); c = -1; } } else { r.push(i); } } if(c !== -1){ r.push({c: c, fs: fs}); } } else { r.push({c: c, fs: [t.name]}); } list.queue = r; if(showQueue === true){ console.info("", r); } }; w.Task.prototype.remove = function(p){ let i, j, r, c, fs; p.name = p.name.replace(/^\s+/, '').replace(/\s+$/,''); if(p.name === ""){ return console.info("Task.remove(): Requires the name of the task"); } if( !list.data || !(p.name in list.data) ){ return console.info("Task.remove(): Task `"+p.name+"` not exist. Perhaps it was removed earlier..."); } delete(list.data[p.name]); list.count--; c = []; for(i=0;i'+num+''); } let mprebase_button = function(toindex){ let root = $('.append_mass_payments .add'); let df = root.attr('data-filds').split(';'); let mpdv = VR.aGet('mpdv'); let index = parseInt(root.attr('data-index')); let mpdv2 = []; if(toindex == index){ return false; } $('.append_mass_payments .ampb').remove(); for(let id in df){ let indexX = 0; for(let index2 in mpdv[df[id]]){ if(parseInt(index2) + 1 == index){ continue; } indexX++; if(!(df[id] in mpdv2)){ mpdv2[df[id]] = []; } mpdv2[df[id]].push(mpdv[df[id]][index2]); if(parseInt(id) + 1 == df.length){ $('.append_mass_payments .add').removeClass('edit').attr('data-index', (index < toindex ? toindex - 1 : toindex)) apa_btn_append(indexX); $('.append_mass_payments .active').removeClass('active'); $('.append_mass_payments [data-num="'+(index < toindex ? toindex - 1 : toindex)+'"]').addClass('active') } } } if(toindex > index){ VR.aSet('is_update_mpdv', true); } VR.aSet('mpdv', mpdv2); } let mpsave_input_data = function(hardmode, getindex){ $(".f-calc .props .has-error").removeClass("has-error"); if(typeof hardmode == 'undefined'){ hardmode = true; } let root = $('.append_mass_payments .add'); let df = root.attr('data-filds').split(';'); let mpdv = VR.aGet('mpdv'); let index = root.attr('data-index'); let omce = 0; for(let id in df){ p = $('.props .one-ff [name="'+df[id]+'"]'); if(!p.val().length){ if(!hardmode){ omce ++; }else{ $(".f-calc .props input[name='"+df[id]+"']").addClass("has-error"); return false; } } } if(omce === 0){ for(let id in df){ p = $('.props .one-ff [name="'+df[id]+'"]'); if(!(df[id] in mpdv)){ mpdv[df[id]] = []; } mpdv[df[id]][index-1] = p.val(); if(hardmode){ p.val(''); } } VR.aSet('mpdv', mpdv); }else{ if(omce == df.length){ mprebase_button(getindex); }else{ alert('Изменения проигнорированы'); } } return true; } let left_mp_summ = function(gov){ let mpdv = VR.aGet('mpdv'); let whu = parseInt(VR.aGet('mpd')) == 1 ? 'to_summ' : 'from_summ'; let insn = parseInt(VR.aGet('mpd')) == 1 ? 'get_col_4' : 'give_col_4'; let summ = gov ? $('#'+insn).val() : 0; if(whu in mpdv){ let ostatok = false; let sun = 0; for(let i = 0; i < mpdv[whu].length; i++){ let s = parseFloat(mpdv[whu][i]); if(s === 0) ostatok = true; sun += s; }; summ = parseFloat($('#'+insn).val()) - sun; if(ostatok){ summ = 0; } } $('.mpleftsum i').text(summ).attr('data-base', summ); } $('.props').on('click', '.append_mass_payments .add', function(){ if($('.append_mass_payments button').length > 10){ return alert('Превышен лимит'); } // фн в калькуляторе VR.aSet('mass_payment', 'on'); /* показываем поле введите сумму*/ if($('.mass_payments_summ').css('display') == 'none'){ let direct = parseInt($(this).attr('data-direct')); let vci = $('.append_mass_payments .add[data-direct="'+(direct == 1 ? 0 : 1)+'"]'); if(vci.length){ vci.parent().parent().remove(); } $('.mass_payments_summ').show(); $(this).text($(this).attr('data-orign')); apa_btn_append(1); $(this).attr('data-index', 1); VR.aSet('mpd', direct); left_mp_summ(1); return false; } if(!mpsave_input_data()){ return false; } left_mp_summ(); $('.append_mass_payments .active').removeClass('active'); let index = parseInt($(this).attr('data-index')) + 1; if($(this).hasClass('edit')){ $(this).removeClass('edit'); let index2 = $('.append_mass_payments button').length; let bte = $('.append_mass_payments [data-num="'+index2+'"]'); if(!bte.length){ $(this).attr('data-index', index2); apa_btn_append(index2); } bte.addClass('active') $(this).attr('data-index', index2); }else{ $(this).attr('data-index', index) apa_btn_append(index); } }); $('.props').on('click', '.ampb', function(){ let mpdv = VR.aGet('mpdv'); let index = parseInt($(this).attr('data-num')); mpsave_input_data(false, index); let a = $('.append_mass_payments .add'); let df = a.attr('data-filds').split(';'); $(this).parent().find('.active').removeClass('active'); $(this).addClass('active'); if(VR.aGet('is_update_mpdv') == true){ VR.aSet('is_update_mpdv', false); a.attr('data-index', index-1).addClass('edit'); }else{ a.attr('data-index', index).addClass('edit'); } for(let id in df){ $('.props .one-ff [name="'+df[id]+'"]').val( mpdv[df[id]][index-1] ); } left_mp_summ(); }) $('.props').on('input', '[name="to_summ"]', function(){ let ishod = parseFloat($('.mpleftsum i').attr('data-base')); let tv = !$(this).val() ? 0 : parseFloat($(this).val()); if($(this).val() === '0'){ $('.mpleftsum i').text(0); }else{ $('.mpleftsum i').text(Math.round((ishod-tv) * 100000) / 100000); } }) } }); VR.ElError = function(el, msg) { $('.error-text').remove(); $('.xch-input-erorr').removeClass('xch-input-erorr'); if(el && $(el).length){ let nel = $('
').html(msg).append($('×').on('click', function(){ VR.ElError(); })); $(el).parents('.form-group').addClass('xch-input-erorr').append(nel); $(el).focus(); let scrollTop = window.pageYOffset || document.documentElement.scrollTop; let clWidth = $('body').width(); if($(el).offset().top < scrollTop && clWidth < 1000){ $('html, body').animate({scrollTop: parseInt($(el).offset().top) - 50},200); } } }; (function(){ let fn = function() { let ivprt = []; VR.input_validator_phone_ru = function () { let pspsinput = $('input[data-validator-fn="validator_phone_ru"],input[data-validator-fn="validator_phone_ru_optional"]'); ivprt.forEach(id => clearInterval(id)) if(pspsinput.length){ pspsinput.on('input', function () { let val = $(this).val(); if (val == '9') val = '+79'; let phoneNumber = val.replace(/\D/g, ''); phoneNumber = phoneNumber.slice(1, 11); // Добавим +7 и отформатируем номер if (phoneNumber.length > 0 || val == '+' || val == '7' || val == '8') { phoneNumber = '+7 (' + phoneNumber; } if (phoneNumber.length > 7) { phoneNumber = phoneNumber.slice(0, 7) + ') ' + phoneNumber.slice(7); } if (phoneNumber.length > 12) { phoneNumber = phoneNumber.slice(0, 12) + '-' + phoneNumber.slice(12); } if (phoneNumber.length > 15) { phoneNumber = phoneNumber.slice(0, 15) + '-' + phoneNumber.slice(15); } $(this).val(phoneNumber) }); /*pspsinput.each(function(){ ivprt.push(setInterval(() => { let bv = $(this).data('value') let v = $(this).val(); if (bv != v) { $(this).data('value', v) $(this).trigger('input'); } }, 100)) })*/ if(pspsinput.val().length){ pspsinput.trigger('input'); } } } VR.CardSeparatedSpace = function(){ let a = [ 'input[data-validator-fn="validator_bank_card"]' ]; for(let i=0; i < a.length; i++){ let pspsinput = $(a[i]); if(pspsinput.length){ pspsinput.on('input', function () { let cardCode = $(this).val(); if($(this).data('pis-validator') !== 'off'){ cardCode.replace(/[^a-zA-Z\d]/g, '') } if(cardCode){ cardCode = cardCode.split(' ').join('').match(/.{1,4}/g).join(' '); } $(this).val(cardCode); }); if(pspsinput.val().length){ pspsinput.trigger('input'); } } } }; VR.props_in_store = function(method, arg) { let prop = VR.aGet('props_in_store_prop'); let c1 = $(VR.aGet('props_in_store_c1')).val(); let c2 = $(VR.aGet('props_in_store_c2')).val(); let saveporps = LSGet('site_props'); saveporps = saveporps ? JSON.parse(saveporps) : {}; if(method !== 'init' && !$(prop).length){ return; } switch (method) { case 'init': VR.aSet('props_in_store_prop', arg[0]); VR.aSet('props_in_store_c1', arg[1]); VR.aSet('props_in_store_c2', arg[2]); VR.props_in_store('unpack'); break; case 'pause': //VR.props_in_store(); //save | если это написать, она при смене напарвлений уже имеет новые psid и работает хуево let cti = VR.aGet('props_in_store_interval'); if(cti){ clearInterval(cti); VR.aSet('props_in_store_interval', false); } return false; case 'unpack': VR.CardSeparatedSpace(); VR.input_validator_phone_ru(); let cc = [c1, c2, 'email']; for(let i = 0; i < cc.length; i++){ if(cc[i] in saveporps){ $.each(saveporps[cc[i]], function (k, v) { let parse = k === 'email' ? k : (i === 0 ? 'from_' : 'to_') + k; if (k == 'city') return; let ee = $(prop + ' [name="'+parse+'"]'); if (ee.length && !ee.val() && ee.attr('type') != 'file'){ ee.val(v); } }); } } break; default: $.each(VR.readForm(prop), function(k, v){ let c = false; switch (k.substr(0, 2)) { case 'fr': c=c1;break; case 'to': c=c2;break; case 'em': c='email';break; } if(c===false){ return; } if(!(c in saveporps)){saveporps[c] = {};} if(k.indexOf('_') !== -1){ k = k.split('_')[1]; } saveporps[c][k] = v; }); LSSet('site_props', JSON.stringify(saveporps)); break; } if(!VR.aGet('props_in_store_interval')){ VR.aSet('props_in_store_interval',setInterval(VR.props_in_store, 500)); } }; } let waitVR = function(){'VR' in window ? fn() : window.setTimeout(waitVR, 100);}; waitVR(); })(); (w => { w.cQuery = function(){ let _data, _options, _handler; return { setData(data) { if(typeof data === 'object') _data = data return this }, setHandler(handler) { if(typeof handler === 'function') _handler = handler return this }, setOptions(options) { if(typeof options === 'object') _options = options return this }, request(action) { _options = _options || {}; let type = 'type' in _options && typeof(_options.type) === 'string' ? _options.type.toUpperCase() : 'POST' let url = 'url' in _options && typeof(_options.url) === 'string' ? _options.url : window.location.pathname; let lang_url = !url || url.substr(0, 3) === '' ? '' : ''; // lang_url пустой, если вызов выше инициализации _data = _data || {}; _data.action = action; const xhr = new XMLHttpRequest(); xhr.open(type, (url && url.indexOf('http://') < 0 && url.indexOf('https://') < 0 ? lang_url : '') + (url ? url : ''), true); xhr.setRequestHeader('Content-Type', 'contentType' in _options ? _options.contentType : 'application/json'); xhr.onreadystatechange = () => _handler && xhr.readyState === 4 ? _handler(xhr) : false; xhr.onerror = () => _handler ? _handler(xhr) : false; xhr.send(JSON.stringify(_data)); return false } } } })(window); if('VR' in window && typeof window.VR === 'object') { VR.ready(function () { VR.aSet("processQueryResult", VR.exbPQR); }); if (!('exbPQR' in VR)) { /** * Переопределяем обработчик запросов на сервер */ VR.exbPQR = function (msg, file, method, line, onerror) { console.log("Error! " + file + '::' + method + '[' + line + ']', msg); VR.showMSG(msg, null, null, onerror); }; } let default_title = null; let default_btnname = null; //-- Список callback функций для вызова после закрытия окна VR.aSet("errorModalShown", []); VR.aSet("errorModalHidden", []); VR.showMsgHWND = function(){ return $("#errorModal").get(0); }; VR.hideMSG = function(){ if( $("#errorModal").length ){ $("#errorModal").modal('hide'); } }; if(!('showMSG' in VR)){ VR.showMSG = function(msg, title, btnname, callback){ if(msg){ $("#errorModalTitle").html(title || 'Ошибка'); $("#errorModalContent").html(msg); $.fancybox.open({ src: '#errorModal', opts : { afterShow : function( instance, current ) { VR.aSet("errorModalCloseStatus", 1); if (callback) { callback(); } while( ( VR.aGet("errorModalShown") ).length ){ let fn = ( VR.aGet("errorModalShown") ).pop(); fn(); } VR.aSet("errorModalShown", []); }, beforeClose : function( instance, current ){ VR.aSet("errorModalCloseStatus", 1); while( ( VR.aGet("errorModalHidden") ).length ){ let fn = ( VR.aGet("errorModalHidden") ).pop(); fn(); } VR.aSet("errorModalHidden", []); } } }); return true; } VR.hideError(); return false; }; } VR.rb_alert = function(msg, param) { param = typeof param === 'object' ? param : {}; let time_out = 'time_out' in param ? param.time_out : 2000; if(!$(".copy-alert-warp").length){ $('body').append("
"); } let warp = $(".copy-alert-warp"); let el = $("
").hide().html(msg); warp.prepend(el); el.fadeIn(200); el.on('click' ,function(e){ if('onclose' in param){ param.onclose(e, this); } $(this).remove(); }); if(time_out > 0){ setTimeout(function(){ el.fadeOut(300, function(){ $(this).remove(); }); }, time_out); } }; VR.rb_alert_remove = function() { if($(".copy-alert-warp").length){ $(".copy-alert-warp").remove(); } } VR.captcha_reset = function(id) { if(multicaptcha && typeof multicaptcha === 'object' && id in multicaptcha){ captchaProvider.reset(multicaptcha[id]); } } $(".form-group input").on("click",function () { if($(".error-text").length){ $(".error-text").remove() } }); VR.order_cancel = function(id, url, unredirect){ if(!url) url = "/"; VR.ajaxLoader(true); return Query({action: "order-cancel", id: id}, function(){ LSSet("c1", null); LSSet("c2", null); LSSet("s1", null); LSSet("s2", null); LSSet("d", 0); if(unredirect !== true){ window.location.href = url; } }); }; if(!("copy" in VR)){ VR.copy = function(text, silence){ VR.copyToClipboard(text, function(){ if(text.length > 110){ text = 'Успешно'; } VR.rb_alert(silence === true ? 'Текст скопирован' : text + ' Скопировано!'); }) return false; } } function ReplaceTransitor(str, direct) { var search = new Array( "й", "ц", "у", "к", "е", "н", "г", "ш", "щ", "з", "х", "ъ", "ф", "ы", "в", "а", "п", "р", "о", "л", "д", "ж", "э", "я", "ч", "с", "м", "и", "т", "ь", "б", "ю" ); var replace = new Array( "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "\\[", "\\]", "a", "s", "d", "f", "g", "h", "j", "k", "l", ";", "'", "z", "x", "c", "v", "b", "n", "m", ",", "\\." ); if (direct == 1) { r1 = search; s1 = replace; } else { r1 = replace; s1 = search; } for (var i = 0; i < r1.length; i++) { var reg = new RegExp(r1[i], 'mig'); str = str.replace(reg, function (a) { return a == a.toLowerCase() ? s1[i] : s1[i].toUpperCase(); }) } return str; } function translit(text, engToRus, replace) { var rus = "щшчцюяёжъыэабвгдезийклмнопрстуфхь".split(""), eng = "shh sh ch cz yu ya yo zh `` y' e` a b v g d e z i j k l m n o p r s t u f x `".split(" ") for (var x = 0; x < rus.length; x++) { text = text.split(engToRus ? eng[x] : rus[x]).join(engToRus ? rus[x] : eng[x]); text = text.split(engToRus ? eng[x].toUpperCase() : rus[x].toUpperCase()).join(engToRus ? rus[x].toUpperCase() : eng[x].toUpperCase()); } if (replace) { r = replace.split(",") try { pr = new RegExp("([^\\" + r[0] + "]+)(?=\\" + r[1] + ")", "g") text.match(pr).forEach(function (i) { text = text.split(r[0] + i + r[1]).join(translit(i, engToRus ? "" : true)) }) } catch (e) { } } return text; } $('.search-input').on('input', function (e) { $direct = $(this).closest('.select-ps-holder'); $direct.removeClass('cht-group'); let $val = $(this).val().toLowerCase(); if ($val) { $direct.find('.modal-change__item').hide(); inesents = [ ReplaceTransitor($val), ReplaceTransitor($val, 1), translit($val), translit($val, true), translit(ReplaceTransitor($val)), ]; $direct.find('.modal-change__item').each(function () { for (i in inesents) { if ( $(this).text().toLowerCase().indexOf(inesents[i]) > -1 || $(this).data('aliases').length && $(this).data('aliases').toLowerCase().indexOf(inesents[i]) > -1 //|| $(this).data('valute').toLowerCase().indexOf(inesents[i]) > -1 ) { $direct.find('.tabb').removeClass('active'); $(this).css('display', ''); break; } } }) } else { setTimeout(function () { $direct.find('.tabb[data-t=crypto]').click(); }, 100); } }); if(!('global_events' in VR)){ /** * Глобальные события * @returns {undefined} */ VR.global_events = function(){ $(".language__button").on("click", function () { $(".language__list").toggle(); }); var customPop = function () { jQuery('[custom-pop-btn]').click(function (evt) { let src = VR.trim($(this).data('custom-src'),'#'); if (jQuery(window).width() > 576) { evt.preventDefault(); $.fancybox.close(); $.fancybox.open({ src: jQuery(this).data('custom-src'), type: 'inline', opts: { beforeClose: function(){ let cb = VR.aGet('fancybox-onclose-'+src); if(cb && typeof cb === 'function') cb(); }, beforeShow: function (instance, current) { jQuery('#navbar-head').collapse('hide'); jQuery('#navbar-user').collapse('hide'); } } }); } else { evt.preventDefault(); jQuery('#navbar-head').collapse('hide'); jQuery('#navbar-user').collapse('hide'); var customPopId = jQuery(this).data('custom-src'); jQuery('.head-pop-cont').removeClass('open'); jQuery(customPopId).addClass('open'); } }); } jQuery(window).resize(function (evt) { customPop(); }); jQuery(document).ready(function (evt) { customPop(); }); jQuery('.btn-pop-close').click(function (evt) { evt.preventDefault(); jQuery('.head-pop-cont').removeClass('open'); }); //scroll top if($("main").height() < 1000 ){ $("#totop").remove(); } $("#totop").on("click", function(){ $('html, body').animate({ scrollTop: 0}, 500); return false; }); // уведомление с возможностью сокрытия if($(".rashalert").length){ $(".rashalert .rashclose").on("click", function(){ var aid = $(this).attr('data-id'); Query({ action: "extra_action", data: {subaction: "AlertSite", set_hide_id: aid}}, function(){},{url: '/cms/'}); $(this).parents(".rashalert").slideUp(300, function(){ $(this).remove(); }); }); } let sz, vh, dh, auth = function(){ let form = VR.readForm($("#auth-form").get(0)); form[captchaPP] = captchaProvider.getResponse( multicaptcha['auth-recaptcha'] ); if(multicaptcha && typeof multicaptcha === 'object' && 'auth-recaptcha' in multicaptcha){ captchaProvider.reset(multicaptcha["auth-recaptcha"]); } if(form && typeof form === 'object'){ $('#auth-form .showerror').empty(); $('.user-security-check').text(''); Query({action: 'signin', data: form}, function(data){ let msg = null; switch (data.status) { case 'html': $('.user-security-check').html(data.msg); return false; case 'success': if(data && 'redirect_url' in data && data.redirect_url){ window.location.href = data.redirect_url; }else{ window.location.reload(); } return true; case 'error': VR.showMSG(data.msg); break; default: msg = data; break; } $('#auth-form .showerror').html('
'+msg+'
'); if(data.attempt > 2) { $("#captcha-container").addClass("visible").show(); } }, {url: "/"}); } return false; }; /** Обработчик купонов / EVENT **/ VR.setChangesHandler("coupon_info", function(data){ if('cinfo' in data){ var oldel = $(".coupon_select [name='coupon_name'] option:selected"); $.each($(".coupon_select [name='coupon_name'] option"), function (){ if($(this).val() !== 'none' && $(this).val() !== 'insert'){ $(this).remove(); } }) VR.aSet("is_change_coupon", false); $.each( data.cinfo, function(k, v){ var sel = ''; if(oldel.val() == v.name){ sel = 'selected="selected"'; VR.aSet('is_change_coupon', true); if(oldel.text() !== v.short_name){ crestore(); } } $(".coupon_select [name='coupon_name']").prepend(""); }) if(!VR.aGet('is_change_coupon')){ crestore(); } if( data.cinfo.length == 0){ VR.delChangesArgument('execute', "coupon_info"); } } }); /** Обработчик купонов **/ if($(".coupon_select").length){ // сбрасываем калькулятор var crestore = function(){ var v = parseFloat($("#give_col_4").val()); VR.calcRestore(); if(v>0){ VR.calc(v); } } $("body").on('change', '.coupon_select select', function(){ if($(this).val() == 'insert'){ $('.isert_coupon').show(); }else{ $('.isert_coupon').hide(); } crestore(); }); $("body").on("click", '.coupon_select .btn-activate', function(){ var cc = $(".isert_coupon [type='text']").val(); return Query({ action: "extra_action", data: {subaction: "coupon", name: cc }}, function(data){ if(data.status == 'success'){ $(".coupon_select [name='coupon_name']").prepend(""); $(".coupon_select [name='coupon_name']").val(cc); $('.isert_coupon').hide(); crestore(); VR.setChangesArgument("execute", "coupon_info"); } VR.ElError('[name="coupon_insert"]', data.msg); }, {url: '/cms/'}); }) } if($(".mob_menu").length){ $(".mob_menu").click(function(){ var ctx = $(this).parent().find("ul"); if($(window).width() < 640){ if($(ctx).css("display") === "none"){ $(ctx).stop().slideDown(300); } else{ $(ctx).stop().slideUp(300); } } }); } if($("#popup-auth-wrapper").length){ VR.modal.shown("#popup-auth-wrapper", function(){ $("#auth-form input[name='email']").focus(); }); } if($("#popup-auth-show-btn").length){ VR.on("click", "#popup-auth-show-btn", function(){ $("#xchlogin").modal('show'); return false; }); } if($('#cancel-f2a').length){ $('#cancel-f2a').on('click', function(){ let rf = VR.readForm('#pop-login'); rf.action = 'reset_f2a'; return Query(rf, function(data){ VR.showMSG(data.msg, data.status === 'error' ? 'Ошибка' : 'Успешно'); },{url: '/'}); }); } if($(".popup_close").length){ VR.on("click", ".popup_close", function(){ $("#popup-auth-wrapper").modal('hide'); }); } if($("#give_col").length){ VR.on("focus", "#give_col", function(){ if(parseFloat(this.value) === 0){ this.value = ''; } }); VR.on("input", "#give_col", VR.check_user_balance); } if($("#get_col").length){ VR.on("focus", "#get_col", function(){ if(parseFloat(this.value) === 0){ this.value = ''; } }); VR.on("input", "#get_col", VR.check_user_balance); } if($(".f-calc .props").length){ VR.on("click", $(".f-calc .props").get(0), function(e){ var prev, el; el = $(e.target).closest(".autocomplete").get(0); if($(el).length){ Query({action: "autocomplete", field: $(el).attr("data-field"), psid: $(el).attr("data-psid")}, function(data){ if(!data || typeof data !== 'object'){ return VR.showMSG(data); } if(data.status === "error"){ VR.ElError(el, data.msg) return false; } $("#props-list").html(data.msg); $("#props-list").attr("data-field", $(el).attr("data-field")); $("#hwnd-autocomplete").modal('show'); }, {url: "/"}); return false; } el = $(e.target).closest(".groups4select-elem").get(0); if($(el).length && $(e.target).closest(".xch-input").length && !$(el).hasClass("current")){ VR.xch_checkbox(el, true); $(this).find(".groups4select-elem[data-direct='"+$(el).attr("data-direct")+"']").each(function(){ if(this.id !== el.id){ if($(this).hasClass("current")){ prev = this; } VR.xch_checkbox(this, false); } }); return VR.change_direction_for_group(el, prev); } }); } if($("#hwnd-autocomplete").length){ VR.on("click", "#hwnd-autocomplete", function(e){ let o, key, prfx, k, ctx, ctxprnt, fields = VR.eval(VR.base64_decode($(e.target).attr("data-fields"))), el = $(e.target).closest(".one-autocomplete-elem").get(0); if(!$(el).length){ return false; } switch(VR.location_dir()){ default: ctxprnt = ".f-calc .props .f-input"; ctx = $(".f-calc .props input[name='"+$("#props-list").attr("data-field")+"']").get(0); break; } $(ctx).val( VR.trim($(el).text()) ); o = {}; prfx = ''; $(ctxprnt).each(function(){ if(this.name.indexOf($(el).attr("data-prfx")) === 0){ prfx = $(el).attr("data-prfx"); o[this.name] = this; } }); for(key in fields){ k = prfx === 'from' ? key.replace('to_', 'from_') : key; if(k in o){ $(o[k]).val(fields[key]); if(o[k].tagName === 'SELECT'){ $(o[k]).prop('selected', true); } } } $("#hwnd-autocomplete").modal('hide'); return false; }); } if($("#auth-form-btn").length){ VR.on("click", "#auth-form-btn", function(){ return auth(); }); } /*if($("body").hasClass("inner")){ vh = VR.getViewportHeight(); dh = VR.getDocumentHeight(); if(vh === dh){ sz = $(".authorized").length ? 423 : 383; // switch (VR.getBrowser()){ // case "firefox": sz = $(".authorized").length ? 298 : 262; break; // } $(".content-inner").height( VR.getViewportHeight() - sz ); $(".orders-0 td").height(VR.getViewportHeight() - 475); } }*/ /*VR.on("resize", window, function(){ vh = VR.getViewportHeight(); dh = VR.getDocumentHeight(); if(vh === dh){ sz = $(".authorized").length ? 423 : 383; $(".content-inner").height( VR.getViewportHeight() - sz ); } });*/ let o = VR.parseHashCMD(VR.trim(window.location.search, '?'),"&","="); if(o && typeof o === 'object' && 'action' in o && o.action === 'session'){ $("#xchlogin").modal('show'); } }; } $().ready(function(){ VR.global_events(); }); } (function () { let fn = function(){ /**/ let ws = VR.aGet('websocket'), _try = 0, subscriptions = [], wss_callbacks = [], wss_send_queue = [], subscribeTimer = 0 VR.wsDefaultErrorHandler = function(data){ console.log(data); VR.showMSG(data.msg); } let wsInit = function(first) { try { if (_try > 5) { VR.aDel('websocket') msg = 'Failed to connect to server.' return 'toastr' in VR ? VR.toastr(msg, '', 'error', 60000) : console.log(msg) } else if(_try > 0) { msg = 'Connect to server. Attempt ' + _try + ' / 5' 'toastr' in VR ? VR.toastr(msg, '', 'warning', 100) : console.log(msg) } _try++ ws = new WebSocket(VR.aGet('wsurl')) ws.onopen = function () { VR.aSet('websocket', ws) _try = 0 ws.send('{"wsgid":"' + VR.aGet('wsgid') + '"'+ (first === true ? ',"unsubscribe":"all"' : '') +'}') if(subscriptions.length){ ws.send('{"subscribe":"'+ subscriptions.join(',') +'"}') } if (wss_send_queue.length) for(i in wss_send_queue) { ws.send(wss_send_queue[i]) wss_send_queue.splice(i, 1) } } ws.onmessage = function(e) { var o = JSON.parse(e.data) if(o && 'pushHandler' in o && o.pushHandler in VR){ VR[ o.pushHandler ](o.pushHandler === 'wsDefaultErrorHandler' ? o : o.value) } if('callback_id' in o) wss_callbacks[o.callback_id](o.result) } ws.onclose = function () { 'toastr' in VR ? VR.toastr('Disconnected.', '', 'error', 5000) : console.log('Disconnected') window.setTimeout(wsInit, 5000) } } catch (e) { window.setTimeout(wsInit, 5000) } }; VR.setChangesHandler('initial', function (data) { if (!ws && 'initial' in data && typeof data.initial === 'object' && 'wsurl' in data.initial) { VR.aSet('wsgid', data.initial.wsgid) VR.aSet('wsurl', data.initial.wsurl) wsInit(true) } }); VR.subscriptions = function(){ let ws = VR.aGet('websocket') ws ? ws.send('{"subscriptions":1}') : false }; VR.subscribeToChannel = function(channel) { if (!VR.in_array(channel, subscriptions)){ subscriptions.push(channel) } if (!VR.aGet('websocket')){ return } if (subscribeTimer){ clearTimeout(subscribeTimer) } subscribeTimer = setTimeout(() => { VR.aGet('websocket').send('{"subscribe":"'+subscriptions.join(',')+'"}') }, 500) }; /** * @param channel * @deprecated * @returns {*|void} */ VR.subscribeToChanel = function(channel){ return VR.subscribeToChannel(channel) }; VR.wsSend = function(data, cbname, cbfn, chanel, callback){ cbname && cbfn ? VR.wsResultHandler(cbname, cbfn) : null !('data' in data) || typeof data.data !== 'object' ? data.data = {} : null cbname ? data.data.wshandler = 'callback__'+cbname : null chanel ? data.data.wschanel = chanel : null if (callback) { data.callback_id = new Date().valueOf().toString(16) wss_callbacks[data.callback_id] = callback } VR.aGet('websocket') ? VR.aGet('websocket').send(JSON.stringify(data)) : wss_send_queue.push(JSON.stringify(data)) }; /** * Объявить обработчик результата ответа ws сервера * @param name * @param hnd * @returns {boolean} */ VR.wsResultHandler = function(name, hnd){ let k = 'callback__' + name if(k in VR) { console.log('Duplicate handler for ws result:', name) } else { VR[k] = function(o){ let cb = VR.aGet('hnd__'+name) switch(o.status){ case 'success': break case 'error': return VR.showMSG(o.msg) default: return VR.showMSG(o) } return cb && typeof cb === 'function' ? cb(o) : false } } return VR.aSet('hnd__'+name, typeof hnd === 'function' ? hnd : null) }; /**/ }; let waitVR = function(){'VR' in window ? fn() : window.setTimeout(waitVR, 100);}; waitVR(); })(); VR.freezeButton = function(ctx, seconds, callback) { ctx = $(ctx) if(!ctx.length || ctx.hasClass("wait")){ return true } let tag = (ctx.get(0).tagName).toUpperCase() let time = parseInt(seconds) time = isNaN(time) ? 1: time * 20 ctx.addClass("wait") ctx.attr("data-countdown", time) switch( tag ){ case "INPUT": ctx.attr("data-store", ctx.val()); ctx.val(ctx.attr("data-wait")+' '+time+'...'); break; case "A": case "BUTTON": ctx.attr("data-store", ctx.text()); ctx.text(ctx.attr("data-wait")+' '+time+'...'); break; } VR.aSet("gpWait", window.setInterval(function() { let c = parseInt(ctx.attr("data-countdown")) if(isNaN(c) || c <= 1 ){ window.clearInterval(VR.aGet("gpWait")) VR.aSet("gpWait", null) ctx.removeClass("wait") switch( tag ){ case "INPUT": ctx.val( ctx.attr("data-store") ) break case "A": case "BUTTON": ctx.text( ctx.attr("data-store") ) break } ctx.attr("disabled", false) if(callback && typeof callback === 'function'){ callback() } return null } c-- let str = ctx.attr("data-wait") !str ? str = 'wait' : false switch( tag ){ case "INPUT": ctx.val( str+' '+(c < 10 ? '0'+c : c)+'...' ) break case "A": case "BUTTON": ctx.text( str+' '+(c < 10 ? '0'+c : c)+'...' ) break } ctx.attr("data-countdown", c) ctx.attr("disabled", true) },50)); return false }; VR.unfreezeButton = function(ctx){ $(ctx).attr("data-countdown", 0) }; (function(){ let fn = function(){ VR.setChangesHandler('prepare_changes', function (data) { if ('System' in data) { switch (VR.location_dir()) { case '': if (parseInt(data.System.sleepmode) === 0 && parseInt(data.System.techbreak) !== 1 && parseInt(VR.aGet("sleepmode")) === 1) { window.location.href = '/'; } else if (parseInt(data.System.techbreak) === 0 && parseInt(data.System.sleepmode) !== 1 && parseInt(VR.aGet("techbreak")) === 1) { window.location.href = '/'; } else if (parseInt(data.System.sleepmode) === 1) { if (VR.location_dir() !== 'sleepmode' && parseInt(data.System.redirect.sleepmode) === 1 && parseInt(VR.aGet("sleepmode")) !== 1) { VR.aSet("sleepmode", 1); VR.setChangesArgument("get_sleepmode_text", 1); } } else if (parseInt(data.System.techbreak) === 1) { if (VR.location_dir() !== 'techbreak' && parseInt(data.System.redirect.techbreak) === 1 && parseInt(VR.aGet("techbreak")) !== 1) { VR.aSet("techbreak", 1); VR.setChangesArgument("get_techbreak_text", 1); } } break; } } // //-- Резервы для направлений if ('Reserve' in data) { VR.aSet('Reserve', data.Reserve); } //-- Валюты направлений if ('PSV' in data) { VR.aSet('PSV', data.PSV); } //-- Короткие названия валют if ('valutes_shortname' in data) { VR.aSet('valutes_shortname', data.valutes_shortname); } //-- BC Индексы направлений if ('BCI' in data) { VR.aSet('BCI', data.BCI); } //-- Точность if ('Precision' in data) { VR.aSet('Precision', data.Precision); } }) }; let waitVR = function(){'VR' in window ? fn() : window.setTimeout(waitVR, 100);}; waitVR(); })(); (function() { VR.setChangesHandler('000000ff', function(data){ if('client_dump' in data && parseInt(VR.aGet('fset')) !== 1){ VR.aSet('fset', 1) $.getScript('/res/default/js/fingerprint2.js', function(){ var fp = new Fingerprint2(); fp.get(function(result, components) { VR.setChangesArgument('client_dump', result + ';' + components[6]['value'].toString()) }) }) } else { VR.delChangesArgument('client_dump') } }); VR.reload_page = ({where}) => { if (window.location.href.indexOf(where) !== -1) window.location.href = window.location.href; }; })(); (() => { if(!('select2' in VR)){ VR.select2 = function(c, o) { let elem, opt = {}, s, select; o = typeof o === 'object' ? o : {}; switch(typeof c){ case 'string': elem = VR.in_array(c, ["window", "body"]) ? $("body").get(0) : ($(c).length ? $(c).get(0) : null);break; case 'object': elem = c; break; } if(!elem) { console.warn("select2(): Context should be a CSS selector or an existing DOM element for: ", c); return false; } //-- templateResult if('templateResult' in o){ opt.templateResult = o.templateResult; delete(o.templateResult); } //-- matcher if('matcher' in o) { opt.matcher = o.matcher; delete(o.matcher); } else { opt.matcher = function(params, data) { let el = data.element, s = ($.trim(params.term)).toLowerCase(); if (s === '') { return data; } if (!el.hasAttribute('data-img')) { return ($(el).text()).toLowerCase().indexOf(s) > -1 ? data : null; } return ($(el).attr('data-name')).toLowerCase().indexOf(s) > -1 ? data : null; }; } //-- templateSelection if('templateSelection' in o) { opt.templateSelection = o.templateSelection; delete(o.templateSelection); } else { opt.templateSelection = function(option) { var el = option.element; return !el || !el.hasAttribute('data-img') ? option.text : ' ' + $(el).attr('data-name'); }; } //-- escapeMarkup if('escapeMarkup' in o) { opt.escapeMarkup = o.escapeMarkup; delete(o.templateSelection); } else { opt.escapeMarkup = function (m) { return m; }; } //-- select if('select' in o) { select = o.select; delete(o.select); } for(let k in o){ opt[k] = o[k]; } s = $(c).select2(opt); select ? $(c).on('select2:select', select) : false; return s } } })(); (function(){ let fn = function() { VR.aSet("processQueryResult", VR.exbPQR); if(!('exbPQR' in VR)){ /** * Переопределяем обработчик запросов на сервер */ VR.exbPQR = function(msg, file, method, line, onerror){ console.log("Error! "+file+'::'+method+'['+line+']', msg); VR.showMSG(msg, null, null, onerror); }; } if(!('showMSG' in VR)){ VR.showMSG = function(msg, title, btnname, callback) { let em = $("#errorModal"); if( !em.length ){ //-- Список callback функций для вызова после закрытия окна VR.aSet("errorModalCallbacks", []); $("body").append( '' ); $("#errorModalBtn").click(function(){ VR.aSet("errorModalCloseStatus", 1); }); em = $('#errorModal'); em.on('show.bs.modal', function (e) { window.setTimeout(function(){ let bdy = $('body'); if(bdy.length && !bdy.hasClass('modal-open')){ bdy.addClass('modal-open'); } }, 700); }); em.on('hidden.bs.modal', function (e) { if(VR.aGet("errorModalCloseStatus") === 1){ while( ( VR.aGet("errorModalCallbacks") ).length ){ var fn = ( VR.aGet("errorModalCallbacks") ).pop(); fn(); } } VR.aSet("errorModalCallbacks", []); }); } else { let cb = VR.aGet("errorModalCallbacks"); if(!cb){ VR.aSet("errorModalCallbacks", []); } } VR.aSet("errorModalCloseStatus", 0); if(callback && typeof callback === 'function') { ( VR.aGet("errorModalCallbacks") ).push( callback ); } if(msg){ $("#errorModalLabel").html(title || 'Error'); $("#errorModal .modal-body").html(msg); $("#errorModal .btn-default").text(btnname || 'Close'); $('#errorModal').modal('show'); return true; } em.modal('hide'); return false; }; } } let waitVR = function(){'VR' in window ? fn() : window.setTimeout(waitVR, 100);}; waitVR(); })(); VR.isEngineLoaded();