$.Engine = {}; $.Engine.costants = { endPoint: "https://restaurant.api.bookingsafe.it/index.php" };/* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ $.Engine.messages = { options: { duration: 10000 // popup: {positionClass: 'toast-top-full-width', containerId: 'toast-top-full-width', 'showMethod': 'slideDown', 'hideMethod': 'slideUp'} }, popup: function (title, description, type, option) { if (option) { var optionex = $.Engine.messages.options; for (i in option) optionex[i] = option[i]; option = optionex; } else option = $.Engine.messages.options; if (type == 'error') type = 'danger'; let colorName = 'alert-' + type; return showNotification(colorName, title, description, 'top', 'right', null, null, option.duration) }, popupWContent: function (title, callback, size) { if (size == 'xl') $('#popupMain .modal-dialog').attr('class', 'modal-dialog modal-xl'); else if (!size || size == 'l') $('#popupMain .modal-dialog').attr('class', 'modal-dialog modal-lg'); else if (size == 'd') $('#popupMain .modal-dialog').attr('class', 'modal-dialog'); else if (size == 's') $('#popupMain .modal-dialog').attr('class', 'modal-dialog modal-sm'); else if (size == 'xs') $('#popupMain .modal-dialog').attr('class', 'modal-dialog modal-xs'); $("#popupMainLabel").html(title); if (callback) { $('#popupMain').on('shown.bs.modal', function (e) { callback(e); }); } $("#popupMain").modal('show'); }, popupWContentClose: function () { $("#popupMainBody").html(''); if ($("#popupMain").is(':visible')) $("#popupMain").modal('toggle'); }, prompt: function (title, type, callback, option) { $.Engine.messages.attemptsToClose = 0; let defOptions = { title: title, centerVertical: true, inputType: type, callback: callback }; if (option) { for (let i in option) { defOptions[i] = option[i]; } } $.Engine.messages.lastPopup = bootbox.prompt(defOptions); }, closeLastPopup: function (force) { if (force) { bootbox.hideAll() } if (!$.Engine.messages.lastPopup && $.Engine.messages.attemptsToClose < 10) { console.log('not ready ', $.Engine.messages.attemptsToClose); $.Engine.messages.attemptsToClose++; setTimeout($.Engine.messages.closeLastPopup, 200); } console.log('ready ', $.Engine.messages.attemptsToClose); $.Engine.messages.attemptsToClose = 0; setTimeout(function () { if ($.Engine.messages.lastPopup) $.Engine.messages.lastPopup.modal('hide'); }, 200); }, confirm: function (description, callbacktrue) { bootbox.confirm({ message: description, buttons: { confirm: { label: 'Si', className: 'btn-success' }, cancel: { label: 'No', className: 'btn-danger' } }, callback: callbacktrue }); }, confirmTemplate: '' } /* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ $.Engine.data = { endPoint: $.Engine.costants.endPoint, toggleEnableButtons: function (main, state) { if (!state) { $(window).bind('beforeunload', function (e, v) { return 'C\'è un\'azione in corso, sei sicuro di voler chiudere?'; }); } else { $(window).unbind('beforeunload'); } $.each($(main).find('button'), function (i, el) { if (!state) { $(el).prop('disabled', 'disabled'); } else $(el).removeAttr('disabled'); }); }, get: function (data, callback, method) { if (!$.Engine.user.isInit) return setTimeout(function () { //console.log('user not init') $.Engine.data.get(data, callback, method) }, 50); method = (method) ? method : 'GET'; var url = $.Engine.data.endPoint; if ($.Engine.user.getTkn((data.hasOwnProperty('gettkn'))) && !data.hasOwnProperty('user')) { data.tkn = $.Engine.user.getTkn(); url = $.Engine.data.endPoint + '?tkn=' + $.Engine.user.getTkn(); } return $.ajax({ type: method, url: url, data: data, success: function (resp) { // console.log(resp, 'GET'); resp = (resp) ? JSON.parse(resp) : {}; if (resp.hasOwnProperty('em') && resp.em == 'no logged' && $.Engine.routes.actual != 'login') setTimeout(function () { $.Engine.routes.go('login'); }, 1000); callback(resp); }, error: function (resp) { $.Engine.messages.popup('Attenzione', 'Si è verificato un problema interno, abbiamo provveduto a segnalarlo al gruppo tecnico.', 'danger'); } }); }, post: function (data, callback) { return $.Engine.data.get(data, callback, 'POST') }, send: function (w) { var form = $('#' + w); $.Engine.data.toggleEnableButtons(form, 0); var data = new FormData(form[0]); var checkbox = form.find("input[type=checkbox]"); $.each(checkbox, function (key, val) { data.append($(val).attr('name'), $(this).is(':checked')) }) //var data = form.serialize(); //console.log(data); var callback = form.data('vks-callback'); if (callback == 'default' || utility.isNull(callback)) callback = $.Engine.data.response; //data.tkn = $.Engine.user.getTkn(); data.append('tkn', $.Engine.user.getTkn()); $.ajax({ type: "POST", url: $.Engine.data.endPoint + '?ref=' + $(form).attr('data-vks-ref') + '&name=' + $(form).attr('data-vks-name') + '&tkn=' + $.Engine.user.getTkn(), data: data, processData: false, contentType: false, success: function (resp) { try { resp = (resp) ? JSON.parse(resp) : {}; if (resp.hasOwnProperty('em') && resp.em == 'no logged' && $.Engine.routes.actual != 'login') setTimeout(function () { $.Engine.routes.go('login'); }, 1000); } catch (e) { $.Engine.messages.popup('Attenzione', 'Si è verificato un problema interno, abbiamo provveduto a segnalarlo al gruppo tecnico.', 'danger'); } $.Engine.data.toggleEnableButtons(form, 1); if (utility.isString(callback)) eval(callback + "(resp,w);"); else callback(resp, w); }, error: function (resp) { $.Engine.messages.popup('Attenzione', 'Si è verificato un problema interno, abbiamo provveduto a segnalarlo al gruppo tecnico.', 'danger'); $.Engine.data.toggleEnableButtons(form, 1); if (utility.isString(callback)) eval(callback + "(resp,w);"); else callback(resp, w); } }); }, response: function (resp, w) { if (resp.e || !resp.return) { $.Engine.messages.popup('Errore', resp.em, 'warning'); return false; } if (!$.Engine.data.temporalyMute) $.Engine.messages.popup('Perfetto', 'Operazione completata', 'success'); $.Engine.data.temporalyMute = false; var postinsert = $('#' + w).find('#return'); if (postinsert.length && (postinsert = $(postinsert).val()) != '0') { if (postinsert.indexOf(',') >= 0) { var args = postinsert.split(','); var urlplus = ''; for (a in args) { if (a == 0) continue; if (a == 2) { urlplus += '_'; } else if (a > 2) { urlplus += '--'; } var dato = (resp.return.hasOwnProperty(args[a])) ? resp.return[args[a]] : args[a]; urlplus += dato; } $.Engine.routes.go(args[0], urlplus); } else $.Engine.routes.go(postinsert); } if (w.indexOf('mod') !== 0) $('#' + w).trigger("reset"); return true; } } /* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ window.addEventListener('popstate', function (event) { var xx = window.location.pathname.replace('/', '').split('?'); $.Engine.routes.go(xx[0].replace('.html', ''), xx[1], '#main-container-app'); }); $.Engine.routes = { busy: false, maxSecondToChangePage: 5, actual: null, actualPageTitle: '', mainContent: '#main-container-app', routes: { 'login': 'login.html', 'home': 'index.html', 'contatti': 'contatti.html', '404': '404.html', }, comeBack: function () { var xx = window.location.pathname.replace('/', '').split('?'); $.Engine.routes.go(xx[0].replace('.html', ''), xx[1], '#main-container-app'); }, go: function (w, data, internal, callback, newpage) { /* let now = new Date(); now = now.getTime() / 1000; if ($.Engine.routes.busy) { if ((now - $.Engine.routes.busy) <= $.Engine.routes.maxSecondToChangePage) { return; } } $.Engine.routes.busy = now; */ if (!$.Engine.routes.routes.hasOwnProperty(w)) return; if (!data) data = '' if (newpage) { window.open($.Engine.routes.routes[w] + "?" + data.replace('?', '&')); return; } if (internal) { if (!callback) callback = function () { $(internal).ready(function () { window.history.pushState(null, $.Engine.routes.actualPageTitle, $.Engine.routes.routes[w] + ((data) ? data : '')); window.document.title = $.Engine.routes.actualPageTitle; }); } $(internal).load($.Engine.routes.routes[w] + "?part=1&" + data.replace('?', '&'), function () { // $.Engine.routes.busy = null; callback() }); return; } else location.href = $.Engine.routes.routes[w] + data; return; }, prev: function () { location.href = document.referrer; }, refresh: function () { location.reload(); }, softRefresh: function (c) { c = (c) ? c : null; //console.log(c) let u = window.location.href; if (u.indexOf('?') > 0) u += '&part=1'; else u += '?part=1'; $($.Engine.routes.mainContent).load(u, c); }, init: function (callback) { $.Engine.routes.callback.preInit(); var m = location.href.toString().match(/.*\/(.+?)\./); $.Engine.routes.actual = 'home'; if (m && m.length > 1) $.Engine.routes.actual = m[1]; if ($.Engine.routes.actual != 'login' && !$.Engine.user.isLogged()) { $.Engine.storage.set('pre_login_url', location.href.toString()); return $.Engine.routes.go('login'); } let pre_login_url = $.Engine.storage.get('pre_login_url'); if ($.Engine.user.isLogged() && pre_login_url) { $.Engine.storage.clear('pre_login_url'); location.href = pre_login_url; } $.Engine.routes.callback.postInit(); $.Engine.routes.elaborateView(); if (callback) callback(); }, callback: { preInit: function () { }, postInit: function () { }, postRouting: function () { } }, parser: { placeHolder: function () { var data = $.find('*[data-vks-place]'); $.each(data, function (i, el) { var xx = $(el).attr('data-vks-place').split('.'); var out = $.Engine; for (a in xx) { if (xx[a]) out = out[xx[a]]; else out = 'NONE'; } $(el).html(out); $(el).removeAttr('data-vks-place'); }); }, loop: function () { var data = $.find('*[data-vks-loop]'); $.each(data, function (i, el) { var parent = $(el).parent(); var xx = $(el).attr('data-vks-loop').split('.'); var out = $.Engine; var tmpcallback = false, tmpinitcallback = false; if ($(el).attr('data-vks-call-callback')) { tmpcallback = $(el).attr('data-vks-call-callback'); $(el).removeAttr('data-vks-call-callback'); } if ($(el).attr('data-vks-call-init')) { tmpinitcallback = $(el).attr('data-vks-call-init'); $(el).removeAttr('data-vks-call-init'); } $(el).removeAttr('data-vks-loop'); if (xx[0] == 'api') { var putdata = {"ref": xx[2], "name": xx[3]}; if (xx.length > 4) { for (var ix = 4; ix < xx.length; ix++) { var tmpx = xx[ix].split(':'); putdata[tmpx[0]] = tmpx[1]; } } /*if (xx[4]) { putdata.id = xx[4]; }*/ $.Engine.data[xx[1]](putdata, function (resp) { if (tmpinitcallback) resp = eval(tmpinitcallback)(resp); $.Engine.routes.loop(resp, $(el)); if (tmpcallback) { if (tmpcallback.indexOf('(') != -1) eval(tmpcallback); else eval(tmpcallback)(resp, parent); } }); } else if (xx[0] == 'stored') { var name = xx[1]; var resp = $.Engine; for (oi = 2; oi < xx.length; oi++) { if (resp.hasOwnProperty(xx[oi])) resp = resp[xx[oi]]; else { resp = null; oi = xx.length; } } $(el).removeAttr('data-vks-loop'); resp = {return: resp}; if (tmpinitcallback) resp = eval(tmpinitcallback)(resp); $.Engine.routes.loop(resp, $(el)); if (tmpcallback) { if (tmpcallback.indexOf('(') != -1) eval(tmpcallback); else eval(tmpcallback)(resp, parent); } } }); }, call: function () { var data = $.find('*[data-vks-call]'); $.each(data, function (i, el) { var xx = $(el).data('vks-call').split('.'); var tmpcallback = false; if ($(el).data('vks-call-callback')) { tmpcallback = $(el).data('vks-call-callback'); $(el).removeAttr('data-vks-call-callback'); } var out = $.Engine; var name = xx[0]; var putdata = {"ref": xx[3], "name": xx[4]}; if (xx[1] == 'api') { if (xx.length > 5 && xx[5].indexOf(':') >= 0) { for (var ix = 5; ix < xx.length; ix++) { var tmpx = xx[ix].split(':'); putdata[tmpx[0]] = tmpx[1]; } } else { putdata.id = xx[5]; } $.Engine.data[xx[2]](putdata, function (resp) { console.log('quiiii'); $.Engine.routes.bind(resp, name); if (tmpcallback) { if (tmpcallback.indexOf('(') != -1) { eval(tmpcallback); } else { eval(tmpcallback)(resp, name); } } }); } $(el).removeAttr('data-vks-call'); }); }, route: function () { var data = $.find('*[data-vks-route]'); $.each(data, function (i, el) { if (!$(el).data('parsed')) { $(el).data('parsed', 1); $(el).on('click', function (e) { e.preventDefault(); var val = $(this).data('vks-route'); var otherdata = null; if (val.indexOf('?') != -1) { var d = val.split('?'); var c = d[0]; var dtxt = val.replace(d[0] + "?", ""); val = c; otherdata = dtxt; } $.Engine.routes.go(val, otherdata, $.Engine.routes.mainContent); }); } }); } }, elaborateView: function () { $.Engine.routes.parser.placeHolder(); $.Engine.routes.parser.loop(); $.Engine.routes.parser.call(); $.Engine.routes.parser.route(); $('button[type=cancel]').on('click', function (e) { var form = $(this).parents('form'); var id = $(this).parents('form').attr('id'); if (id.indexOf('mod') === 0) { $.Engine.routes.prev(); } else form.trigger("reset"); e.preventDefault(); }); }, loop: function (data, dom_el) { var template = $(dom_el).outerHTML().toString().replace('hidden', ''); var parent = $(dom_el).parent(); var pattern = '', def = '', defNull = ''; parent.html(''); if (data.return) { $.each(data.return, function (i, el) { var tmp_template = template.toString(); $.each(el, function (field, value) { /* def = defNull.toString(); if (field.indexOf('|') > 0) { field = field.split('|'); def = field[1]; field = field[0]; }*/ value = (utility.isNull(value)) ? def : value; pattern = new RegExp("\{" + field + "\}", "g"); tmp_template = tmp_template.replace(pattern, value); pattern = new RegExp("\%7B" + field + "\%7D", "g"); tmp_template = tmp_template.replace(pattern, value); }) $(parent).append(tmp_template); }); } }, bind: function (data, name) { if (!data.return) data.return = {}; var elements = $.find('*[data-vks-bind-call=' + name + ']'); $.each(elements, function (i, el) { var elname = $(el).attr('data-vks-bind-value'); if (data.return.hasOwnProperty(elname)) var out = data.return[elname]; else var out = ''; if (out == null || out == 'null') out = ''; if (out == '') { let not_null = $(el).attr('data-vks-bind-not-null'); if (not_null) { eval(not_null); return; } } var format = ($(el).attr('data-vks-bind-value-format')) ? $(el).attr('data-vks-bind-value-format') : '{data}'; var out = format.replace('{data}', out); if ($(el).attr('data-vks-bind-value-attr')) { var att = $(el).attr('data-vks-bind-value-attr'); $(el).attr(att, out); return; } var tag = $(el).prop("tagName"); switch (tag.toLowerCase()) { case 'select': $(el).attr('data-vks-val', out); $(el).val(out); $(el).trigger('change'); break; case 'input': if ($(el).attr('type') == 'checkbox') { $(el).prop('checked', ((parseInt(out) == 1) ? true : false)); break; } case 'textarea': $(el).val(out); break; case 'holder': $(el).replaceWith(out); break; default: $(el).html(out); } }); } } /* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ $.Engine.user = { logoutTimer: null, data: {}, isInit: false, isLogged: function (mute) { var now = new Date(); if ($.Engine.user.data && $.Engine.user.data.tkn) { if ($.Engine.user.data.expireDate > (now.getTime() / 1000)) { if ($.Engine.user.logoutTimer == null) { $.Engine.user.logoutTimer = setTimeout(function () { clearTimeout($.Engine.user.logoutTimer); $.Engine.user.logoutTimer = null; $.Engine.user.isLogged(); }, 20000); } return true; } else if (!mute) { $.Engine.user.logout(); $.Engine.messages.popup('Sessione Scaduta', null, 'warning'); } } $.Engine.user.data = {}; return false; }, getTkn: function (mute) { if (!$.Engine.user.isLogged(mute)) return false; return $.Engine.user.data.tkn; }, login: function (user, password) { $.Engine.data.get({"user": user, "password": password, "gettkn": true}, $.Engine.user.callback.checkLogin, 'get'); }, logout: function () { $.Engine.user.data = {}; $.Engine.user.save(); $.Engine.data.endPoint = $.Engine.costants.endPoint; $.Engine.data.get({"logout": "exit"}, function (resp) { $.Engine.user.callback.logout(); $.Engine.routes.init() }); }, callback: { logout: function () { }, checkLogin: function (resp) { $.Engine.user.callback.beforeCheck(resp); if (!resp || resp.e) { $.Engine.user.data = {}; $.Engine.user.save(); $.Engine.messages.popup('Errore Login', resp.em, 'warning'); $.Engine.user.callback.loginError(resp); return; } $.Engine.user.data = resp.return; $.Engine.user.data.roletxt = i18next.t('app.roles.' + $.Engine.user.data.role); $.Engine.user.save(); if ($.Engine.user.callback.loginOk(resp)) { $.Engine.routes.go('home'); } }, beforeCheck: function (resp) { return true; }, loginError: function (resp) { return true; }, loginOk: function (resp) { return true; }, postInitLogged: function (user) { return true; }, postInitNoLogged: function () { return true; }, }, save: function () { $.Engine.storage.set('user', $.Engine.user.data); }, init: function () { $.Engine.user.isInit = false; var user = $.Engine.storage.get('user'); if (user) { $.Engine.user.data = user; $.Engine.user.callback.postInitLogged(user); } else { $.Engine.user.data = null; $.Engine.user.callback.postInitNoLogged(); } $.Engine.user.isInit = true; } };/* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ $.Engine.storage = { storage: window.localStorage, globalData: {}, get: function (w) { var data = $.Engine.storage.storage.getItem(w); if (data && data.indexOf('{') >= 0) return JSON.parse(data); return data; }, set: function (w, data) { if (typeof data === 'object') data = JSON.stringify(data); $.Engine.storage.storage.setItem(w, data); }, clear: function (w) { $.Engine.storage.storage.removeItem(w); } };/* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ var utility = { toggle: function (id) { let el = (utility.isString(id)) ? $('#' + id) : id; if (el.is(":visible")) utility.hide(el); else utility.show(el); }, show: function (id) { let el = (utility.isString(id)) ? $('#' + id) : id; el.removeClass('hidden'); el.show(); }, hide: function (id) { let el = (utility.isString(id)) ? $('#' + id) : id; el.hide(); }, clone: function (obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr]; } return copy; }, capitalize: function (el) { jQuery(document).ready(function ($) { $(el).change(function (event) { var textBox = event.target; var start = textBox.selectionStart; var end = textBox.selectionEnd; textBox.value = textBox.value.charAt(0).toUpperCase() + textBox.value.slice(1); textBox.setSelectionRange(start, end); }); }); }, zerofilled: function (number, width) { width -= number.toString().length; if (width > 0) return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number; return number + ""; }, getSessionId: function () { var jsId = document.cookie.match(/PHPSESSID=[^;]+/); if (jsId != null) { if (jsId instanceof Array) jsId = jsId[0].substring(10); else jsId = jsId.substring(10); } return jsId; }, isString: function (a) { return (typeof a === "string" || a instanceof String); }, isNumber: function (a) { return (typeof a === "number"); }, isBoolean: function (a) { return (typeof a === "boolean"); }, isObject: function (a) { if (a === null) { return false; } return ((typeof a === 'function') || (typeof a === 'object')); }, isFunction: function (a) { if (a === null) { return false; } return (typeof a === 'function'); }, purifyString: function (a) { if (!a) return ''; return a.replace(/[\W_]+/g, "."); }, getFileExtension: function (a) { a = a.split('.'); return a[a.length - 1].toLowerCase(); }, isNull: function (a) { if (a === undefined || a === null || a == 'null') return true; return false; }, replaceAll: function (txt, vett, defNull) { var r = '', x = '', def = '', v = null; for (i in vett) { r = '\{?\{' + i + '\}\}?' r = new RegExp(r, "g"); let r2 = '\%7B' r2 = new RegExp(r2, "g"); let r3 = '\%7D' r3 = new RegExp(r3, "g"); def = defNull; v = vett[i]; if (utility.isObject(vett[i])) { def = (vett[i].hasOwnProperty('default')) ? vett[i].default : defNull; v = vett[i].val; } v = (utility.isNull(v)) ? def : v; txt = txt.replace(r2, '{'); txt = txt.replace(r3, '}'); txt = txt.replace(r, v); } return txt; }, removeByDistance: function (dist, tag, el) { var x = $(el); for (let i = 0; i < dist; i++) x = $(x).parent(); $(x).remove(); }, retainDataDataTable: function (dt, id) { this[id] = {p: null, f: null}; var info = dt.page.info(); this[id].p = info.page + 1; this[id].f = dt.order(); if (this[id].f.hasOwnProperty(0) && this[id].f[0].hasOwnProperty(0)) if (this[id].f[0][0] == 0) { this[id].f = null; //[0][0] = 1; } }, getDataDataTable: function (dt, id) { if (this.hasOwnProperty(id) && this[id].hasOwnProperty('f') && this[id].f) dt.order(this[id].f).draw(); if (this.hasOwnProperty(id) && this[id].hasOwnProperty('p')) $('a[data-dt-idx=' + this[id].p + ']').trigger('click') }, hasRealProperty: function (a, b) { //a.split(','); b = b.split('.'); for (let i in b) { if (!a.hasOwnProperty(b[i])) return false; else a = a[b[i]]; } return true; //return jQuery('
').append(this.eq(0).clone()).html(); }, // private property _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode: function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = utility._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + utility._keyStr.charAt(enc1) + utility._keyStr.charAt(enc2) + utility._keyStr.charAt(enc3) + utility._keyStr.charAt(enc4); } return output; }, // public method for decoding decode: function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = utility._keyStr.indexOf(input.charAt(i++)); enc2 = utility._keyStr.indexOf(input.charAt(i++)); enc3 = utility._keyStr.indexOf(input.charAt(i++)); enc4 = utility._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = utility._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode: function (string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode: function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; }, copyToClipBoard: function (elem) { // create hidden text element, if it doesn't already exist var targetId = "_hiddenCopyText_"; var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; var origSelectionStart, origSelectionEnd; if (isInput) { // can just use the original source element for the selection and copy target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else { // must use a temporary form element for the selection and copy target = document.getElementById(targetId); if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target); } target.textContent = elem.textContent; } // select the content var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // copy the selection var succeed; try { succeed = document.execCommand("copy"); } catch (e) { succeed = false; } // restore original focus if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // restore prior selection elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // clear temporary content target.textContent = ""; } return succeed; }, encryptDecrypt: function (key, str) { var s = [], j = 0, x, res = ''; for (var i = 0; i < 256; i++) { s[i] = i; } for (i = 0; i < 256; i++) { j = (j + s[i] + key.charCodeAt(i % key.length)) % 256; x = s[i]; s[i] = s[j]; s[j] = x; } i = 0; j = 0; for (var y = 0; y < str.length; y++) { i = (i + 1) % 256; j = (j + s[i]) % 256; x = s[i]; s[i] = s[j]; s[j] = x; res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]); } return res; }, CryptoJSAesEncrypt: function (passphrase, plain_text) { var salt = CryptoJS.lib.WordArray.random(256); var iv = CryptoJS.lib.WordArray.random(16); //for more random entropy can use : https://github.com/wwwtyro/cryptico/blob/master/random.js instead CryptoJS random() or another js PRNG var key = CryptoJS.PBKDF2(passphrase, salt, {hasher: CryptoJS.algo.SHA512, keySize: 64 / 8, iterations: 999}); var encrypted = CryptoJS.AES.encrypt(plain_text, key, {iv: iv}); var data = { ciphertext: CryptoJS.enc.Base64.stringify(encrypted.ciphertext), salt: CryptoJS.enc.Hex.stringify(salt), iv: CryptoJS.enc.Hex.stringify(iv) } return JSON.stringify(data); }, CryptoJSAesDecrypt: function (passphrase, encrypted_json_string) { var obj_json = JSON.parse(encrypted_json_string); var encrypted = obj_json.ciphertext; var salt = CryptoJS.enc.Hex.parse(obj_json.salt); var iv = CryptoJS.enc.Hex.parse(obj_json.iv); var key = CryptoJS.PBKDF2(passphrase, salt, {hasher: CryptoJS.algo.SHA512, keySize: 64 / 8, iterations: 999}); var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv}); return decrypted.toString(CryptoJS.enc.Utf8); }, scrollToAnchor: function (t) { $('*').animate({scrollTop: t.offset().top}, 'slow'); }, randomize: function (min, max) { min = min ? min : 0; max = max ? max : 1000; min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }, findByKey: function (data, key, value) { for (let v of data) { if (v[key] == value) return v; } return false; } } jQuery.fn.outerHTML = function () { return jQuery('
').append(this.eq(0).clone()).html(); }; /* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ var localize = function () { if (!i18initok) return setTimeout(localize, 100); $('*').localize(); } $.Engine.routes.routes = { 'login': 'login.html', 'home': 'index.html', 'agencyprofile': 'agencyprofile.html', 'agdashboard': 'agdashboard.html', // planner 'planner': 'planner.html', // agency 'agency': 'agency.html', 'agencies': 'agencies.html', 'addagency': 'addagency.html', 'modagencypassword': 'modagencypassword.html', 'changeagencypassword': 'changeagencypassword.html', // settings 'permissions': 'permissions.html', 'addpermission': 'addpermission.html', 'addapi': 'addapi.html', 'templates': 'templates.html', // faq 'faq': 'faq.html', // dictionaries 'dictionaries': 'dictionaries.html', //menu 'addmenu': 'addmenu.html', 'getmenus': 'getmenus.html', 'addmenucategory': 'addcategory.html', 'getmenucategories': 'getcategories.html', 'addproduct': 'addproduct.html', 'getproducts': 'getproducts.html', 'getmenuseattypes': 'getmenuseattypes.html', 'relateunrelate': 'relateunrelate.html', 'modproductphoto': 'modproductphoto.html', //esercizi 'addplace': 'addplace.html', 'getplaces': 'getplaces.html', 'addplacecategory': 'addplacecategory.html', 'getplacecategories': 'getplacecategories.html', 'modphotos': 'modphotos.html', //postazioni 'addmultiseat': 'addmultiseat.html', 'addseat': 'addseat.html', 'getseats': 'getseats.html', 'addseattype': 'addseattype.html', 'getseattypes': 'getseattypes.html', //clienti 'addcustomer': 'addcustomer.html', 'getcustomers': 'getcustomers.html', 'modcustomerpassword': 'modcustomerpassword.html', //ordini 'addorder': 'addorder.html', 'getorders': 'getorders.html', 'getactualorders': 'getactualorders.html', 'gettakeawayorders': 'gettakeawayorders.html', 'orderdetails': 'orderdetails.html', //prenotazioni 'addreservation': 'addreservation.html', 'getreservations': 'getreservations.html', 'getactualreservations': 'getactualreservations.html', 'reservation': 'reservation.html', 'reservationchangestatus': 'reservationchangestatus.html', //camerieri 'addwaiter': 'addwaiter.html', 'getwaiters': 'getwaiters.html', 'modwaiterpassword': 'modwaiterpassword.html', 'getwaitersrequests': 'getwaitersrequests.html', //campagne 'addcampaign': 'addcampaign.html', 'getcampaigns': 'getcampaigns.html', } $.Engine.routes.callback.postRouting = function () { // $('.page-loader-wrapper').fadeIn(); $.Engine.routes.init(function () { localize(); CustomJs(); if (window.innerWidth < 770) $(".sidebar").toggleClass("open"); $('.page-loader-wrapper').hide(); //$.Engine.parts.cards.init(); // $.Engine.parts.checkbox.init(); /* $("form").validate({ errorElement: "em", errorPlacement: function (error, element) { error.addClass("help-block"); if (element.prop("type") === "checkbox") { error.insertAfter(element.parent("label")); } else { error.insertAfter(element); } }, highlight: function (element, errorClass, validClass) { $(element).parents(".col-5").addClass("alert alert-danger").removeClass("alert alert-success"); }, unhighlight: function (element, errorClass, validClass) { $(element).parents(".col-5").addClass("alert alert-success").removeClass("alert alert-danger"); } });*/ }); } $.Engine.routes.callback.preInit = function () { $('.page-loader-wrapper').show(); } $.Engine.user.getEndPoint = function (user) { let vksPromises = jQuery.Deferred(); //$.Engine.data.endPoint = $.Engine.costants.endPointMain; $.Engine.data.get({'ref': 'agency', 'name': 'getEndPoint', user: user}, function (resp) { if (!resp.e && resp.return) { vksPromises.resolve(resp.return) } else vksPromises.reject(resp.em) }) return vksPromises.promise(); } $.Engine.routes.callback.postInit = function () { var actual = $('.menu-item[href="' + $.Engine.routes.routes[$.Engine.routes.actual] + '"]'); if ($(actual).hasClass('has-sub')) { $(actual).addClass('open'); } else { $(actual).parents('.nav-item.has-sub').addClass('open'); } /*$.each($('label.required'), function (i, el) { $(el).text('* ' + $(el).text()); });*/ $('#vks-login').on('click', function () { let user = $('#vks-login-user').val(); let pass = $('#vks-login-password').val(); if (!user) { $.Engine.messages.popup(i18next.t('app.login.nouser'), null, 'warning'); return; } $.Engine.user.getEndPoint(user).then(function (endPoint) { document.location.href = 'https://' + endPoint + '.restaurant.manage.bookingsafe.it/login.html?user=' + user; }, function (resp) { $.Engine.messages.popup(i18next.t('app.login.usernotfound'), null, 'warning'); }); return; if (!pass) { if ($.Engine.data.endPoint && $.Engine.data.endPoint !== $.Engine.costants.endPointMain) { $.Engine.messages.popup(i18next.t('app.login.nopassword'), null, 'warning'); return; } // call for end point } else { } return $.Engine.user.login(user, pass); }); $('#vks-logout').on('click', function () { return $.Engine.user.logout(); }); $('#loader').fadeOut(); // $.Engine.parts.checkbox.init(); localize(); return; } $.Engine.user.callback.logout = function () { $.Engine.data.endPoint = 'https://manage.bookitsafe.it/vksEngine/store.php' $.Engine.data.get({'delete': 1}, function (resp) { }); $.Engine.data.endPoint = $.Engine.costants.endPoint; } $.Engine.user.callback.loginOk = function (resp) { $.Engine.data.endPoint = 'https://manage.bookitsafe.it/vksEngine/store.php' $.Engine.data.get({}, function (resp) { $.Engine.routes.go('home'); }); $.Engine.data.endPoint = $.Engine.costants.endPoint; return false; } $.Engine.user.callback.postInitLogged = function (user) { $.Engine.parts.comunications.init(); }; $.Engine.user.callback.postInitNoLogged = function () { }; $.Engine.parts = {} $.Engine.parts.finder = { init: function () { $('#finder-engine').on('keypress', function (e) { if (e.which == 13) { let v = $('#finder-engine').val(); $('#finder-engine').val('') $.Engine.parts.finder.search(v); } }) }, search: function (e) { e = e.toLowerCase(); if (e.indexOf('tkt') >= 0) { $.Engine.routes.go('order', '?id=' + e.replace('tkt', '').replace('-', '')); } } } $.Engine.parts.condominium = { id: null, callback: { afterRenderCondominiumSelect: function (resp) { var select = $('#c_idCondominium'); $(select).prepend('') var val = $(select).data('vks-val'); if (val) { $(select).val(val); } if ($.Engine.parts.condominium.id) $(select).val($.Engine.parts.condominium.id).trigger('change'); else $(select).val(0).trigger('change'); select.select2(); } } } $.Engine.parts.occupant = { id: null, data: null, callback: { savedata: function (resp, w) { if (resp.hasOwnProperty('return')) $.Engine.parts.occupant.data = resp.return; else $.Engine.parts.occupant.data = null; }, reload: function (resp, w) { if ($.Engine.data.response(resp, w)) { if ($("#tb_occupants").length) { $("#tb_occupants").jsGrid('search'); $.Engine.messages.popupWContentClose(); } } }, } } $.Engine.parts.order = { id: null, callback: { preloadModOrder: function (resp, w) { if (resp.return) { if (resp.return.hasOwnProperty('files') && resp.return.files.length > 0) { var t = $("#order-list-files").html().toString(); $("#order-list-files").html(''); for (i in resp.return.files) { var tempfile = t.toString(); tempfile = tempfile.replace('hidden', ''); tempfile = tempfile.replace(/\{name\}/g, resp.return.files[i][0]); tempfile = tempfile.replace(/\{url\}/g, resp.return.files[i][1]); tempfile = tempfile.replace('{icon}', $.Engine.parts.basics.getFileIcon(resp.return.files[i][0])); $("#order-list-files").append(tempfile) } } if (resp.return.dateRemind) { var $inputT = $('.recallTime').pickatime(); var $inputD = $('.recallData').pickadate(); var pickerT = $inputT.pickatime('picker'); var pickerD = $inputD.pickadate('picker'); var t = resp.return.dateRemind.split(' '); pickerD.set('select', resp.return.dateRemind, {format: 'yyyy-mm-dd hh:i'}); pickerT.set('select', resp.return.dateRemind, {format: 'yyyy-mm-dd hh:i'}); } let txtCat = ((resp.return.idCategory_title) ? resp.return.idCategory_title : '') if (resp.return.idSubCategory_title) txtCat += ' / ' + resp.return.idSubCategory_title; $('.filter-option.pull-left').html(txtCat); } else { $('#modorder').html('

' + i18next.t('app.basic.nodata') + '

') } }, reload: function (resp, w) { if ($.Engine.data.response(resp, w)) { $.Engine.messages.popupWContentClose(); if ($.Engine.routes.actual == 'order') { $.Engine.routes.softRefresh(); } else if ($.Engine.routes.actual == 'orders') loadOrders(); } } } } $.Engine.parts.orderJob = { id: null, data: null, templates: {}, prefetchFiles: function (resp) { if (!resp.return) return resp; var ret = []; for (i in resp.return) { ret.push({name: resp.return[i][0], link: resp.return[i][1], icon: $.Engine.parts.basics.getFileIcon(resp.return[i][0])}) } return {"return": ret}; }, elaborateOrderData: function (a) { if (a.return) { $.Engine.parts.orderJob.data = a = a.return; $.Engine.parts.orderJob.data.fileshtml = []; for (let i in $.Engine.parts.orderJob.data.files) { var tempfile = $.Engine.parts.orderJob.templates.orderFile.toString(); tempfile = tempfile.replace('hidden', ''); tempfile = tempfile.replace(/\{name\}/g, $.Engine.parts.orderJob.data.files[i][0]); tempfile = tempfile.replace(/\{url\}/g, $.Engine.parts.orderJob.data.files[i][1]); tempfile = tempfile.replace('{icon}', $.Engine.parts.basics.getFileIcon($.Engine.parts.orderJob.data.files[i][0])); $.Engine.parts.orderJob.data.fileshtml.push(tempfile); } if ($.Engine.parts.orderJob.data.providersData) { for (i in $.Engine.parts.orderJob.data.providersData) { $.Engine.parts.orderJob.data.providersData[i].hasphone = 'hidden'; $.Engine.parts.orderJob.data.providersData[i].phone = ''; if (!utility.isNull($.Engine.parts.orderJob.data.providersData[i].phone1)) { $.Engine.parts.orderJob.data.providersData[i].hasphone = ''; $.Engine.parts.orderJob.data.providersData[i].phone = $.Engine.parts.orderJob.data.providersData[i].phone1; } else if (!utility.isNull($.Engine.parts.orderJob.data.providersData[i].phone2)) { $.Engine.parts.orderJob.data.providersData[i].hasphone = ''; $.Engine.parts.orderJob.data.providersData[i].phone = $.Engine.parts.orderJob.data.providersData[i].phone2; } else if (!utility.isNull($.Engine.parts.orderJob.data.providersData[i].phone3)) { $.Engine.parts.orderJob.data.providersData[i].hasphone = ''; $.Engine.parts.orderJob.data.providersData[i].phone = $.Engine.parts.orderJob.data.providersData[i].phone3; } } } if (a.hasOwnProperty('jobs') && a.jobs.length > 0) { $.Engine.parts.orderJob.data.responseJob = {}; for (let o in a.jobs) { if (a.jobs[o].idOrderJob > 0) { if (!$.Engine.parts.orderJob.data.responseJob.hasOwnProperty(a.jobs[o].idOrderJob)) { $.Engine.parts.orderJob.data.responseJob[a.jobs[o].idOrderJob] = []; } $.Engine.parts.orderJob.data.responseJob[a.jobs[o].idOrderJob].push(a.jobs[o]); } else { let title = a.jobs[o].title; let icon = 'bullseye'; switch (a.jobs[o].idType_title) { case "commitment": icon = "briefcase"; title = title + " " + i18next.t('app.basic.at') + " " + a.jobs[o].destinationName break; case "closing": icon = ""; title = title break; case "extimate": icon = "money"; title = title break; case "comment": icon = "comment"; title = title break; } a.jobs[o].icon = icon; a.jobs[o].title = title; } } } } }, OLDloadTimeline: function (a, b, c) { if (a.return) { $.Engine.parts.orderJob.data = a = a.return; if ($.Engine.parts.orderJob.data.providersData) { for (i in $.Engine.parts.orderJob.data.providersData) { $.Engine.parts.orderJob.data.providersData[i].hasphone = 'hidden'; $.Engine.parts.orderJob.data.providersData[i].phone = ''; if (!utility.isNull($.Engine.parts.orderJob.data.providersData[i].phone1)) { $.Engine.parts.orderJob.data.providersData[i].hasphone = ''; $.Engine.parts.orderJob.data.providersData[i].phone = $.Engine.parts.orderJob.data.providersData[i].phone1; } else if (!utility.isNull($.Engine.parts.orderJob.data.providersData[i].phone2)) { $.Engine.parts.orderJob.data.providersData[i].hasphone = ''; $.Engine.parts.orderJob.data.providersData[i].phone = $.Engine.parts.orderJob.data.providersData[i].phone2; } else if (!utility.isNull($.Engine.parts.orderJob.data.providersData[i].phone3)) { $.Engine.parts.orderJob.data.providersData[i].hasphone = ''; $.Engine.parts.orderJob.data.providersData[i].phone = $.Engine.parts.orderJob.data.providersData[i].phone3; } } } var temp = $.Engine.parts.orderJob.templates.main.toString(); temp = temp.replace('{title}', a.title); temp = temp.replace('{description}', a.description); temp = temp.replace('{data}', a.dateInsertIT); temp = temp.replace('{idCondominium}', a.idCondominium); temp = temp.replace('{idOccupant}', a.idOccupant); temp = temp.replace('{nfiles}', (a.files.length > 0) ? a.files.length : 0); temp = temp.replace('{nproviders}', a.countProviders); $('#timeline-in').append(temp) var mt = 0; var title = ''; var icon = ''; var responseJob = []; if (a.hasOwnProperty('jobs') && a.jobs.length > 0) { for (o in a.jobs) { if (a.jobs[o].idOrderJob > 0) { responseJob.push(a.jobs[o]); } else { title = a.jobs[o].title; switch (a.jobs[o].idType_title) { case "commitment": icon = "briefcase"; title = title + " " + i18next.t('app.basic.at') + " " temp = $.Engine.parts.orderJob.templates.text.toString(); break; case "closing": icon = ""; title = title temp = $.Engine.parts.orderJob.templates.close.toString(); break; case "extimate": icon = "money"; title = title temp = $.Engine.parts.orderJob.templates.text.toString(); break; case "comment": icon = "comment"; title = title temp = $.Engine.parts.orderJob.templates.text.toString(); break; default: icon = 'bullseye'; temp = $.Engine.parts.orderJob.templates.text.toString(); break; } var mt = (o % 2) ? 4 : 0; temp = utility.replaceAll(temp, { 'mt': mt, 'title': title, 'destinationName': a.jobs[o].destinationName, 'id': a.jobs[o].id, 'idDestination': a.jobs[o].idDestination, 'senderName': a.jobs[o].senderName, 'description': a.jobs[o].description, 'data': a.jobs[o].dateInsertIT, 'icon': icon }, '-') /* temp = temp.replace('{mt}', mt); temp = temp.replace('{title}', title); temp = temp.replace('{destinationName}', a.jobs[o].destinationName); temp = temp.replace(/\{id\}/g, a.jobs[o].id); temp = temp.replace(/\{idDestination\}/g, a.jobs[o].idDestination); temp = temp.replace('{senderName}', a.jobs[o].senderName); temp = temp.replace('{description}', a.jobs[o].description); temp = temp.replace('{data}', a.jobs[o].dateInsertIT); temp = temp.replace('{icon}', icon);*/ $('#timeline-in').append(temp); } } $.Engine.parts.orderJob.loadResponseTimeline(responseJob); } } }, loadResponseTimeline: function (responseJob, reset) { var resetted = []; // check responses if (responseJob.length > 0) { for (o in responseJob) { if (reset && resetted.indexOf(responseJob[o].idOrderJob) === -1) { $('li[data-id-order-job=' + responseJob[o].idOrderJob + '] .response-holder').html('') resetted.push(responseJob[o].idOrderJob); } if (responseJob[o].files && responseJob[o].files.length > 0) { var contFiles = $(''); for (f in responseJob[o].files) { let tempfile = $.Engine.parts.orderJob.templates.orderJobResponseFile.toString(); tempfile = utility.replaceAll(tempfile, { 'name': responseJob[o].files[f][0], 'url': responseJob[o].files[f][1], 'icon': $.Engine.parts.basics.getFileIcon(responseJob[o].files[f][0]) }, '-') contFiles.append(tempfile) } contFiles = contFiles.prop('outerHTML'); } else { var contFiles = ''; } var temp = $.Engine.parts.orderJob.templates.orderJobResponse.toString(); temp = utility.replaceAll(temp, { 'senderName': responseJob[o].senderName, 'description': responseJob[o].description, 'data': responseJob[o].dateInsertIT, 'files': contFiles }, '') $('li[data-id-order-job=' + responseJob[o].idOrderJob + '] .response-holder').append(temp); } } $(".preview-dialog").dialog({ autoOpen: false, width: '50%', close: function () { $(this).find("img").attr('src', ''); }, modal: true }); $('.preview-dialog-btn').on('click', function () { $(".preview-dialog img").attr('src', 'getFile.php?d=' + $(this).data('url') + '&p=1'); $(".preview-dialog").dialog("open"); }) }, reloadResponseTimeline: function (idOrderJob) { $.Engine.data.get({'ref': 'order', 'name': 'getOrderJobs', 'f_idOrderJob': idOrderJob, 'f_rich': 1}, function (resp) { if (resp.return) { $.Engine.parts.orderJob.loadResponseTimeline(resp.return, true); $(".preview-dialog").dialog({ autoOpen: false, width: '50%', close: function () { $(this).find("img").attr('src', ''); }, modal: true }); } }, 'POST') }, callback: { reload: function (resp, w) { if ($.Engine.data.response(resp, w)) { if ($("#tb_occupants").length) { $("#tb_occupants").jsGrid('search'); $.Engine.messages.popupWContentClose(); } } } } } $.Engine.parts.basics = { display: function (a, b) { $(b).removeClass('hidden'); }, getFileIcon: function (a) { var ext = utility.getFileExtension(a); switch (ext) { case 'pdf': return 'la-file-pdf-o'; break; case 'jpg': case 'jpeg': case 'png': case 'gif': return 'la-file-image-o'; break; case 'mp3': case 'mpu': case 'wav': return 'la-file-audio-o'; break; case 'zip': case 'rar': case 'gz': return 'la-file-archive-o'; break; case 'doc': case 'txt': case 'docx': case 'odt': case 'rft': return 'la-file-word-o'; break; case 'ppt': case 'pptx': return 'la-file-powerpoint-o'; break; case 'xls': case 'xlsx': case 'ods': return 'la-file-excel-o'; break; case 'avi': case 'mp4': case 'mkv': return 'la-file-video-o'; break; default: return 'la-file'; break; } }, callback: { renderSelectsWNew: function (resp, el) { var val = $(el).data('vks-val'); if (val) { $(el).val(val); } $(el).select2({ tags: true, createTag: function (params) { return { id: params.term, text: params.term, newOption: true } }, templateResult: function (data) { if (data.id === '') { return 'Digita un nuovo valore e dai invio per salvarlo'; } return data.text; } }); }, renderSelects: function (resp, el) { if ($(el).prop('nodeName').toString().toLowerCase() != 'select') el = $(el).parent(); var val = $(el).data('vks-val'); val = (val) ? val : ''; $(el).val(val); if ($(el).data('rendered')) return; var val = $(el).data('vks-val'); if (val) { $(el).val(val); } $(el).attr('data-rendered', 1); $(el).select2({ // minimumInputLength: 3, //tags: false, }); } } }; $.Engine.parts.cards = { init: function () { // Collapsible Card $('a[data-action="collapse"]').on('click', function (e) { e.preventDefault(); $(this).closest('.card').children('.card-content').collapse('toggle'); $(this).closest('.card').find('[data-action="collapse"] i').toggleClass('ft-minus ft-plus'); }); $('a[data-action="collapse"]').removeAttr('data-action'); // Toggle fullscreen $('a[data-action="expand"]').on('click', function (e) { e.preventDefault(); $(this).closest('.card').find('[data-action="expand"] i').toggleClass('ft-maximize ft-minimize'); $(this).closest('.card').toggleClass('card-fullscreen'); }); $('a[data-action="expand"]').removeAttr('data-action'); // Reload Card $('a[data-action="reload"]').on('click', function () { var block_ele = $(this).closest('.card'); // Block Element block_ele.block({ message: '
', timeout: 2000, //unblock after 2 seconds overlayCSS: { backgroundColor: '#FFF', cursor: 'wait', }, css: { border: 0, padding: 0, backgroundColor: 'none' } }); }); $('a[data-action="reload"]').removeAttr('data-action'); // Close Card $('a[data-action="close"]').on('click', function () { $(this).closest('.card').removeClass().slideUp('fast'); }); $('a[data-action="close"]').removeAttr('data-action'); } } $.Engine.parts.checkbox = { init: function () { $('.skin-line:not(.modalinset):not(.done) input').each(function () { var self = $(this), label = self.next(), label_text = label.text(); self.parents('.skin-line').addClass('done'); label.remove(); self.iCheck({ checkboxClass: 'icheckbox_line-blue', radioClass: 'iradio_line-blue', insert: '
' + label_text }); }); // Checkbox & Radio 2 $('.icheck_minimal:not(.modalinset):not(.done) input').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal', }); $('.icheck_minimal:not(.modalinset):not(.done)').addClass('done'); // Square Checkbox & Radio $('.skin-square:not(.modalinset):not(.done) input').iCheck({ checkboxClass: 'icheckbox_square-red', radioClass: 'iradio_square-red', }); $('.skin-square:not(.modalinset):not(.done)').addClass('done'); //Flat Checkbox & Radio $('.skin-flat:not(.modalinset):not(.done) input').iCheck({ checkboxClass: 'icheckbox_flat-green', radioClass: 'iradio_flat-green' }); $('.skin-flat:not(.modalinset):not(.done)').addClass('done'); // Polaris Checkbox & Radio $('.skin-polaris:not(.modalinset):not(.done) input').iCheck({ checkboxClass: 'icheckbox_polaris', radioClass: 'iradio_polaris', increaseArea: '-10%' }); $('.skin-polaris:not(.modalinset):not(.done)').addClass('done'); // Futurico Checkbox & Radio $('.skin-futurico:not(.modalinset):not(.done) input').iCheck({ checkboxClass: 'icheckbox_futurico', radioClass: 'iradio_futurico', increaseArea: '20%' }); $('.skin-futurico:not(.modalinset):not(.done)').addClass('done'); } } $.Engine.parts.audio = { play: function (what) { let tmp = new Date(); let id = 'sound' + tmp.getTime(); $('body').append(''); setTimeout(function () { $('#' + id).remove() }, 3000); } }; $.Engine.parts.operators = {callback: {}}; $.Engine.parts.comunications = { init: function () { if ($.Engine.user.isLogged()) { if ($.Engine.user.data.role == '005') { $.Engine.data.get({'ref': 'agency', 'name': 'getMineTopic'}, function (resp) { if (resp.return && !resp.e) { $.Engine.parts.comunications.signal.topic = resp.return; $.Engine.parts.comunications.signal.init(); } }); } /*$.Engine.data.get({'ref': 'comunication', 'name': 'getNotices'}, function (resp) { if (resp.return && resp.return.length) { for (let i in resp.return) { $.Engine.parts.comunications.addNotice(resp.return[i]); } } })*/ } }, setAsRead: function (id) { $.Engine.data.get({'ref': 'comunication', 'name': 'setNoticeAsRead', 'id': id}, function (resp) { if (resp.return) { $('#notice_up_' + id).remove(); $('#notice_up_media_' + id).remove(); let count = parseInt($('#notifier_count').data('count')); count--; $('#notifier_count').data('count', count); $('#notifier_count').html(count); $('#notifier_count-2').html(count + ' Nuov' + ((count > 1) ? 'e' : 'a')); if (count <= 0) { utility.hide('notifier_count'); utility.hide('notifier_count-2'); } else { $('#notifier_toggle').trigger('click'); } } }, 'POST'); }, setAsShow: function (id) { $.Engine.data.get({'ref': 'comunication', 'name': 'setNoticeAsShow', 'id': id}, function (resp) { }, 'POST'); }, addNotice: function (data) { let count = parseInt($('#notifier_count').data('count')); count++; $('#notifier_count').data('count', count); $('#notifier_count').html(count); $('#notifier_count-2').html(count + ' Nuov' + ((count > 1) ? 'e' : 'a')); utility.show('notifier_count'); utility.show('notifier_count-2'); $('.scrollable-container.media-list').prepend('
\n\
\n\
\n\
\n\
' + data.description + '
\n\ \n\ \n\ \n\ Segna come letto\n\ \n\
\n\
\n\
'); $.Engine.parts.comunications.setAsShow(data.id); }, signal: { topic: '', client: null, endPoint: 'broker.bookitsafe.it', port: 9001, init: function () { $.Engine.parts.comunications.signal.client = new Paho.MQTT.Client($.Engine.parts.comunications.signal.endPoint, $.Engine.parts.comunications.signal.port, "main_cond_" + Math.random()); $.Engine.parts.comunications.signal.client.onConnectionLost = $.Engine.parts.comunications.signal.onConnectionLost; $.Engine.parts.comunications.signal.client.onMessageArrived = $.Engine.parts.comunications.signal.onMessageArrived; $.Engine.parts.comunications.signal.connect(); }, connect: function () { var options = { useSSL: true, userName: "", password: "", //"Md6hH£44f", onSuccess: $.Engine.parts.comunications.signal.onConnect, onFailure: $.Engine.parts.comunications.signal.doFail } $.Engine.parts.comunications.signal.client.connect(options); }, onConnect: function () { $.Engine.parts.comunications.signal.client.subscribe($.Engine.parts.comunications.signal.topic); }, doFail: function (e) { //alert('Connessione con il server assente'); }, onConnectionLost: function (responseObject) { if (responseObject.errorCode !== 0) { setTimeout($.Engine.parts.comunications.signal.connect, 2000); } }, onMessageArrived: function (message) { try { $.Engine.parts.audio.play('dlindlon'); // message = JSON.parse(atob(message.payloadString)); message = JSON.parse(utility.CryptoJSAesDecrypt($.Engine.parts.comunications.signal.topic, utility.decode(message.payloadString))); switch (message.object) { case 'call'://notify if ($.Engine.routes.actual == 'index') { if (typeof part_dashboard !== 'undefined') { part_dashboard.addModCall(message.data); } } break; case 'reservation'://notify if ($.Engine.routes.actual == 'index') { if (typeof part_dashboard !== 'undefined') { part_dashboard.addModReservation(message.data); } } else { if (typeof part_reservation_list !== 'undefined') { part_reservation_list.refreshTable(); } } switch (message.action) { case 'changeStatus': break; } //let data = JSON.parse(utility.decode(utility.CryptoJSAesDecrypt($.Engine.user.data.tkn, utility.decode(message.d)))); //$.Engine.parts.comunications.addNotice(data); break; case 'order'://notify if ($.Engine.routes.actual == 'index') { if (typeof part_dashboard !== 'undefined') { part_dashboard.addModOrder(message.data); } } else { if (typeof part_order_list !== 'undefined') { part_order_list.hasOwnProperty('refreshTable') ? part_order_list.refreshTable() : null; } } switch (message.action) { case 'changeStatus': break; } //let data = JSON.parse(utility.decode(utility.CryptoJSAesDecrypt($.Engine.user.data.tkn, utility.decode(message.d)))); //$.Engine.parts.comunications.addNotice(data); break; } } catch (e) { } } }, callback: {} }; $(document).ready(function () { $('#dialog-confirm').hide(); $('#dialog-confirm').removeClass('hidden'); $.Engine.parts.finder.init(); }); function dropzoneExists(selector) { var elements = $(selector).find('.dz-default'); return elements.length > 0; } function getTableFilter(call, filter, id) { let fields = $("#" + id).jsGrid("option", "fields"); let fieldsType = {}; for (let k in fields) { if (fields[k].type == 'select') fieldsType[fields[k].name] = 'number'; else fieldsType[fields[k].name] = fields[k].sorter; } for (let f in filter) { if (filter[f] != '' && filter[f] != undefined) { let val = filter[f]; if (fieldsType[f] != 'number') val = '%' + filter[f] + '%'; call['f_' + f] = val; } } return call; } function getDayNumber(day) { switch (day) { case 'monday': return 1; case 'tuesday': return 2; case 'wednesday': return 3; case 'thursday': return 4; case 'friday': return 5; case 'saturday': return 6; case 'sunday': return 7; default: return null; } } function initJsGridExtraFields() { (function (jsGrid, $) { var NumberField = jsGrid.NumberField; function DecimalField(config) { NumberField.call(this, config); } DecimalField.prototype = new NumberField({ step: 0.01, filterValue: function () { return this.filterControl.val() ? parseFloat(this.filterControl.val()) : undefined; }, insertValue: function () { return this.insertControl.val() ? parseFloat(this.insertControl.val()) : undefined; }, editValue: function () { return this.editControl.val() ? parseFloat(this.editControl.val()) : undefined; }, _createTextBox: function () { return NumberField.prototype._createTextBox.call(this) .attr("step", this.step); } }); jsGrid.fields.decimal = jsGrid.DecimalField = DecimalField; function EuroField(config) { NumberField.call(this, config); } EuroField.prototype = new NumberField({ step: 0.01, filterValue: function () { return this.filterControl.val() ? parseFloat(this.editControl.val().replace('€ ', '')) : undefined; }, insertValue: function () { return this.insertControl.val() ? parseFloat(this.editControl.val().replace('€ ', '')) : undefined; }, editValue: function () { return this.editControl.val() ? parseFloat(this.editControl.val().replace('€ ', '')) : undefined; }, _createTextBox: function () { return NumberField.prototype._createTextBox.call(this) .attr("step", this.step); }, itemTemplate: function (value) { if (parseFloat(value)) return "€ " + value; return undefined; } }); jsGrid.fields.euro = jsGrid.EuroField = EuroField; }(jsGrid, jQuery)); } $.fn.setNow = function (onlyBlank) { var now = new Date($.now()) , year , month , date , hours , minutes , seconds , formattedDateTime ; year = now.getFullYear(); month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1; date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate(); /* hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours(); minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes(); seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();*/ formattedDateTime = year + '-' + month + '-' + date/* + 'T' + hours + ':' + minutes + ':' + seconds*/; if (onlyBlank === true && $(this).val()) { return this; } $(this).val(formattedDateTime); return this; } $.fn.setNowPlusHours = function (onlyBlank, howHours) { var now = new Date($.now()) , year , month , date , hours , minutes , seconds , formattedDateTime ; now.setTime(now.getTime() + (howHours * 60 * 60 * 1000)); year = now.getFullYear(); month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1; date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate(); hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours(); minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes(); seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds(); formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds; if (onlyBlank === true && $(this).val()) { return this; } $(this).val(formattedDateTime); return this; } function dayzerofill(i) { return (i < 10 ? '0' : '') + i; } var vksDropMe = { id: null, resp_a: null, resp_b: null, alreadyMakeIt: null, dropme: null, upType: null, MAX_WIDTH: 800, MAX_HEIGHT: 600, maxFiles: 10, maxFileSize: 10, acceptedFiles: "image/jpeg,image/png,image/gif", resize: false, initDropzoneVars: function () { if (!Dropzone.hasOwnProperty('vksPromises')) { Dropzone.vksPromises = jQuery.Deferred(); Dropzone.vksPromisesNotify = Dropzone.vksPromises.promise(); Dropzone.vksQueueCompleted = 0; } }, init: function (id) { this.initDropzoneVars(); this.id = id this.upType = $(id).data('up-type'); this.dropme = new Dropzone($(id + "-cont")[0], { autoProcessQueue: false, url: $.Engine.costants.endPoint + "?ref=uploader&name=upload", previewsContainer: id + "-cont", clickable: id, paramName: "up_file", createImageThumbnails: true, addRemoveLinks: true, maxFiles: this.maxFiles, maxFileSize: this.maxFileSize, acceptedFiles: this.acceptedFiles }); this.dropme.on("complete", function (file) {}); var errorFunction = (function (file) { this.sendFilesError('Il server non risponde'); }).bind(this); this.dropme.on("error", errorFunction); var queuecompleteFunction = (function () { this.dropme.options.autoProcessQueue = false; this.save(this.dropme.getRejectedFiles().length); }).bind(this); this.dropme.on("queuecomplete", queuecompleteFunction); var successFunction = (function (file) { if (file.xhr.response) { try { var a = JSON.parse(file.xhr.response); if (a.hasOwnProperty('return') && a.return) { this.dropme.removeFile(file); } else { file.accepted = false; file.status = Dropzone.Error; this.dropme._errorProcessing([file], a.em); this.dropme.sendFilesError(a.em); } } catch (e) { file.accepted = false; file.status = Dropzone.Error; this.dropme._errorProcessing([file], e); this.sendFilesError(e); } } }).bind(this); this.dropme.on("success", successFunction) var addedfileFunction = (function (origFile) { var dropme = this.dropme; var MAX_WIDTH = this.MAX_WIDTH; var MAX_HEIGHT = this.MAX_HEIGHT; var resize = this.resize; var reader = new FileReader(); var loadfileFunction = (function (event) { if (!resize) return; var origImg = new Image(); origImg.src = event.target.result; origImg.addEventListener("load", function (event) { var width = event.target.width; var height = event.target.height; // Don't resize if it's small enough if (width <= MAX_WIDTH && height <= MAX_HEIGHT) { //dropme.enqueueFile(origFile); return; } // Calc new dims otherwise if (width > height) { if (width > MAX_WIDTH) { height *= MAX_WIDTH / width; width = MAX_WIDTH; } } else { if (height > MAX_HEIGHT) { width *= MAX_HEIGHT / height; height = MAX_HEIGHT; } } let pop = $.Engine.messages.popup('Un attimo', 'Sto ridimensionando l\'immagine', 'info', {duration: 50000}) // Resize var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); ctx.drawImage(origImg, 0, 0, width, height); var resizedFile = base64ToFile(canvas.toDataURL(), origFile); // Replace original with resized var origFileIndex = dropme.files.indexOf(origFile); dropme.files[origFileIndex] = resizedFile; pop.close() $.Engine.messages.popup('fatto', 'Immagine pronta per il caricamento', 'info', {duration: 3000}) }); }).bind(this); // Convert file to img reader.addEventListener("load", loadfileFunction); reader.readAsDataURL(origFile); }).bind(this); this.dropme.on("addedfile", addedfileFunction); return this.dropme; }, sendFilesError: function (a) { Dropzone.vksPromises.notify({error: 1, id: this.id}); this.dropme.removeFile(a) }, retryDropZoneQueue: function () { for (let file in this.dropme.files) { file.status = Dropzone.QUEUED file.upload.progress = 0; file.upload.bytesSent = 0; } this.dropme.options.autoProcessQueue = true; this.dropme.processQueue(); }, save: function (error) { if (this.alreadyMakeIt) return; this.alreadyMakeIt = true; if (parseInt(error) == 0) { if (this.dropme.getUploadingFiles().length === 0 && this.dropme.getQueuedFiles().length === 0) { Dropzone.vksQueueCompleted += 1; Dropzone.vksPromises.notify({error: 0, id: this.id}); //$.Engine.messages.popup('', 'File caricati', 'success'); } this.alreadyMakeIt = false; this.dropme.disable(); this.dropme.destroy(); } else { $('#' + this.resp_b).find('.form-actions').hide(); } }, send: function (a, b) { this.resp_a = a; this.resp_b = b; if (this.resp_a.hasOwnProperty('return') && this.resp_a.return.hasOwnProperty('id') && this.resp_a.return.id) { if (this.dropme.files.length) { this.dropme.options.url = $.Engine.costants.endPoint + "?ref=uploader&name=upload&tkn=" + $.Engine.user.getTkn() + "&up_type=" + this.upType + "&up_id=" + a.return.id; this.dropme.options.autoProcessQueue = true; this.dropme.processQueue(); } else { this.save(0); } } else { $.Engine.messages.popup(i18next.t('app.popup.title.error'), i18next.t('app.popup.description.error') + ' ' + a.em, 'error'); } } } function base64ToFile(dataURI, origFile) { var byteString, mimestring; if (dataURI.split(',')[0].indexOf('base64') !== -1) { byteString = atob(dataURI.split(',')[1]); } else { byteString = decodeURI(dataURI.split(',')[1]); } mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]; var content = new Array(); for (var i = 0; i < byteString.length; i++) { content[i] = byteString.charCodeAt(i); } var newFile = new File( [new Uint8Array(content)], origFile.name, {type: mimestring} ); // Copy props set by the dropzone in the original file var origProps = [ "upload", "status", "previewElement", "previewTemplate", "accepted" ]; $.each(origProps, function (i, p) { newFile[p] = origFile[p]; }); return newFile; }/* * Questo file e' stato sviluppato da Vittorio Domenico Padiglia. * La copia o l'uso dello stesso senza una regolare licenza o consenso dell'autore * punibile per legge. */ $(document).ready(function () { $.Engine.user.init(); $.Engine.routes.init(); });