1518 lines
45 KiB
JavaScript
1518 lines
45 KiB
JavaScript
/*jshint esversion: 6 */
|
||
"use strict";
|
||
|
||
//var g_translations = {'':''};
|
||
|
||
//Массив g_translations подгружается отдельно
|
||
function trt(key)
|
||
{
|
||
if(key==null || key===undefined) return '';
|
||
let val=null;
|
||
if(typeof g_translations !== 'undefined'){
|
||
val=g_translations[key];
|
||
if(val==null || val===undefined)
|
||
{
|
||
for(let item in g_translations) {
|
||
if(item.toLowerCase()==(''+key).toLowerCase())
|
||
{
|
||
val=g_translations[item];
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if(val==null || val===undefined) {
|
||
|
||
return ('' + key).replace(/_/g, ' ');
|
||
}
|
||
else return val;
|
||
}
|
||
|
||
function trts(text)
|
||
{
|
||
let result='';
|
||
let pLen=4; //Длина преамбулы trt(
|
||
let cut=0;
|
||
let from = 0; // Позиция поиска для итерации
|
||
while (true)
|
||
{
|
||
let pos1 = text.indexOf('trt(', from);
|
||
if(pos1 >= 0)
|
||
{
|
||
from = pos1+pLen+1;
|
||
let pos2 = -1;
|
||
if(text[pos1+pLen] == '"') pos2 = text.indexOf('")', from);
|
||
if(text[pos1+pLen] == "'") pos2 = text.indexOf("')", from);
|
||
if(pos2 > 0)
|
||
{
|
||
result+=text.substring(cut, pos1);
|
||
let toTranslate=text.substring(pos1+pLen+1, pos2 );
|
||
result+=trt(toTranslate);
|
||
cut=pos2+2;
|
||
from = pos2;
|
||
}
|
||
}else break;
|
||
}
|
||
result+=text.substring(cut); //Копируем остатки
|
||
return result;
|
||
}
|
||
|
||
function deleteOption(sel,id){
|
||
if(typeof sel == 'string') sel=document.getElementById(sel);
|
||
let i=0;
|
||
while (i<sel.length) {
|
||
if(sel.options[i].value == id) {
|
||
sel.remove(i);
|
||
}else{
|
||
i++;
|
||
}
|
||
}
|
||
}
|
||
|
||
//Расширить плитку чтобы она занимала всю штртну области
|
||
//margin - С права и слева по одному пикселю (умножается на 2)
|
||
function resizeDivTile(parent,minWidth)
|
||
{
|
||
if(typeof parent == 'string') parent=document.getElementById(parent);
|
||
if(parent==null) return;
|
||
let dx=Math.floor(parent.offsetWidth/(minWidth));
|
||
|
||
//log.info("parent.offsetWidth="+parent.offsetWidth+" minWidth="+minWidth+" margin="+margin+" dx="+dx);
|
||
|
||
let addW=0;
|
||
for(let i=0;i<minWidth+2;i++)
|
||
{
|
||
if(dx>=parent.offsetWidth/(minWidth+i))
|
||
{
|
||
addW=i-1;
|
||
//log.info("addW="+addW+" parent.offsetWidth/(minWidth+margin+i)="+(parent.offsetWidth/(minWidth+margin+i)));
|
||
break;
|
||
}
|
||
}
|
||
|
||
for(let i = 0; i < parent.children.length; i++) {
|
||
//log.info(parent.children[i].tagName);
|
||
if(parent.children[i].tagName.toUpperCase()=='DIV')
|
||
{
|
||
parent.children[i].style.width = (minWidth+addW)+"px";
|
||
}
|
||
}
|
||
//log.info("minWidth+addW="+(minWidth+addW));
|
||
|
||
//Центрирую, путем добавления пространства с лева
|
||
parent.style.paddingLeft = Math.floor((parent.offsetWidth-(dx*(minWidth+addW)))/2) + "px";
|
||
|
||
//log.info("parent.style.paddingLeft="+parent.style.paddingLeft+" calc="+(Math.floor((parent.offsetWidth-(dx*(minWidth+addW)))/2)));
|
||
}
|
||
|
||
//Получить уникальный идентификатор в рамках текущего NAMESPACE из глобальной переменной
|
||
var UID=0;
|
||
function getUID()
|
||
{
|
||
UID++;
|
||
return UID;
|
||
}
|
||
|
||
//Функция всегда возвращающая false
|
||
function falsefunc()
|
||
{ return false;
|
||
}
|
||
|
||
//Чтоб всегда знать глоб. коордионаты мыши.
|
||
var pageX=0;
|
||
var pageY=0;
|
||
function MMove(e)
|
||
{
|
||
if(!e) e = window.event;
|
||
pageX=e.pageX || e.x;
|
||
pageY=e.pageY || e.y;
|
||
let obj=document.getElementById("pBarIco");
|
||
if(obj!=null)
|
||
{
|
||
obj.style.left=(pageX+15)+'px';
|
||
obj.style.top=(pageY)+'px';
|
||
}
|
||
}
|
||
document.onmousemove = MMove;
|
||
|
||
//Расширяем класс даты для получения даты в формате "2017-02-01 15:15:00"
|
||
Date.prototype.toString = function ()
|
||
{
|
||
let str='';
|
||
str+=this.getFullYear()+'-'+('0'+(this.getMonth()+1)).slice(-2)+'-'+('0'+this.getDate()).slice(-2)+' '
|
||
str+=('0'+this.getHours()).slice(-2)+":"+('0'+this.getMinutes()).slice(-2)+":"+('0'+this.getSeconds()).slice(-2)
|
||
return str;
|
||
};
|
||
Date.prototype.toTimeString = function ()
|
||
{
|
||
let str='';
|
||
str+=('0'+this.getHours()).slice(-2)+":"+('0'+this.getMinutes()).slice(-2)+":"+('0'+this.getSeconds()).slice(-2);
|
||
return str;
|
||
};
|
||
|
||
Date.prototype.toDateString = function (){
|
||
let d = this.getDate();
|
||
let m = this.getMonth() + 1; //Month from 0 to 11
|
||
let y = this.getFullYear();
|
||
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
|
||
}
|
||
|
||
Date.prototype.addHours = function(h) {
|
||
this.setTime(this.getTime() + (h*60*60*1000));
|
||
return this;
|
||
}
|
||
|
||
//Расширяем класс строки для удаления HTML тегов
|
||
String.prototype.stripTags = function() {
|
||
return this.replace(/<\/?[^>]+>/g, '');
|
||
};
|
||
|
||
//Показать прогрес бар
|
||
function showProgressBar(obj,img_id)
|
||
{
|
||
if(img_id === undefined) img_id='';
|
||
|
||
if (typeof obj === 'string' || obj instanceof String)
|
||
obj=document.getElementById(obj);
|
||
if(obj===null) return;
|
||
if(obj.style.position!='absolute') obj.style.position = 'relative';
|
||
let pBarDiv=document.createElement('div');
|
||
pBarDiv.id=obj.id+'_pBar';
|
||
pBarDiv.style.cssText='position: absolute; left: 0px; top: 0px; z-index: 1; background-color: rgba(0,0,0,0.5); width:100%; height: 100%;';
|
||
pBarDiv.innerHTML='<table width="100%" height="100%" cellpadding="0" cellspacing="0"><tr><td align="center" style="vertical-align: middle;"><img src="../resources/metadata/dbms/images/loading'+img_id+'.gif" alt=""></td></tr></table>';
|
||
obj.appendChild(pBarDiv);
|
||
};
|
||
|
||
function hideProgressBar(obj)
|
||
{
|
||
if(obj===null || typeof(obj)=='undefined') return;
|
||
if (typeof obj === 'string' || obj instanceof String)
|
||
deleteHTML(obj+'_pBar');
|
||
else
|
||
deleteHTML(obj.id+'_pBar');
|
||
}
|
||
|
||
//Показать прогрес бар рядом с курсором (сколько раз вызвали столько раз и должны скрыть)
|
||
var cntShPrBICnt = 0; //Сколько раз вызвали отображение иконки прогресса
|
||
function showProgressBarIco()
|
||
{
|
||
if(cntShPrBICnt==0)
|
||
{
|
||
let img=document.createElement("img");
|
||
img.id='pBarIco';
|
||
img.style.cssText='position: absolute; left: 0px; top: 0px; z-index: 1000;';
|
||
img.style.left=(pageX+15)+'px';
|
||
img.style.top=(pageY)+'px';
|
||
img.style.width = "32px";
|
||
img.style.height = "32px";
|
||
img.src = "../resources/images/loader3.svg";
|
||
document.body.appendChild(img);
|
||
}
|
||
cntShPrBICnt++;
|
||
};
|
||
function hideProgressBarIco()
|
||
{
|
||
if(cntShPrBICnt>0) cntShPrBICnt--;
|
||
if(cntShPrBICnt==0)
|
||
{
|
||
deleteHTML('pBarIco');
|
||
}
|
||
}
|
||
|
||
function loadContent(url,obj)
|
||
{
|
||
if (typeof obj === 'string' || obj instanceof String)
|
||
obj=document.getElementById(obj);
|
||
|
||
if(obj===null || typeof(obj)=='undefined') return;
|
||
showProgressBar(obj);
|
||
let req=createRequestObject();
|
||
req.onreadystatechange = function(req,obj)
|
||
{
|
||
return function(){
|
||
if(req.readyState === 4){
|
||
hideProgressBar(obj);
|
||
obj.innerHTML=req.responseText;
|
||
}
|
||
};
|
||
}(req,obj);
|
||
req.open( "GET", url, true );
|
||
req.send( null );
|
||
}
|
||
|
||
//POST Json Data to server and Json in result
|
||
function postJsonData(url,data,fun){
|
||
if(typeof data !== 'string') {
|
||
data = JSON.stringify(data);
|
||
}
|
||
let req=createRequestObject();
|
||
req.onreadystatechange = function(req)
|
||
{
|
||
return function(){
|
||
if(req.readyState == 4 || typeof(req.readyState)=='undefined'){
|
||
if(req.status == 200) {
|
||
let json = null;
|
||
try {
|
||
json = JSON.parse(req.responseText);
|
||
} catch (e) {
|
||
}
|
||
if (json != null)
|
||
fun(true, json);
|
||
else
|
||
fun(false, req.responseText);
|
||
}else{
|
||
fun(false,trt('Failed_to_receive_data'));
|
||
}
|
||
}
|
||
};
|
||
}(req);
|
||
req.open( "POST", url, true );
|
||
req.setRequestHeader("Content-type", "application/json");
|
||
req.send(data);
|
||
}
|
||
|
||
//Вывести текст поверх окон с кнопочкой OK
|
||
function alert2(title,smallText,fullText,okFunc=null)
|
||
{
|
||
if(fullText === undefined) fullText='';
|
||
if(smallText === undefined || smallText==''){
|
||
smallText=fullText;
|
||
fullText='';
|
||
}
|
||
let pos1=smallText.indexOf('[[');
|
||
let pos2=smallText.indexOf(']]');
|
||
if(pos1>=0 && pos2>=0 && pos1<pos2) smallText=smallText.substring(pos1+2, pos2);
|
||
|
||
let win=new TWin(true);
|
||
win.BuildGUI(10,10);
|
||
win.setCaption(document.createTextNode(title));
|
||
let html=`
|
||
<table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">
|
||
<tr id="smallText_`+win.uid+`">
|
||
<td colspan="2" style="text-align: center; vertical-align: middle;">`+smallText+`</td>
|
||
</tr>
|
||
<tr id="fullText_`+win.uid+`" style="display: none;">
|
||
<td colspan="2" style="text-align: center; vertical-align: middle;">`+fullText+`</td>
|
||
</tr>
|
||
<tr style="width: 100%;height: 10px;">
|
||
<td>`+(fullText === undefined || fullText == '' ? '' : '<label><input type="checkbox" id="show_'+win.uid+'" name="scales"> '+trt('Full_text')+'</label>')+` </td>
|
||
<td style="width: 80px;"><button class="button-secondary" id="close_`+win.uid+`" style="width: 100%;">`+trt('OK')+`</button></td>
|
||
</tr>
|
||
</table>`;
|
||
|
||
win.setContent(html);
|
||
|
||
let obj=document.getElementById('show_'+win.uid);
|
||
if(obj!=null){
|
||
obj.onclick=function(win){
|
||
return function(){
|
||
if(document.getElementById('show_'+win.uid).checked) {
|
||
document.getElementById('smallText_' + win.uid).style.display = "none";
|
||
document.getElementById('fullText_' + win.uid).style.display = "table-row";
|
||
}else{
|
||
document.getElementById('smallText_' + win.uid).style.display = "table-row";
|
||
document.getElementById('fullText_' + win.uid).style.display = "none";
|
||
}
|
||
};
|
||
}(win);
|
||
}
|
||
|
||
obj=document.getElementById('close_'+win.uid);
|
||
if(obj!=null){
|
||
obj.focus();
|
||
obj.onclick=function(win,okFunc){return function(){ win.Close(); if(okFunc!=null) okFunc(); };}(win,okFunc);
|
||
}
|
||
win.setSize("300px","150px");
|
||
win.setCenter();
|
||
win.shadow=true;
|
||
win.hide(false);
|
||
return obj;
|
||
}
|
||
|
||
//Вывести текст поверх окон с кнопочкой OK
|
||
function confirm2(title,smallText,fullText,okFunc,cancelFunc)
|
||
{
|
||
let win=new TWin();
|
||
win.BuildGUI(10,10);
|
||
win.setCaption(document.createTextNode(title));
|
||
let html=`
|
||
<table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">
|
||
<tr id="smallText_`+win.uid+`" style="width: 100%;">
|
||
<td colspan="3" style="text-align: center; vertical-align: middle; width: 100%;">`+smallText+`</td>
|
||
</tr>
|
||
<tr id="fullText_`+win.uid+`" style="width: 100%; display: none;">
|
||
<td colspan="3" style="text-align: center; vertical-align: middle; width: 100%;">`+fullText+`</td>
|
||
</tr>
|
||
<tr style="height: 10px;">
|
||
<td style="width: 100%;">`+(fullText === undefined || fullText == '' ? '' : '<label><input type="checkbox" id="show_'+win.uid+'" name="scales"> '+trt('Full_text')+'</label>')+` </td>
|
||
<td><button class="button-secondary" id="`+win.uid+`_ok" style="width: 80px;margin:1px;">`+trt('Ok')+`</button></td>
|
||
<td><button class="button-secondary" id="`+win.uid+`_cancel" style="width: 80px;margin:1px;">`+trt('Cancel')+`</button></td>
|
||
</tr>
|
||
</table>`;
|
||
|
||
win.setContent(html);
|
||
|
||
let obj=document.getElementById('show_'+win.uid);
|
||
if(obj!=null) obj.onclick=function(win){
|
||
return function(){
|
||
if(document.getElementById('show_'+win.uid).checked) {
|
||
document.getElementById('smallText_' + win.uid).style.display = "none";
|
||
document.getElementById('fullText_' + win.uid).style.display = "table-row";
|
||
}else{
|
||
document.getElementById('smallText_' + win.uid).style.display = "table-row";
|
||
document.getElementById('fullText_' + win.uid).style.display = "none";
|
||
}
|
||
};
|
||
}(win);
|
||
|
||
let btnO=document.getElementById(win.uid+'_ok');
|
||
if(btnO!=null){
|
||
btnO.onclick=function(win){
|
||
return function(){
|
||
win.Close();
|
||
if(okFunc!=null) okFunc();
|
||
};
|
||
}(win,okFunc);
|
||
}
|
||
let btnC=document.getElementById(win.uid+'_cancel');
|
||
btnC.focus();
|
||
if(btnC!=null) {
|
||
btnC.onclick = function (win) {
|
||
return function () {
|
||
win.Close();
|
||
if(cancelFunc!=null) cancelFunc();
|
||
};
|
||
}(win,cancelFunc);
|
||
}
|
||
|
||
win.setSize("300px","150px");
|
||
win.setCenter();
|
||
win.shadow=true;
|
||
win.hide(false);
|
||
return win;
|
||
}
|
||
|
||
//С поле ввода
|
||
function prompt2(title,smallText,fieldText,defaultText,okFunc,cancelFunc){
|
||
let win=new TWin();
|
||
win.BuildGUI(10,10);
|
||
win.setCaption(document.createTextNode(title));
|
||
let html=`
|
||
<table cellpadding="0" cellspacing="0" style="width: 100%; height: 100%;">
|
||
<tr style="width: 100%;">
|
||
<td colspan="3" style="text-align: center; vertical-align: middle; width: 100%;">`+smallText+`</td>
|
||
</tr>
|
||
<tr style="width: 100%;">
|
||
<td colspan="3" style="width: 100%;">`+fieldText+`</td>
|
||
</tr>
|
||
<tr style="width: 100%;">
|
||
<td colspan="3" style="width: 100%;"><textarea rows="5" style="width: 100%;" id="text_`+win.uid+`">`+defaultText+`</textarea></td>
|
||
</tr>
|
||
<tr style="height: 10px;">
|
||
<td style="width: 100%;"> </td>
|
||
<td><button class="button-secondary" id="`+win.uid+`_ok" style="width: 80px;margin:1px;">`+trt('Ok')+`</button></td>
|
||
<td><button class="button-secondary" id="`+win.uid+`_cancel" style="width: 80px;margin:1px;">`+trt('Cancel')+`</button></td>
|
||
</tr>
|
||
</table>`;
|
||
|
||
win.setContent(html);
|
||
|
||
let btnO=document.getElementById(win.uid+'_ok');
|
||
btnO.focus();
|
||
if(btnO!=null){
|
||
btnO.onclick=function(win){
|
||
return function(){
|
||
let text=document.getElementById('text_'+win.uid).value;
|
||
win.Close();
|
||
if(okFunc!=null) okFunc(text);
|
||
};
|
||
}(win,okFunc);
|
||
}
|
||
let btnC=document.getElementById(win.uid+'_cancel');
|
||
if(btnC!=null) {
|
||
btnC.onclick = function (win) {
|
||
return function () {
|
||
win.Close();
|
||
if(cancelFunc!=null) cancelFunc();
|
||
};
|
||
}(win,cancelFunc);
|
||
}
|
||
|
||
win.setSize("350px","200px");
|
||
win.setCenter();
|
||
win.shadow=true;
|
||
win.hide(false);
|
||
return win;
|
||
}
|
||
|
||
/**
|
||
* Добавить событие к объекту
|
||
* @param {object} obj Объект
|
||
* @param {name} name Наименование события
|
||
* @param {function} fun Выполняемая функция
|
||
* @returns {null}
|
||
*/
|
||
function addEvent(obj,name,fun)
|
||
{
|
||
if (obj.addEventListener)
|
||
{
|
||
obj.addEventListener(name, fun, false);
|
||
}else
|
||
{
|
||
obj.attachEvent(name, fun);
|
||
}
|
||
}
|
||
|
||
function validateNumber(myEvent,decimal) {
|
||
let e = myEvent || window.event;
|
||
let key = e.keyCode || e.which;
|
||
|
||
if (e.shiftKey) {
|
||
} else if (e.altKey) {
|
||
} else if (e.ctrlKey) {
|
||
} else if (key === 48) { // 0
|
||
} else if (key === 49) { // 1
|
||
} else if (key === 50) { // 2
|
||
} else if (key === 51) { // 3
|
||
} else if (key === 52) { // 4
|
||
} else if (key === 53) { // 5
|
||
} else if (key === 54) { // 6
|
||
} else if (key === 55) { // 7
|
||
} else if (key === 56) { // 8
|
||
} else if (key === 57) { // 9
|
||
|
||
} else if (key === 96) { // Numeric keypad 0
|
||
} else if (key === 97) { // Numeric keypad 1
|
||
} else if (key === 98) { // Numeric keypad 2
|
||
} else if (key === 99) { // Numeric keypad 3
|
||
} else if (key === 100) { // Numeric keypad 4
|
||
} else if (key === 101) { // Numeric keypad 5
|
||
} else if (key === 102) { // Numeric keypad 6
|
||
} else if (key === 103) { // Numeric keypad 7
|
||
} else if (key === 104) { // Numeric keypad 8
|
||
} else if (key === 105) { // Numeric keypad 9
|
||
|
||
} else if (key === 8) { // Backspace
|
||
} else if (key === 9) { // Tab
|
||
} else if (key === 13) { // Enter
|
||
} else if (key === 35) { // Home
|
||
} else if (key === 36) { // End
|
||
} else if (key === 37) { // Left Arrow
|
||
} else if (key === 39) { // Right Arrow
|
||
} else if (key === 190 && decimal) { // decimal
|
||
} else if (key === 110 && decimal) { // period on keypad
|
||
// } else if (key === 188) { // comma
|
||
} else if (key === 109) { // minus
|
||
} else if (key === 46) { // Del
|
||
} else if (key === 45) { // Ins
|
||
} else {
|
||
e.returnValue = false;
|
||
if (e.preventDefault) e.preventDefault();
|
||
}
|
||
}
|
||
|
||
//Добавить предшествующие нули к цифре
|
||
function pad(number, length)
|
||
{
|
||
let str = '' + number;
|
||
while (str.length < length)
|
||
{ str = '0' + str;
|
||
}
|
||
return str;
|
||
}
|
||
|
||
|
||
|
||
//Добавить дней к дате
|
||
function addDays(date, n)
|
||
{
|
||
let d = new Date();
|
||
d.setTime(date.getTime() + n * 24 * 60 * 60 * 1000);
|
||
return d;
|
||
}
|
||
//Остановить выполнение кода на заданое количество милисекунд
|
||
function delay(millis)
|
||
{
|
||
let date = new Date();
|
||
let curDate = null;
|
||
|
||
do { curDate = new Date(); }
|
||
while(curDate-date < millis);
|
||
}
|
||
//Вернёт название класса объекта
|
||
function getClassName(obj)
|
||
{
|
||
if (obj && obj.constructor && obj.constructor.toString)
|
||
{
|
||
let arr = obj.constructor.toString().match(/function\s*(\w+)/);
|
||
if (arr && arr.length == 2)
|
||
{ return arr[1];
|
||
}
|
||
}
|
||
return undefined;
|
||
}
|
||
function toDec(hexNumber) {
|
||
return parseInt(hexNumber,16);
|
||
}
|
||
function toHex(number) {
|
||
return parseInt(number).toString(16);
|
||
}
|
||
//Строку в CRC32 (не подходит для unicode)
|
||
function crc32(str)
|
||
{
|
||
let table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
|
||
let crc = 0;
|
||
let n = 0; //a number between 0 and 255
|
||
let x = 0; //a hex number
|
||
crc = crc ^ (-1);
|
||
for(let i = 0, iTop = str.length; i < iTop; i++ ) {
|
||
n = ( crc ^ str.charCodeAt(i) ) & 0xFF;
|
||
x = "0x" + table.substr( n * 9, 8 );
|
||
crc = ( crc >>> 8 ) ^ x;
|
||
}
|
||
crc = crc ^ (-1)
|
||
//convert to unsigned 32-bit int if needed
|
||
if (crc < 0) {crc += 4294967296}
|
||
return toHex(crc);
|
||
}
|
||
|
||
function guid()
|
||
{
|
||
function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }
|
||
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
|
||
}
|
||
|
||
//Получить абсолютные коордионаты элемента
|
||
function ElemCoords(obj)
|
||
{
|
||
let curLeft = 0;
|
||
let curTop = 0;
|
||
if (obj.offsetParent)
|
||
{
|
||
while (1)
|
||
{
|
||
curLeft += obj.offsetLeft;
|
||
curTop += obj.offsetTop;
|
||
if (!obj.offsetParent)
|
||
break;
|
||
obj=obj.offsetParent;
|
||
}
|
||
}
|
||
else if (obj.x || obj.y)
|
||
{
|
||
curLeft += obj.x;
|
||
curTop += obj.y;
|
||
}
|
||
return {
|
||
x:curLeft,
|
||
y:curTop
|
||
};
|
||
}
|
||
|
||
function goToURL(url)
|
||
{ window.location.href=url;
|
||
}
|
||
|
||
function mailTo(mail)
|
||
{
|
||
mail=mail.replace(/#/, "@");
|
||
document.location.href="MailTo:"+mail;
|
||
}
|
||
|
||
function getCookie(c_name)
|
||
{
|
||
let i,x,y,arrCookies=document.cookie.split(";");
|
||
for (i=0;i<arrCookies.length;i++)
|
||
{
|
||
x=arrCookies[i].substr(0,arrCookies[i].indexOf("="));
|
||
y=arrCookies[i].substr(arrCookies[i].indexOf("=")+1);
|
||
x=x.replace(/^\s+|\s+$/g,"");
|
||
if (x==c_name)
|
||
{
|
||
return unescape(y);
|
||
}
|
||
}
|
||
return "";
|
||
}
|
||
|
||
//expires - Сколько дней хранить куки
|
||
//path - Путь куда разрешено пересылать куки (по умолчанию текущий)
|
||
function setCookie (name, value, expires, path, domain, secure)
|
||
{
|
||
let exDate=new Date();
|
||
exDate.setDate(exDate.getDate() + expires);
|
||
expires=exDate.toUTCString();
|
||
|
||
let str = name + "=" + escape(value) +
|
||
((expires) ? "; expires=" + expires : "") +
|
||
((path) ? "; path=" + path : "") +
|
||
((domain) ? "; domain=" + domain : "") +
|
||
((secure) ? "; secure" : "");
|
||
|
||
document.cookie = str;
|
||
}
|
||
|
||
//Delete all Cookies
|
||
function eraseCookies()
|
||
{
|
||
|
||
}
|
||
|
||
function move_me(e,win)
|
||
{
|
||
let elem=win.div;
|
||
if(!e) e = window.event;
|
||
win.dx=parseInt(elem.style.left)-(e.pageX || e.x);
|
||
win.dy=parseInt(elem.style.top)-(e.pageY || e.y);
|
||
document.onmousedown = function() {
|
||
return false;
|
||
};
|
||
document.onmousemove = function(e) {
|
||
if(!e) e = window.event;
|
||
let x2 = e.pageX || e.x;
|
||
let y2 = e.pageY || e.y;
|
||
elem.style.top = win.dy + y2+'px';
|
||
if(parseInt(elem.style.top)<0) elem.style.top='0px';
|
||
elem.style.left = win.dx + x2+'px';
|
||
return false;
|
||
};
|
||
document.onmouseup = function() {
|
||
document.onmousedown = null;
|
||
document.onmousemove = MMove;//null;
|
||
};
|
||
return false;
|
||
}
|
||
|
||
function createImg(src,w,h)
|
||
{
|
||
let img=new Image();
|
||
if ((/MSIE (5\.5|6).+Win/.test(navigator.userAgent))&&(/\.png$/.test(src)))
|
||
{
|
||
img.style.cssText="height:"+h+"; width:"+w+"; background:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"' ,sizingMethod='scale');";
|
||
img.src="blank.gif";
|
||
img.setAttribute("alt"," ");
|
||
}else
|
||
{
|
||
img.style.cssText="height:"+h+"; width:"+w+";";
|
||
img.src=src;
|
||
img.setAttribute("alt"," ");
|
||
}
|
||
return img;
|
||
}
|
||
|
||
//заплатка для IE (см CSS)
|
||
function fixPNG(element)
|
||
{
|
||
if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
|
||
{
|
||
let src;
|
||
if (element.tagName=='IMG')
|
||
{
|
||
if (/\.png$/.test(element.src))
|
||
{
|
||
src = element.src;
|
||
element.src = "blank.gif";
|
||
}
|
||
}
|
||
else
|
||
{
|
||
src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i)
|
||
if (src)
|
||
{
|
||
src = src[1];
|
||
element.runtimeStyle.backgroundImage="none";
|
||
}
|
||
}
|
||
if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
|
||
}
|
||
}
|
||
// Получить из iframe его document
|
||
function getIframeDocument(iframeNode)
|
||
{
|
||
if (iframeNode.contentDocument) return iframeNode.contentDocument;
|
||
if (iframeNode.contentWindow) return iframeNode.contentWindow.document;
|
||
return iframeNode.document;
|
||
}
|
||
function setIframeSrc(iframeNode, src)
|
||
{
|
||
getIframeDocument(iframeNode).location.replace(src);
|
||
}
|
||
// браузер хранится в объекте browser
|
||
function createIFrame(fname, fsrc, parent, debug)
|
||
{
|
||
let ifrstr = BrowserDetect.browser=='Explorer' ? '<iframe name="'+fname+'" src="'+src+'">' : 'iframe';
|
||
let cframe = document.createElement(ifrstr);
|
||
|
||
cframe.name = fname // это не для IE
|
||
cframe.setAttribute("name", fname) // и это тоже, но вреда не будет
|
||
cframe.id = fname // а это везде ок
|
||
cframe.src = fsrc //Так ка setIframeSrc глючит если не задан родитель
|
||
|
||
// можно добавлять сразу к document.body
|
||
//document.body.appendChild(cframe);
|
||
//document.getElementById(parent).appendChild(cframe);
|
||
parent.appendChild(cframe);
|
||
|
||
/*if(! (BrowserDetect.browser=='Explorer'))
|
||
{
|
||
setIframeSrc(cframe, fsrc);
|
||
}*/
|
||
|
||
if (!debug) {
|
||
hideIframe(cframe);
|
||
}
|
||
return cframe;
|
||
}
|
||
|
||
// прячем фрейм
|
||
function hideIframe(iframeNode)
|
||
{
|
||
if(BrowserDetect.browser!='Safari'){
|
||
iframeNode.style.position = "absolute";
|
||
}
|
||
iframeNode.style.left = "0px";
|
||
iframeNode.style.height = "1px";
|
||
iframeNode.style.visibility = "hidden";
|
||
}
|
||
|
||
//вернуть строку до заданных символов
|
||
function BeforeFirst(str,sub)
|
||
{
|
||
let pos=str.indexOf(sub);
|
||
if (pos==-1) return null;
|
||
return str.substring(0, pos);
|
||
}
|
||
//вернуть строку до последнего найденого символа
|
||
function BeforeLast(str,sub)
|
||
{
|
||
let pos=str.lastIndexOf(sub);
|
||
if (pos==-1) return null;
|
||
return str.substring(0, pos);
|
||
}
|
||
|
||
//вернуть строку после заданных символов
|
||
function AfterFirst(str,sub)
|
||
{
|
||
let pos=str.indexOf(sub);
|
||
if (pos==-1) return null;
|
||
return str.substring(pos+sub.length, str.length);
|
||
}
|
||
|
||
function AfterLast(str,sub)
|
||
{
|
||
let pos=str.lastIndexOf(sub);
|
||
if (pos==-1) return null;
|
||
return str.substring(pos+sub.length, str.length);
|
||
}
|
||
|
||
//взять параметры из строки запроса (раздел по ? и &)
|
||
function getParam(sParamName,win)
|
||
{
|
||
let Params = win.location.search.substring(1).split("&"); // отсекаем «?» и вносим переменные и их значения в массив
|
||
let variable = "";
|
||
for (let i = 0; i < Params.length; i++)
|
||
{
|
||
if (Params[i].split("=")[0] == sParamName)
|
||
{
|
||
if (Params[i].split("=").length > 1) variable = Params[i].split("=")[1]; // если значение параметра задано, то возвращаем его
|
||
return variable;
|
||
}
|
||
}
|
||
return "";
|
||
}
|
||
//утилитарная функция из-за различий IE и FF
|
||
function getXMLNodeSerialisation(xmlNode)
|
||
{
|
||
let text = null;
|
||
try
|
||
{
|
||
let serializer = new XMLSerializer(); // Gecko-based browsers, Safari, Opera.
|
||
text = serializer.serializeToString(xmlNode);
|
||
}
|
||
catch (e)
|
||
{
|
||
try
|
||
{
|
||
text = xmlNode.xml; // Internet Explorer.
|
||
}
|
||
catch (e) {}
|
||
}
|
||
return text;
|
||
}
|
||
//утилитарная функция из-за различий IE и FF
|
||
function createRequestObject()
|
||
{
|
||
if (typeof XMLHttpRequest === 'undefined')
|
||
{
|
||
XMLHttpRequest = function()
|
||
{
|
||
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
|
||
catch(e) {}
|
||
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
|
||
catch(e) {}
|
||
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
|
||
catch(e) {}
|
||
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
|
||
catch(e) {}
|
||
throw new Error("This browser does not support XMLHttpRequest.");
|
||
};
|
||
}
|
||
return new XMLHttpRequest();
|
||
}
|
||
|
||
//создать DOMParser
|
||
function CreateXMLDOC(xmlString)
|
||
{
|
||
let xml=null;
|
||
if (window.ActiveXObject)
|
||
{
|
||
xml = new ActiveXObject("MSXML2.DOMDocument");
|
||
xml.loadXML(xmlString);
|
||
}
|
||
else if(document.implementation)
|
||
{
|
||
let parser = new DOMParser();
|
||
xml = parser.parseFromString(xmlString,"text/xml");
|
||
}
|
||
return xml
|
||
}
|
||
//вернуть первый узел заданного типа (без поиска по вложености)
|
||
function findNode(node, nodename, n)
|
||
{
|
||
if (typeof n == "undefined") n = 0;
|
||
if(node==null) return null;
|
||
let nextNode = node.firstChild;
|
||
while (nextNode != null)
|
||
{
|
||
if(nextNode.nodeName.toLowerCase()==nodename.toLowerCase()) return nextNode;
|
||
nextNode=nextNode.nextSibling;
|
||
}
|
||
return null;
|
||
}
|
||
//Вернуть узел по имени и порядковому номеру (нумерация с 0)
|
||
function findNodeOnNum(node,nodename,n)
|
||
{
|
||
if (typeof n == "undefined") n = 0;
|
||
if(node==null) return null;
|
||
let nextNode = node.firstChild;
|
||
let i=0
|
||
while (nextNode != null)
|
||
{
|
||
if(nextNode.nodeName.toLowerCase()==nodename.toLowerCase())
|
||
{
|
||
if(i==n) return nextNode;
|
||
i++;
|
||
}
|
||
nextNode=nextNode.nextSibling;
|
||
}
|
||
return null;
|
||
}
|
||
//Вернуть первый узел заданного типа
|
||
function findNodeOnAttribute(node, nodename, Attribute, val)
|
||
{
|
||
if(node==null) return null;
|
||
let n = node.firstChild;
|
||
while (n != null)
|
||
{
|
||
if((n.nodeName.toLowerCase()==nodename.toLowerCase())&&(n.getAttribute(Attribute)==val)) {
|
||
return n;
|
||
}
|
||
n=n.nextSibling;
|
||
}
|
||
return null;
|
||
}
|
||
//Вернуть номер узла по атрибуту среди себеподобных (нумерация с 0)
|
||
function findNumNodeOnAttribute(node, nodename,Attribute,val)
|
||
{
|
||
if(node==null) return -1;
|
||
let i=0;
|
||
let n = node.firstChild;
|
||
while (n != null){
|
||
if(n.nodeName.toLowerCase()==nodename.toLowerCase()){
|
||
if(n.getAttribute(Attribute)==val) return i;
|
||
i++;
|
||
}
|
||
n=n.nextSibling;
|
||
}
|
||
return -1;
|
||
}
|
||
//рекурсию не буду использовать, обойдусь массивом вложенности
|
||
function findFirstNode(node, nodename)
|
||
{
|
||
if(node==null) return null;
|
||
let mas=new Array();
|
||
let pos=0;
|
||
mas[pos] = node.firstChild;
|
||
while (mas[pos] != null)
|
||
{
|
||
if(mas[pos].nodeName.toLowerCase()==nodename.toLowerCase())
|
||
{
|
||
return mas[pos];
|
||
}
|
||
if(mas[pos].firstChild!=null)
|
||
{
|
||
pos++;
|
||
mas[pos]=mas[pos-1].firstChild;
|
||
}else
|
||
{
|
||
//если не идёт дальше пытаемся подняться в верх по дереву
|
||
while (true)
|
||
{
|
||
mas[pos] = mas[pos].nextSibling;
|
||
if (mas[pos]==null)
|
||
{
|
||
if(pos>0){
|
||
pos--;
|
||
}else{
|
||
break;
|
||
}
|
||
}else
|
||
{
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
//рекурсию не буду использовать, обойдусь массивом вложенности
|
||
function findFirstNodeOnAttribute(node, nodename,Attribute,val)
|
||
{
|
||
if(node==null) return null;
|
||
let mas=new Array();
|
||
let pos=0;
|
||
mas[pos] = node.firstChild;
|
||
while (mas[pos] != null)
|
||
{
|
||
if((mas[pos].nodeName.toLowerCase()==nodename.toLowerCase())&&(mas[pos].getAttribute(Attribute)==val))
|
||
{
|
||
return mas[pos];
|
||
}
|
||
if(mas[pos].firstChild!=null)
|
||
{
|
||
pos++;
|
||
mas[pos]=mas[pos-1].firstChild;
|
||
}else
|
||
{
|
||
//если не идёт дальше пытаемся подняться в верх по дереву
|
||
while (true)
|
||
{
|
||
mas[pos] = mas[pos].nextSibling;
|
||
if (mas[pos]==null)
|
||
{
|
||
if(pos>0){
|
||
pos--;
|
||
}else{
|
||
break;
|
||
}
|
||
}else
|
||
{
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
/**
|
||
* Поиск узла по пути "type/objects/list/filter/column" или "Employees/Employee[@id='4']"
|
||
* @node Node Узел с которого ищется
|
||
* @path String Путь по котрому ищется
|
||
*/
|
||
function findNodeOnPath(node, path)
|
||
{
|
||
if(node==null) return null;
|
||
let Params = path.split("/");
|
||
for (let i=0;i<Params.length;i++)
|
||
{
|
||
if(node==null) return null;
|
||
let pos1=Params[i].indexOf('[@');
|
||
if(pos1>=0){
|
||
let pos2=Params[i].indexOf("='");
|
||
let pos3=Params[i].indexOf("']");
|
||
let name=Params[i].substring(0, pos1);
|
||
let attribute=Params[i].substring(pos1+2, pos2);
|
||
let val=Params[i].substring(pos2+2, pos3);
|
||
|
||
node = findNodeOnAttribute(node, name, attribute, val);
|
||
}else {
|
||
node = findNode(node, Params[i]);
|
||
}
|
||
}
|
||
return node;
|
||
}
|
||
|
||
//вернёт первую CDATA секцию если её нет то создаст}
|
||
function getCdata(node,n)
|
||
{
|
||
if(node==null) return null;
|
||
let r=findNodeOnNum(node,'#cdata-section',n);
|
||
if(r==null)
|
||
{
|
||
r=node.ownerDocument.createCDATASection("");
|
||
node.appendChild(r);
|
||
}
|
||
return r;
|
||
}
|
||
//Вернёт данные CDATA без создания секции
|
||
function getCdataValue(node,n)
|
||
{
|
||
if(node==null) return '';
|
||
let r=findNodeOnNum(node,'#cdata-section',n);
|
||
if(r==null) return '';
|
||
return r.nodeValue;
|
||
}
|
||
|
||
//Задать данные CDATA с созданием секции если её нет
|
||
function setCdataValue(node,n,value)
|
||
{
|
||
let cNode=getCdata(node,n);
|
||
if(cNode!=null)
|
||
cNode.nodeValue=value;
|
||
}
|
||
|
||
//удалить элемент HTML
|
||
function deleteHTML(obj)
|
||
{
|
||
if (typeof obj === 'string' || obj instanceof String)
|
||
obj=document.getElementById(obj);
|
||
if(obj!=null)
|
||
{
|
||
let parent=obj.parentNode;
|
||
if(parent!=null) parent.removeChild(obj);
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
//Удалить дочерние HTML элементы
|
||
function delChild(obj)
|
||
{
|
||
if (typeof obj === 'string' || obj instanceof String)
|
||
obj=document.getElementById(obj);
|
||
if(obj!=null)
|
||
{
|
||
while(true)
|
||
{
|
||
let c=obj.firstChild;
|
||
if(c!=null) obj.removeChild(c); else break;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* Присвоить дочерние узлы первого дерева второму если их нет, иначе дополнить либо заменить. (Работает через рекурсию нужно для передачи параметров между окнами)
|
||
* @param {XML} first Узел где ханятся настройки
|
||
* @param {XML} second Узел к которому применяются настройки
|
||
* @param {String} name Имя атрибута по которому будут находиться одинаковые XML узлы
|
||
* @returns {undefined}
|
||
*/
|
||
function applyNodeToNode(first, second, name)
|
||
{
|
||
if(first===null || second===null || name ===null){
|
||
log.error("first="+first+" second="+second+" name="+name);
|
||
return;
|
||
}
|
||
//Если есть совпадающие узлы то передаём в рекурсию если нет то просто копируем
|
||
let fn=first.firstChild;
|
||
while (fn !== null)
|
||
{
|
||
let sn=null;
|
||
if(fn.nodeName!=="#text" && fn.nodeName!=="#cdata-section" && fn.nodeName!=="#comment"){ //потому что для этих getAttribute вызывает ошибку
|
||
sn=findNodeOnAttribute(second,fn.nodeName,name,fn.getAttribute(name));
|
||
}
|
||
|
||
if(sn!==null) //Если по имени атрибуту совпали узлы
|
||
{
|
||
//Переписываем значения атрибутов из первого второму, если их нет то создаются автоматом
|
||
for(let i=0;i<fn.attributes.length;i++)
|
||
{ sn.setAttribute(fn.attributes[i].nodeName,fn.attributes[i].value);
|
||
}
|
||
applyNodeToNode(fn,sn,name); //В рекурсию
|
||
}
|
||
else
|
||
{
|
||
//Значения CDADA или text node не должны накапливаться их мы пересоздаём (потом по момеру можно сделать 1й заменяется первым итд.)
|
||
if(fn.nodeName === "#cdata-section")
|
||
{
|
||
getCdata(second).nodeValue = fn.nodeValue;
|
||
}else
|
||
{
|
||
second.appendChild(fn.cloneNode(true));
|
||
}
|
||
}
|
||
fn=fn.nextSibling;
|
||
}
|
||
}
|
||
|
||
/*function applyObjectToObject(first, second, name){
|
||
if(first===null || second===null || name ===null){
|
||
log.error("first="+first+" second="+second+" name="+name);
|
||
return;
|
||
}
|
||
}*/
|
||
|
||
function escapeRegExp(str) {
|
||
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
|
||
}
|
||
|
||
function replaceAll(str, find, replace) {
|
||
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
|
||
}
|
||
|
||
//Заменить текст во всех CDATA секцияъ по шаблону
|
||
//node - Корневой узел
|
||
//oldStr - Что найти
|
||
//newStr - На что земенить
|
||
function replaseTextInCDATA(node,oldStr,newStr)
|
||
{
|
||
if(node===null || oldStr===null || newStr===null) return;
|
||
|
||
let fn=node.firstChild;
|
||
while (fn !== null)
|
||
{
|
||
if(fn.nodeName=="#cdata-section")
|
||
{
|
||
fn.nodeValue = replaceAll(fn.nodeValue,oldStr,newStr);
|
||
}
|
||
//В рекурсию
|
||
if(fn.nodeName!=="#text" && fn.nodeName!=="#cdata-section" && fn.nodeName!=="#comment")
|
||
replaseTextInCDATA(fn,oldStr,newStr)
|
||
|
||
fn=fn.nextSibling;
|
||
}
|
||
}
|
||
|
||
//Wrapper for XMLHttpRequest
|
||
class TRequest
|
||
{
|
||
constructor(listener)
|
||
{
|
||
if(listener.applyReq==null) alert('An object can not be found the function: "applyReq()"!');
|
||
//if(listener.name==null) alert('An object can not be found the propenty: "name"!'); незачем
|
||
this.winObj=listener;
|
||
//private
|
||
this.m_seq=0;
|
||
this.seq=-1;
|
||
}
|
||
|
||
callServer(url,xmlString)
|
||
{
|
||
let call=new myXMLHttpRequest(this);
|
||
return call.callServer(url,xmlString);
|
||
}
|
||
|
||
processReqChange(xmlHttpRequest,url,xmlString)
|
||
{
|
||
if(typeof(xmlHttpRequest.status)=='undefined' || xmlHttpRequest.status == 200)
|
||
{
|
||
//console.log(JSON.stringify(xmlHttpRequest));
|
||
if(xmlHttpRequest.responseXML!=null) {
|
||
//if(typeof(xmlHttpRequest.responseXML)=='undefined' && xmlHttpRequest.contentType.match(/\/xml/)) //For IE XDomainRequest
|
||
// xmlHttpRequest.responseXML=CreateXMLDOC(xmlHttpRequest.responseText);
|
||
let xmldoc = xmlHttpRequest.responseXML;
|
||
if (xmldoc == null) {
|
||
alert2(trt('Alert'), trt('Wrong_XML_document') + "!\nXML=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\nxmlString=(' + xmlString + ')');
|
||
return;
|
||
}
|
||
let node = xmldoc.documentElement;
|
||
if ((node == null) || (node.getAttribute("fn") == null)){
|
||
alert2(trt('Error'), trt('No_data')+"! \n" + xmlHttpRequest.responseText);
|
||
}else {
|
||
let fn = node.getAttribute("fn");
|
||
if (this.winObj != null) {
|
||
this.winObj.applyReq(this, fn, node, xmldoc, this.winObj);
|
||
return null;
|
||
}
|
||
}
|
||
}else{
|
||
let obj=null;
|
||
try { obj = JSON.parse(xmlHttpRequest.responseText); } catch (e) {}
|
||
if(obj==null) {
|
||
alert2(trt('Alert'), trt('Wrong_JSON_document') + "!\nJSON=(" + xmlHttpRequest.responseText + ') ',xmlHttpRequest.responseURL);
|
||
return;
|
||
}
|
||
if(this.winObj!=null)
|
||
{
|
||
this.winObj.applyReq(this,obj.fn,obj,null,this.winObj);
|
||
return null;
|
||
}
|
||
}
|
||
}else
|
||
{
|
||
if(confirm(trt('Failed_to_get_data')+"\n URL: "+url+"\n"+xmlHttpRequest.statusText+trt('Repeat_request')+'?'))
|
||
{
|
||
this.callServer(url,xmlString);
|
||
};
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/*processReqChange(xmlHttpRequest,url,xmlString)
|
||
{
|
||
//if (typeof(xmlHttpRequest.readyState)=='undefined' || xmlHttpRequest.readyState == 4)
|
||
//{
|
||
if(typeof(xmlHttpRequest.status)=='undefined' || xmlHttpRequest.status == 200)
|
||
{
|
||
alert(JSON.stringify(xmlHttpRequest));
|
||
if(typeof(xmlHttpRequest.responseXML)=='undefined') {
|
||
if(xmlHttpRequest.contentType.match(/\/xml/)) {
|
||
xmlHttpRequest.responseXML = CreateXMLDOC(xmlHttpRequest.responseText);
|
||
if(xmlHttpRequest.responseXML==null) {
|
||
alert2(trt('Alert'), trt('Wrong_XML_document') + "!\nXML=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\nxmlString=(' + xmlString + ')');
|
||
return;
|
||
}
|
||
//загрузился xml документ начинаем его разбирать (по id функции в документе)
|
||
let node = xmlHttpRequest.responseXML.documentElement;
|
||
if((node==null)||(node.getAttribute("fn")==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText);
|
||
else
|
||
{
|
||
let fn = node.getAttribute("fn");
|
||
if(this.winObj!=null)
|
||
{
|
||
this.winObj.applyReq(this,fn,node,xmldoc,this.winObj);
|
||
return null;
|
||
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue);
|
||
}
|
||
|
||
}else if(xmlHttpRequest.contentType.match(/\/json/)){
|
||
xmlHttpRequest.responseXML = JSON.parse(xmlHttpRequest.responseText);
|
||
if(xmlHttpRequest.responseXML==null) {
|
||
alert2(trt('Alert'), trt('Wrong_JSON_document') + "!\nJSON=(" + xmlHttpRequest.responseText + ')\nURL=(' + url + ')\njsonString=(' + xmlString + ')');
|
||
return;
|
||
}
|
||
//загрузился xml документ начинаем его разбирать (по id функции в документе)
|
||
let node=xmlHttpRequest.responseXML;
|
||
if((node==null)||(node.fn==null)) alert(trt('Error')+"\n"+trt('No_data')+"!\n"+xmlHttpRequest.responseText);
|
||
else
|
||
{
|
||
if(this.winObj!=null)
|
||
{
|
||
this.winObj.applyReq(this,node.fn,node,null,this.winObj);
|
||
return null;
|
||
}else if(fn==0) alert(findFirstNode(node,'#cdata-section').nodeValue);
|
||
}
|
||
|
||
}
|
||
}
|
||
|
||
}else
|
||
{
|
||
if(confirm(trt('Failed_to_get_data')+"\n URL: "+url+"\n"+xmlHttpRequest.statusText+"\nПовторить запрос?"))
|
||
{
|
||
this.callServer(url,xmlString);
|
||
};
|
||
}
|
||
//}
|
||
return null;
|
||
}*/
|
||
};
|
||
|
||
/** Класс асинхронных запросов к серверу
|
||
*/
|
||
class myXMLHttpRequest
|
||
{
|
||
constructor(obj)
|
||
{
|
||
this.url=null;
|
||
this.xmlString=null;
|
||
this.name="myXMLHttpRequest";
|
||
this.obj=obj;
|
||
if(obj.processReqChange==null) alert('Нет функции "processReqChange"');
|
||
this.xmlHttpRequest=createRequestObject();
|
||
}
|
||
/**
|
||
* Функция возвращяет ссылку на анонимную функцию
|
||
*/
|
||
LocCallback(thiz)
|
||
{
|
||
return function()
|
||
{
|
||
// Если состояние запроса COMPLETE то есть 4 для кросдоменного запроса undefined
|
||
if(thiz.xmlHttpRequest.readyState == 4 || typeof(thiz.xmlHttpRequest.readyState)=='undefined')
|
||
{
|
||
thiz.xmlHttpRequest.onreadystatechange = function(){};//Разрываем циклическую связь объекта-запроса и функции
|
||
thiz.obj.processReqChange(thiz.xmlHttpRequest,thiz.url,thiz.xmlString);//вызываем метод переданного объекта
|
||
}
|
||
};
|
||
}
|
||
/** Запросить данные постом
|
||
*/
|
||
callServer(url,xmlString)
|
||
{
|
||
this.url=url;
|
||
this.xmlString=xmlString;
|
||
this.xmlHttpRequest.onload=this.LocCallback(this);
|
||
|
||
this.xmlHttpRequest.open("POST", url, true); //если ошибка проверь есть ли файл на сервере
|
||
//this.xmlHttpRequest.setRequestHeader("Content-type", "application/json");
|
||
//this.xmlHttpRequest.setRequestHeader("Content-type", "application/xml");
|
||
this.xmlHttpRequest.setRequestHeader("Content-type", "text/plain");
|
||
this.xmlHttpRequest.send(xmlString);
|
||
|
||
return true;
|
||
}
|
||
/** Запросить данные гетом
|
||
*/
|
||
GETFromServer(url,xmlString)
|
||
{
|
||
this.url=url;
|
||
this.xmlString=xmlString;
|
||
if (this.xmlHttpRequest==null) this.xmlHttpRequest=createRequestObject();
|
||
this.xmlHttpRequest.onreadystatechange=this.LocCallback(this);
|
||
this.xmlHttpRequest.open("GET", url, true);
|
||
this.xmlHttpRequest.setRequestHeader("Content-Type", "text/xml");
|
||
this.xmlHttpRequest.send(xmlString);
|
||
}
|
||
}
|
||
|
||
//список параметров (TODO для чего использую?)
|
||
class TSettings
|
||
{
|
||
constructor()
|
||
{
|
||
this.seq=0;
|
||
this.mas = new Array();
|
||
}
|
||
add(id,val)
|
||
{ this.mas[id]=val;
|
||
}
|
||
del(id)
|
||
{ return this.mas[id];
|
||
};
|
||
get(id)
|
||
{ delete(this.mas[id]);
|
||
};
|
||
}
|
||
var Settings=new TSettings();
|
||
|
||
|
||
function isInt(value)
|
||
{
|
||
let num="-1234567890"
|
||
for (let i=0;i<value.length;i++)
|
||
{
|
||
let b=true;
|
||
for(let j=0;j<num.length;j++)
|
||
{
|
||
if (value.charAt(i)==num.charAt(j)) b=false;
|
||
}
|
||
if(b) return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
function isFloat(value)
|
||
{
|
||
let num="-1234567890.,"
|
||
for(let i=0;i<value.length;i++)
|
||
{
|
||
let b=true;
|
||
for(let j=0;j<num.length;j++)
|
||
{
|
||
if(value.charAt(i)==num.charAt(j)) b=false;
|
||
}
|
||
if(b) return false;
|
||
}
|
||
return true;
|
||
}
|
||
|
||
//Проверка email на валидность
|
||
function isEmail(email)
|
||
{
|
||
email = email.replace(/^\s+|\s+$/g, '');
|
||
return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
|
||
}
|
||
|
||
function getIntVal(str)
|
||
{
|
||
if(str==null || str=="") return 0
|
||
var num="-1234567890"
|
||
var rez=""
|
||
for (var i=0;i<str.length;i++)
|
||
{
|
||
for(var j=0;j<num.length;j++)
|
||
{
|
||
if (str.charAt(i)==num.charAt(j)) rez+=str.charAt(i);
|
||
}
|
||
}
|
||
if(rez=="") return 0
|
||
else return parseInt(rez)
|
||
}
|
||
|
||
//Аналог PHP функции форматирования чисел (для разделения на десятки и сотни)
|
||
function number_format (number, decimals, dec_point, thousands_sep)
|
||
{
|
||
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
|
||
let n = !isFinite(+number) ? 0 : +number;
|
||
let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
|
||
let sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
|
||
let dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
|
||
let s = '';
|
||
let toFixedFix = function (n, prec) {
|
||
let k = Math.pow(10, prec);
|
||
return '' + Math.round(n * k) / k;
|
||
};
|
||
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
|
||
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
|
||
if (s[0].length > 3) {
|
||
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
|
||
}
|
||
if ((s[1] || '').length < prec) {
|
||
s[1] = s[1] || '';
|
||
s[1] += new Array(prec - s[1].length + 1).join('0');
|
||
}
|
||
return s.join(dec);
|
||
}
|
||
|
||
|
||
|
||
|
||
/*
|
||
function number_format( number, decimals, dec_point, thousands_sep )
|
||
{ // Format a number with grouped thousands
|
||
//
|
||
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
|
||
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
|
||
// + bugfix by: Michael White (http://crestidg.com)
|
||
|
||
var i, j, kw, kd, km;
|
||
|
||
// input sanitation & defaults
|
||
if( isNaN(decimals = Math.abs(decimals)) )
|
||
{ decimals = 2;
|
||
}
|
||
if( dec_point == undefined )
|
||
{ dec_point = ",";
|
||
}
|
||
if( thousands_sep == undefined )
|
||
{ thousands_sep = ".";
|
||
}
|
||
|
||
i = parseInt(number = (+number || 0).toFixed(decimals)) + "";
|
||
|
||
if( (j = i.length) > 3 )
|
||
{ j = j % 3;
|
||
}else
|
||
{ j = 0;
|
||
}
|
||
|
||
km = (j ? i.substr(0, j) + thousands_sep : "");
|
||
kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
|
||
//kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
|
||
kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");
|
||
|
||
return km + kw + kd;
|
||
}
|
||
*/
|
||
|
||
//Получить случайное RGB в заданном промежутке
|
||
function getRandomColor(start,end)
|
||
{
|
||
let r = Math.floor(Math.random() * (end-start)+start);
|
||
let g = Math.floor(Math.random() * (end-start)+start);
|
||
let b = Math.floor(Math.random() * (end-start)+start);
|
||
return 'rgb('+r+','+g+','+b+')';
|
||
}
|