\
';
//console.log('hdTicketToken', '');
if('' !== '') {
sessionStorage.setItem('eaero-hdTicketToken', '');
}
html = html.replace(/##nl##/g, " ");
html = html.replace(/##crlf##/g, "\n");
var me = document.getElementById('div_chatbot22');
if (!me) {
me = document.getElementById('chatbot22');
}
if (me) {
var textnode = document.createElement('div');
textnode.id = 'div_chatbot22';
textnode.scriptSrc = '//test.eaero.de/api/chatbot/index/22/4c91a34a24038194a21dc96e2c0050e6?scriptId=chatbot22';
textnode.innerHTML = html;
me.parentNode.replaceChild(textnode, me);
}
else {
// typ und id suchen
var scripts = document.getElementsByTagName("script");
var src = '//test.eaero.de/api/chatbot/index/22/4c91a34a24038194a21dc96e2c0050e6?scriptId=chatbot22';
var type = '';
var id = '';
var pos1TableOfHours = src.indexOf('/api/tableOfHours/');
var pos1CalendarOfHours = src.indexOf('/api/calendarOfHours/');
var pos1hours = src.indexOf('/api/hours/');
var pos1chatbot = src.indexOf('/api/chatbot/');
var offset = 0;
var idInNext = false;
var template = '/';
var pos1 = -1;
if(pos1TableOfHours > -1) {
pos1 = pos1TableOfHours;
offset = 18;
type = 'tableOfHours';
}
else if(pos1CalendarOfHours > -1) {
type = 'calendarOfHours';
template = 'document.write';
}
else if(pos1hours > -1) {
pos1 = pos1hours;
offset = 11;
idInNext = true;
type = 'hours'; // 11-5=6
}
else if(pos1chatbot> -1) {
pos1 = pos1chatbot;
offset = 13;
idInNext = true;
type = 'chatbot'; // 9-3=6 7+6=13
}
if(pos1 > -1) {
var pos2 = src.indexOf('/', pos1 + offset);
if(!idInNext) {
id = src.substring(pos1 + offset, pos2);
}
else {
var pos2Back = pos2 + 1;
template = '/' + src.substring(pos1 + offset, pos2) + '/';
pos2 = src.indexOf('/', pos2 + 1);
id = src.substring(pos2Back, pos2);
}
//console.log(type);
//console.log(id);
//console.log(template);
}
// /typ und id suchen
var scriptNodeReplaced = false;
if(type != '' && id != '') {
for(i=0;i -1) {
//console.log(scripts[i]);
var newNode = document.createElement('div');
//console.log(html);
newNode.innerHTML = html;
newNode.setAttribute('id', 'div_chatbot22');
newNode.setAttribute('scriptSrc', '//test.eaero.de/api/chatbot/index/22/4c91a34a24038194a21dc96e2c0050e6?scriptId=chatbot22');
scripts[i].parentNode.replaceChild(newNode, scripts[i]);
scriptNodeReplaced = true;
//console.log('gefunden');
}
}
}
if(!scriptNodeReplaced && template != '/') {
//console.log('document.write');
//alert("div_chatbot22");
document.write('
' + html + '
');
}
}
if ('{withEQCSS}' == 'withEQCSS') {
var bodyElement = document.getElementsByTagName('body')[0];
var bodyEQCSS = bodyElement.getAttribute('eqcss');
if (bodyEQCSS == null) {
//console.log('body eqcss: ' + bodyElement.getAttribute('eqcss'));
bodyElement.setAttribute('eqcss', 'eqcss');
//!!console.log(typeof(EQCSS));
if (typeof(EQCSS) === 'undefined') {
//!!console.log('EQCSS laden');
eaApiLoadScript('{base_src}/js/EQCSS.min.js', function () {
if (typeof(EQCSS) !== 'undefined') {
//console.log('EQCSS apply');
EQCSS.apply();
}
});
}
else {
if (typeof(EQCSS) !== 'undefined') {
//console.log('EQCSS apply');
EQCSS.apply();
}
}
}
else {
if (typeof(EQCSS) !== 'undefined') {
//console.log('EQCSS apply');
EQCSS.apply();
}
}
}
if('{withEQCSS}' == 'withEQCSS' && '{withoutMouseUpListener}' != 'withoutMouseUpListener') {
if(window.eAeroMouseupInstalled === undefined) {
window.eAeroMouseupInstalled = true;
document.addEventListener("mouseup", function(e) {
//console.log('mouseup');
setTimeout(function() {
//console.log('EQCSS apply');
EQCSS.apply();
}, 1);
});
}
}
if ('{withCalendarControl}' == 'withCalendarControl') {
/*
var bodyElement = document.getElementsByTagName('body')[0];
var bodyJQUERY = bodyElement.getAttribute('jquery');
var bodyJQUERYUI = bodyElement.getAttribute('jqueryui');
*/
var isPreloadJs = typeof createjs !== 'undefined';
function doWithCalendar() {
return;
var bodyElement = document.getElementsByTagName('body')[0];
var preloadjs = bodyElement.getAttribute('preloadjs');
if (preloadjs) {
//console.log('#div_chatbot22 #datepicker');
$('#div_chatbot22 #datepicker').datepicker({
language: 'de',
xmultidate: true
}).next().on('click', function () {
});
}
}
if (!isPreloadJs && false) {
eaApiLoadScript('{base_src}/js/vendor/preloadjs-0.6.1.min.js', function () {
//console.log('loaded preloadjs chatbot22');
if(typeof eaQueue == 'undefined') {
//console.log('new eqQueue');
eaQueue = [];
}
eaQueue['chatbot22'] = new createjs.LoadQueue();
// Callback, wenn Queue abgearbeitet
eaQueue['chatbot22'].on("complete", function () {
var bodyElement = document.getElementsByTagName('body')[0];
bodyElement.setAttribute('preloadjs', 'preloadjs');
//console.log('complete chatbot22');
//console.log($.fn.datepicker.dates['de']);
doWithCalendar();
}, this);
var manifest = [];
var mi = 0;
if (!window.jQuery) {
// nur, wenn kein jQuery da
//eaQueue['chatbot22'].loadFile('{base_src}/js/vendor/jquery-1.11.3.min.js');
manifest[mi++] = '{base_src}/js/vendor/jquery-1.11.3.min.js';
}
//eaQueue['chatbot22'].loadFile('{base_src}/assets/js/date-time/bootstrap-datepicker.min.js');
manifest[mi++] = '{base_src}/assets/js/date-time/bootstrap-datepicker.min.js';
//if(!window.jQuery || typeof ($.fn.datepicker.dates['de']) == 'undefined') {
// nur, wenn kein jquery oder locale da
//eaQueue['chatbot22'].loadFile('{base_src}/assets/js/date-time/locales/bootstrap-datepicker.de.js');
manifest[mi++] = '{base_src}/assets/js/date-time/locales/bootstrap-datepicker.de.js';
//}
//eaQueue['chatbot22'].loadFile('{base_src}/assets/css/bootstrap.min.css');
manifest[mi++] = '{base_src}/assets/css/bootstrap.min.css';
//eaQueue['chatbot22'].loadFile('{base_src}/assets/css/bootstrap-datepicker.css');
manifest[mi++] = '{base_src}/assets/css/bootstrap-datepicker.css';
//eaQueue['chatbot22'].loadFile('{base_src}/assets/css/datepicker.css');
manifest[mi++] = '{base_src}/assets/css/datepicker.css';
//eaQueue['chatbot22'].loadFile('{base_src}/assets/css/custom.css');
manifest[mi++] = '{base_src}/assets/css/custom.css';
//queue.loadFile('{base_src}/assets/css/ace.min.css');
eaQueue['chatbot22'].loadManifest(manifest, true);
//console.log('load chatbot22');
//eaQueue['chatbot22'].load();
setTimeout(function() {
//console.log('load chatbot22');
//eaQueue['chatbot22'].load();
}, 1000);
});
/*
if(bodyJQUERY == null) {
bodyElement.setAttribute('jquery', 'jquery');
eaApiLoadScript('{base_src}/js/vendor/jquery-1.11.3.min.js', function() {
bodyJQUERY = true;
bodyElement.setAttribute('jqueryui', 'jqueryui');
//eaApiLoadScript('{base_src}/assets/js/jquery-ui-1.10.3.full.min.js', function() {
eaApiLoadScript('{base_src}/assets/js/date-time/bootstrap-datepicker.min.js', function() {
bodyJQUERYUI = true;
doWithCalendar();
});
});
}
else {
doWithCalendar();
}
*/
}
else {
doWithCalendar();
}
}
function eaApiLoadScript(url, callback) {
//console.log('eaApiLoadScript');
// script-Tag anlegen
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Callback-Funktion binden
//script.onreadystatechange = callback; // Probleme mit IE < 11, daher auskommentiert
script.onload = callback;
// Script-Tag im Header anlegen, damit Ladevorgang beginnt
head.appendChild(script);
}
if (eaeroChatBotApi == undefined) {
var eaeroChatBotApi = {};
// Lädt und aktualisiert Öffnungszeiten für mehrere IDs über ein API-Script.
eaeroChatBotApi.updateMultipleHours = function (idArr, template, date, clear, withDayAfterTomorrow, withFootnotes, withLegend) {
// todo: prüfen, ob dies ev. auch im head-Element funktioniert
var bodyElement = document.getElementsByTagName('body')[0];
if(!bodyElement && bodyElement == undefined) {
console.log('Fehler in der Implementierung der eaero-API. Kein Body-Element gefunden. Script wird eventuell zu früh geladen.');
return
}
if (!withDayAfterTomorrow || withDayAfterTomorrow == undefined) {
withDayAfterTomorrow = 0;
}
if (!withFootnotes || withFootnotes == undefined) {
withFootnotes = 0;
}
if (!withLegend || withLegend == undefined) {
withLegend = 0;
}
var src = '//test.eaero.de/api/chatbot/index/22/4c91a34a24038194a21dc96e2c0050e6?scriptId=chatbot22/api/multiHours/' + template + '/' + idArr + '/' + date + '/4c91a34a24038194a21dc96e2c0050e6';
var params = '';
if(withDayAfterTomorrow != 0) {
if(params == '') params += '?'; else params += '&';
params += 'withDayAfterTomorrow=1';
}
if(withFootnotes != 0) {
if(params == '') params += '?'; else params += '&';
params += 'withFootnotes=1';
}
if(withLegend != 0) {
if(params == '') params += '?'; else params += '&';
params += 'withLegend=1';
}
src += params;
var s = document.createElement("script");
s.type = "text/javascript";
s.src = src;
if (clear) {
for (var i = 0; i < idArr.length; i++) {
var divId = 'div_hours' + idArr[i];
var div = document.getElementById(divId);
if (div && div != undefined) {
div.innerHTML = '';
}
}
}
bodyElement.appendChild(s);
};
// Lädt und aktualisiert Öffnungszeiten für eine einzelne ID über ein API-Script.
eaeroChatBotApi.updateHours = function (scriptId, id, template, date, clear, withDayAfterTomorrow, withFootnotes, withLegend) {
var divElement = document.getElementById('div_' + scriptId);
if (!divElement || divElement == undefined) {
return;
}
if (!withDayAfterTomorrow || withDayAfterTomorrow == undefined) {
withDayAfterTomorrow = 0;
}
if (!withFootnotes || withFootnotes == undefined) {
withFootnotes = 0;
}
if (!withLegend || withLegend == undefined) {
withLegend = 0;
}
var scriptSrc = '';
if (divElement.scriptSrc != undefined) {
scriptSrc = divElement.scriptSrc;
}
else {
scriptSrc = '//test.eaero.de/api/chatbot/index/22/4c91a34a24038194a21dc96e2c0050e6?scriptId=chatbot22/api/hours/' + template + '/' + id + '/4c91a34a24038194a21dc96e2c0050e6';
}
var scriptSrcArr = scriptSrc.split('/');
for (i = 0; i < scriptSrcArr.length; i++) {
if (scriptSrcArr[i] == 'hours') {
scriptSrcArr[i + 3] = date;
}
}
src = scriptSrcArr.join('/');
var params = '';
if(withDayAfterTomorrow != 0) {
if(params != '') params += '?'; else params += '&';
params += 'withDayAfterTomorrow=1';
}
if(withFootnotes != 0) {
if(params != '') params += '?'; else params += '&';
params += 'withFootnotes=1';
}
if(withLegend != 0) {
if(params != '') params += '?'; else params += '&';
params += 'withLegend=1';
}
src += params;
var s = document.createElement("script");
s.type = "text/javascript";
s.src = src;
s.id = 'div_' + scriptId;
if (clear) {
divElement.innerHTML = '';
}
divElement.appendChild(s);
};
// Lädt und aktualisiert eine Tabelle mit Öffnungszeiten.
eaeroChatBotApi.updateTableOfHours = function(scriptId, date, clear) {
var divElement = document.getElementById('div_' + scriptId);
var prevButton = document.getElementById('toh_prev_button_' + scriptId);
var nextButton = document.getElementById('toh_next_button_' + scriptId);
var loadIndicator = document.getElementById('toh_load_indicator_' + scriptId);
if (!divElement || divElement == undefined) {
return;
}
if(prevButton) {
prevButton.setAttribute('disabled', 'disabled');
}
if(nextButton) {
nextButton.setAttribute('disabled', 'disabled');
}
if(loadIndicator) {
loadIndicator.setAttribute('style', '');
}
var scriptSrc = '';
if (divElement.scriptSrc != undefined) {
scriptSrc = divElement.scriptSrc;
}
else if(divElement.getAttribute('scriptSrc') != undefined) {
scriptSrc = divElement.getAttribute('scriptSrc');
}
else {
scriptSrc = '//test.eaero.de/api/chatbot/index/22/4c91a34a24038194a21dc96e2c0050e6?scriptId=chatbot22/api/tableOfHours/' + scriptId + '/1,2,3,4,5,6,7//4c91a34a24038194a21dc96e2c0050e6';
}
var scriptSrcArr = scriptSrc.split('/');
for (i = 0; i < scriptSrcArr.length; i++) {
if (scriptSrcArr[i] == 'tableOfHours') {
scriptSrcArr[i + 3] = date;
}
}
src = scriptSrcArr.join('/');
var s = document.createElement("script");
s.type = "text/javascript";
s.src = src;
s.id = 'div_' + scriptId;
if (clear) {
divElement.innerHTML = '';
}
divElement.appendChild(s);
};
// Schließt den Chatbot.
eaeroChatBotApi.closeChatBot = function(scriptId) {
eaeroChatBotApi.closeOrStartChatBot(scriptId, true);
};
// Startet den Chatbot.
eaeroChatBotApi.startChatBot = function(scriptId) {
eaeroChatBotApi.closeOrStartChatBot(scriptId, false);
};
// Öffnet oder schließt den Chatbot basierend auf dem Status.
eaeroChatBotApi.closeOrStartChatBot = function(scriptId, close) {
var divElement = document.getElementById('div_' + scriptId);
if (!divElement || divElement == undefined) {
return;
}
var sendButton = document.getElementById('ea-send-message-' + scriptId);
var closeButton = document.getElementById('ea-close-bot-' + scriptId);
if(sendButton) {
sendButton.setAttribute('disabled', 'true');
}
if(closeButton) {
closeButton.setAttribute('disabled', 'true');
}
if(!close) {
sessionStorage.removeItem('eaero-hdTicketToken');
}
console.log('updateChatBot-close');
eaeroChatBotApi.updateChatBot('chatbot22', sessionStorage.getItem('eaero-hdTicketToken'), null, close);
if(!close) {
eaeroChatBotApi.updateChatBot('chatbot22', sessionStorage.getItem('eaero-hdTicketToken'), null);
}
}
// Minimiert oder öffnet den Chatbot und aktualisiert bei Bedarf.
eaeroChatBotApi.toggleChat = function(withUpdate) {
if(withUpdate === undefined) {
withUpdate = true;
}
console.log('toggleChat');
var container = document.getElementById('ea-chat-bot-container');
var overlay = document.getElementById('ea-modal-overlay');
container.classList.toggle('minimized');
container.classList.remove('maximized');
container.classList.remove('snapped');
container.classList.remove('chatting-window');
if (container.classList.contains('maximized')) {
overlay.style.display = 'block';
} else {
overlay.style.display = 'none';
}
sessionStorage.setItem('eaero-mini', container.classList.contains('minimized'));
sessionStorage.setItem('eaero-maxi', false);
sessionStorage.setItem('eaero-snap', false);
var panel = document.getElementById('ea-chat');
if(panel !== null) panel.scrollTop = panel.scrollHeight;
if(!container.classList.contains('maximized')) {
eaeroChatBotApi.snapInChat(withUpdate);
}
if(!container.classList.contains('minimized')) {
console.log('updateChatBot-toggleChat');
if(withUpdate) eaeroChatBotApi.updateChatBot('chatbot22', sessionStorage.getItem('eaero-hdTicketToken'), null);
}
if(!container.classList.contains('minimized') && !container.classList.contains('maximized') && !container.classList.contains('snapped')) {
container.classList.add('chatting-window');
}
document.getElementById("ea-message").focus();
};
// Maximiert oder verkleinert den Chatbot-Fensterbereich.
eaeroChatBotApi.toggleMaximizeChat = function(chatBotId) {
//console.log('toggleMaximizeChat', chatBotId);
var container = document.getElementById('ea-chat-bot-container');
var overlay = document.getElementById('ea-modal-overlay');
container.classList.toggle('maximized');
container.classList.remove('minimized');
container.classList.remove('snapped');
container.classList.remove('chatting-window');
if (container.classList.contains('maximized')) {
overlay.style.display = 'block';
} else {
overlay.style.display = 'none';
}
sessionStorage.setItem('eaero-mini', false);
sessionStorage.setItem('eaero-maxi', container.classList.contains('maximized'));
sessionStorage.setItem('eaero-snap', false);
if(container.classList.contains('maximized')) {
// prüfen, ob im snap-in-container, dann ans wieder zurück zum Script
const chatDivElement = document.getElementById('div_chatbot' + chatBotId);
const chatbotElement = document.querySelector('.ea-chatbot');
if (chatDivElement && chatbotElement) {
// Den Chatbot in das snap-in-Element verschieben
//console.log('appendChild from .ea-chatbot to div_chatbot8');
chatDivElement.appendChild(chatbotElement);
}
}
var panel = document.getElementById('ea-chat');
if(panel !== null) panel.scrollTop = panel.scrollHeight;
if(!container.classList.contains('maximized')) {
eaeroChatBotApi.snapInChat();
}
if(!container.classList.contains('minimized') && !container.classList.contains('maximized') && !container.classList.contains('snapped')) {
container.classList.add('chatting-window');
}
document.getElementById("ea-message").focus();
};
// Verschiebt den Chatbot in die Snap-In-Ansicht, wenn er nicht maximiert ist.
eaeroChatBotApi.snapInChatIfNotMaximized = function() {
//console.log('snapInChatIfNotMaximized');
if(sessionStorage.getItem('eaero-maxi') != 'true') {
eaeroChatBotApi.snapInChat();
}
};
// Verschiebt den Chatbot in die Snap-In-Ansicht.
eaeroChatBotApi.snapInChat = function(withUpdate) {
if(withUpdate === undefined) {
withUpdate = true;
}
console.log('snapInChat');
const snapInElement = document.getElementById('ea-chat-bot-snap-in-container');
const chatbotElement = document.querySelector('.ea-chatbot');
if (snapInElement && chatbotElement) {
// Den Chatbot in das snap-in-Element verschieben
//console.log('appendChild from .ea-chatbot to ea-chat-bot-snap-in-container');
snapInElement.innerHTML = ''; // Inhalt leeren
snapInElement.appendChild(chatbotElement);
var container = document.getElementById('ea-chat-bot-container');
var overlay = document.getElementById('ea-modal-overlay');
container.classList.remove('maximized');
container.classList.remove('minimized');
container.classList.add('snapped');
overlay.style.display = 'none';
sessionStorage.setItem('eaero-mini', false);
sessionStorage.setItem('eaero-maxi', false);
sessionStorage.setItem('eaero-snap', true);
console.log('updateChatBot-snapInChat');
if(withUpdate) eaeroChatBotApi.updateChatBot('chatbot22', sessionStorage.getItem('eaero-hdTicketToken'), null);
}
};
eaeroChatBotApi.isUpdatingChat = false;
// Aktualisiert den Chatverlauf durch einen API-Request.
eaeroChatBotApi.updateChatBot = function(scriptId, hdTicketToken, message, close) {
console.log('updateChatBot');
console.log(eaeroChatBotApi.isUpdatingChat);
if(eaeroChatBotApi.isUpdatingChat) {
return;
}
console.log('a');
if(close === undefined) {
close = false;
}
console.log('b');
console.log('scriptId', scriptId);
console.log('hdTicketToken', hdTicketToken);
console.log('message', message);
console.log('close', close);
var divElement = document.getElementById('div_' + scriptId);
console.log(divElement);
if (!divElement || divElement == undefined) {
return;
}
console.log('c');
if(!close) {
eaeroChatBotApi.isUpdatingChat = true;
}
console.log('d');
var sendButton = document.getElementById('ea-send-message-' + scriptId);
var closeButton = document.getElementById('ea-close-bot-' + scriptId);
var messageBox = document.getElementById('ea-message');
//console.log('...');
if(sendButton) {
sendButton.setAttribute('disabled', 'true');
}
if(closeButton) {
closeButton.setAttribute('disabled', 'true');
}
if(messageBox) {
messageBox.setAttribute('disabled', 'true');
}
console.log('e');
src = '//test.eaero.de/app.php/api/chatbot/do/chat/22/4c91a34a24038194a21dc96e2c0050e6';
src = src.replace(/\/app\.php\//g, '/');
console.log('src', src);
document.getElementById('ea-message').value = '';
const chatDiv = document.getElementById('ea-chat');
if(message) {
const messageDiv = document.createElement("div");
messageDiv.classList.add("ea-chat-item");
messageDiv.classList.add("ea-chat-role-user");
messageDiv.textContent = message;
chatDiv.appendChild(messageDiv);
}
eaeroChatBotApi.typing();
fetch(src, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
scriptId: scriptId,
hdTicketToken: hdTicketToken,
message: message,
close: close
})
})
.then(response => response.json())
.then(data => {
//console.log("Antwort vom Server:", data);
eaeroChatBotApi.isUpdatingChat = false;
handleChatData(data);
if(close && data.history.length === 0) {
// todo: wenn snappedIn, dann Chat mit neuem Request neu starten
var container = document.getElementById('ea-chat-bot-container');
if(container.classList.contains('snapped')) {
console.log('CHAT NEU STARTEN');
eaeroChatBotApi.updateChatBot('chatbot22', sessionStorage.getItem('eaero-hdTicketToken'), null);
return
}
eaeroChatBotApi.toggleChat(false);
}
if(sendButton) {
sendButton.removeAttribute('disabled');
}
if(closeButton) {
closeButton.removeAttribute('disabled');
}
if(messageBox) {
messageBox.removeAttribute('disabled');
messageBox.focus();
}
})
.catch(error => {
eaeroChatBotApi.isUpdatingChat = false;
console.error("Fehler:", error)
});
};
// Sendet ein Formular aus dem Chatbot per API an den Server.
eaeroChatBotApi.postChatBotForm = function(scriptId, hdTicketToken, formData) {
console.log('postChatBotForm');
if(close === undefined) {
close = false;
}
//console.log('message', message);
//console.log('scriptId', scriptId);
var divElement = document.getElementById('div_' + scriptId);
if (!divElement || divElement == undefined) {
return;
}
var sendButton = document.getElementById('ea-send-message-' + scriptId);
var closeButton = document.getElementById('ea-close-bot-' + scriptId);
var messageBox = document.getElementById('ea-message');
//console.log('...');
if(sendButton) {
sendButton.setAttribute('disabled', 'true');
}
if(closeButton) {
closeButton.setAttribute('disabled', 'true');
}
if(messageBox) {
messageBox.setAttribute('disabled', 'true');
}
//return;
var src = '//test.eaero.de/app.php/api/chatbot/do/postForm/22/4c91a34a24038194a21dc96e2c0050e6';
src = src.replace(/\/app\.php\//g, '/');
document.getElementById('ea-message').value = '';
document.querySelectorAll('.ea-chat-form button, .ea-chat-form input').forEach(function(element) {
element.disabled = true;
});
document.querySelectorAll('.ea-chat-form-before button, .ea-chat-form-before input').forEach(function(element) {
element.disabled = true;
});
eaeroChatBotApi.typing();
fetch(src, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
scriptId: scriptId,
hdTicketToken: hdTicketToken,
formData: formData,
close: close
})
})
.then(response => response.json())
.then(data => {
//console.log("Antwort vom Server:", data);
handleChatData(data);
if(sendButton) {
sendButton.removeAttribute('disabled');
}
if(closeButton) {
closeButton.removeAttribute('disabled');
}
if(messageBox) {
messageBox.removeAttribute('disabled');
messageBox.focus();
}
})
.catch(error => console.error("Fehler:", error));
};
// Zeigt eine Tipp-Animation im Chatbot an.
eaeroChatBotApi.typing = function() {
const chatDiv = document.getElementById('ea-chat');
const typingDiv = document.createElement('div');
typingDiv.className = 'ea-chat-typing-indicator';
typingDiv.innerHTML = `
`;
document.querySelectorAll('.ea-chat-typing-indicator').forEach(el => el.remove());
chatDiv.appendChild(typingDiv);
chatDiv.scrollTop = chatDiv.scrollHeight;
};
if (typeof eAeroChatBotApiLoaded == 'function') {
eAeroChatBotApiLoaded();
}
eaeroChatBotApi.chatbotCheckForUpdateTimeStamp = null;
function handleChatData(data) {
console.log('handleChatData', data);
sessionStorage.setItem('eaero-hdTicketToken', data['hdTicketToken']);
// Element in den Container einfügen
const chatContainer = document.getElementById("ea-chat"); // Ziel-Container im HTML
const chatBotContainer = document.getElementById("ea-chat-bot-container"); // Ziel-Container im HTML
if(!data['isArchived']) {
chatBotContainer.classList.remove('ea-chat-not-in-conversation');
}
else if(data['isArchived']) {
chatBotContainer.classList.add('ea-chat-not-in-conversation');
}
if(data['isInConversation'] !== null && data['isArchived'] !== null && !data['isInConversation'] && !data['isArchived']) {
eaeroChatBotApi.chatbotCheckForUpdateTimeStamp = data['timestamp'];
}
else {
eaeroChatBotApi.chatbotCheckForUpdateTimeStamp = null;
}
chatContainer.innerHTML = '';
data.history.forEach(chatItem => {
const chatDiv = document.createElement("div");
const innerDiv = document.createElement("div");
// Klasse je nach "in"-Wert setzen
chatDiv.classList.add("ea-chat-item", chatItem.in ? "ea-chat-role-user" : "ea-chat-role-assistant");
innerDiv.classList.add("ea-chat-time");
innerDiv.setAttribute("date", chatItem.timestamp.date);
// Textinhalt setzen
chatDiv.textContent = chatItem.text;
chatDiv.appendChild(innerDiv);
chatContainer.appendChild(chatDiv);
if(!chatItem.in) {
const faceDiv = document.createElement("div");
const faceImg = document.createElement("img");
faceDiv.classList.add("ea-chat-face", chatItem.in ? "ea-chat-face-role-user" : "ea-chat-face-role-assistant");
faceImg.setAttribute("src", "//test.eaero.de/eaero\x2Dchat\x2Dbot\x2Fimages\x2Fface.png");
faceImg.setAttribute("alt", "Bild des Chat-Bots - Frag mich was");
faceDiv.appendChild(faceImg);
chatContainer.appendChild(faceDiv);
}
});
renderChatBot();
initChatForm();
chatBotFormatRelativeTime();
var panel = document.getElementById('ea-chat');
if(panel !== null) panel.scrollTop = panel.scrollHeight;
document.getElementById("ea-message").focus();
}
function chatBotFormatRelativeTime() {
//console.log('chatBotFormatRelativeTime');
const elements = document.querySelectorAll('.ea-chat-time');
elements.forEach(el => {
const timeAttr = el.getAttribute('date');
if (!timeAttr) return;
const dateStr = timeAttr.replace(" ", "T"); // "2025-03-21T14:20:08.000000"
const eventDate = new Date(dateStr);
const now = new Date();
// Zeitdifferenz in Millisekunden
const diffMs = now - eventDate;
const diffSeconds = Math.floor(diffMs / 1000);
const diffMinutes = Math.floor(diffMs / 1000 / 60);
// Format-Helfer
const pad = (num) => String(num).padStart(2, "0");
// Datumsteile
const eventDay = eventDate.getDate();
const eventMonth = eventDate.getMonth();
const eventYear = eventDate.getFullYear();
const nowDay = now.getDate();
const nowMonth = now.getMonth();
const nowYear = now.getFullYear();
let text = "";
if (diffSeconds < 10) {
text = "gerade eben";
} else if (diffSeconds < 60) {
text = `vor ${diffSeconds} Sekunde${diffSeconds === 1 ? "" : "n"}`;
} else if (diffMinutes < 30) {
text = `vor ${diffMinutes} Minute${diffMinutes === 1 ? "" : "n"}`;
} else if (
eventYear === nowYear &&
eventMonth === nowMonth &&
eventDay === nowDay
) {
// gleiches Datum wie heute
text = `um ${pad(eventDate.getHours())}:${pad(eventDate.getMinutes())}`;
} else {
text = `${pad(eventDate.getDate())}.${pad(eventDate.getMonth() + 1)}.${eventDate.getFullYear()} ${pad(eventDate.getHours())}:${pad(eventDate.getMinutes())}`;
}
el.textContent = text;
});
}
function chatBotCheckForUpdates() {
return; // derzeit deaktiviert. Es gbit ein Problem mit dieser Aktualisierung und der Interaktion mit dem Schließen-Button des Chat-Bots
if(eaeroChatBotApi.chatbotCheckForUpdateTimeStamp === null) {
return;
}
console.log('chatBotCheckForUpdates', eaeroChatBotApi.chatbotCheckForUpdateTimeStamp, eaeroChatBotApi.chatBotScriptId);
eaeroChatBotApi.updateChatBot(eaeroChatBotApi.chatBotScriptId, sessionStorage.getItem('eaero-hdTicketToken'), null);
}
setInterval(chatBotFormatRelativeTime, 1 * 1000);
setInterval(chatBotCheckForUpdates, 10 * 1000);
}
/**
* Konvertiert einen Markdown-Tabellenblock in HTML.
*
* @param {string} markdown - Der Markdown-Text, der eine Tabelle enthält.
* @returns {string} - Der HTML-String der Tabelle.
*/
function convertMarkdownTableToHTML(markdown) {
// Zeilenweise aufteilen und leere Zeilen entfernen
const rows = markdown.trim().split('\n').filter(row => row.trim() !== '');
// Es müssen mindestens drei Zeilen vorhanden sein (Header, Trennlinie, mindestens eine Datenzeile)
if (rows.length < 3) {
return markdown;
}
// Erste Zeile: Kopfzeile (Header)
const headerCells = rows[0]
.split('|')
.map(cell => cell.trim())
.filter(cell => cell.length > 0);
// HTML-Tabelle initialisieren
let html = '
';
// Kopfbereich erstellen
html += '
';
headerCells.forEach(cell => {
html += `
${cell}
`;
});
html += '
';
// Tabellenkörper (Datenzeilen; zweite Zeile ist die Trennzeile)
html += '';
for (let i = 2; i < rows.length; i++) {
const row = rows[i];
// Zellen aufteilen – führende/abschließende Pipes ignorieren
const cells = row
.split('|')
.map(cell => cell.trim())
.filter(cell => cell.length > 0);
html += '
';
cells.forEach(cell => {
html += `
${cell}
`;
});
html += '
';
}
html += '
';
return html;
}
/**
* Durchsucht einen gesamten Chat-Text nach Markdown-Tabellen und ersetzt diese
* durch die entsprechende HTML-Tabelle. Alle übrigen Textteile bleiben unverändert.
*
* @param {string} text - Der komplette Chat-Text.
* @returns {string} - Der Text, in dem Markdown-Tabellen in HTML umgewandelt wurden.
*/
function convertMarkdownTablesInChat(text) {
const lines = text.split('\n');
let result = '';
let i = 0;
while (i < lines.length) {
// Prüfe, ob die aktuelle Zeile der Beginn einer möglichen Tabelle ist
if (lines[i].trim().startsWith('|')) {
// Prüfe, ob die nächste Zeile eine Trennzeile (bestehend aus Bindestrichen und Pipes) ist
if (i + 1 < lines.length && /^[\s|:-]+$/.test(lines[i + 1].trim())) {
// Markdown-Tabellenblock sammeln (Header, Trennzeile, Datenzeilen)
let tableBlock = lines[i] + '\n' + lines[i + 1] + '\n';
i += 2;
while (i < lines.length && lines[i].trim().startsWith('|')) {
tableBlock += lines[i] + '\n';
i++;
}
// Umwandlung des Tabellenblocks in HTML und Anhängen an das Ergebnis
result += convertMarkdownTableToHTML(tableBlock) + '\n';
continue;
}
}
// Falls es sich nicht um einen Tabellenblock handelt, füge die Zeile unverändert hinzu
result += lines[i] + '\n';
i++;
}
return result;
}
/**
* Wandelt den Inhalt eines [Text=...]-Elements in HTML um.
* Markdown-Listenzeilen (-, *, + bzw. 1.) werden zu
/ zusammengefasst,
* dabei wird die Einrückung (Leerzeichen/Tabs) für mehrstufige (verschachtelte)
* Listen ausgewertet. Übrige Zeilen bleiben durch getrennt.
* Die Zeilentrennung erfolgt über , da echte Zeilenumbrüche zu diesem
* Zeitpunkt bereits ersetzt wurden.
*
* @param {string} text - Der bereits -getrennte Text-Inhalt.
* @returns {string} - Der in HTML umgewandelte Inhalt.
*/
function renderChatTextElement(text) {
const lines = text.split(/ /);
let html = '';
let pending = [];
const stack = []; // offene Listen, jeweils { indent, tag }; oberster Eintrag = tiefste Ebene mit offenem
const flushText = function() {
if (pending.length) {
html += pending.join(' ');
pending = [];
}
};
const closeAll = function() {
while (stack.length) {
html += '
' + stack.pop().tag + '>';
}
};
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(/^([ \t]*)([-*+]|\d+\.)\s+(.+)$/);
if (!match) {
closeAll();
pending.push(lines[i]);
continue;
}
flushText();
const indent = match[1].replace(/\t/g, ' ').length;
const tag = /\d/.test(match[2]) ? 'ol' : 'ul';
const item = match[3].trim();
// tiefer eingerückte Ebenen schließen, bis die oberste Ebene <= aktuelle Einrückung ist
while (stack.length && stack[stack.length - 1].indent > indent) {
html += '' + stack.pop().tag + '>';
}
const top = stack[stack.length - 1];
if (top && top.indent === indent && top.tag === tag) {
// gleiche Ebene, gleicher Listentyp: vorheriges
schließen, neues öffnen
html += '
' + item;
}
else {
if (top && top.indent === indent) {
// gleiche Ebene, anderer Listentyp (z. B. Wechsel von - zu 1.): Liste wechseln
html += '
' + stack.pop().tag + '>';
}
// neue (tiefere oder erste) Liste öffnen
html += '<' + tag + '>
');
content = convertMarkdownTablesInChat(content);
// Mehrzeilige Code-Blöcke mit Sprachangabe (```php ... ```)
content = content.replace(/```(\w+)?\n([\s\S]+?)```/g, (match, lang, code) => {
lang = lang || "code"; // Falls keine Sprache angegeben ist, Standard auf "code"
return `
');
// Ersetzt Inline-Code `...`
content = content.replace(/`([^`]+)`/g, '$1');
// Zeilenumbruch
//content = content.replace(/\n/g, " ");
// Ersetze Zeilenumbrüche durch , aber NICHT nach
,
oder
content = content.replace(/(?)\n/g, ' ');
content = content.replace(/\r/g, '');
// Wenn Zeilenumbrüche am Ende, dann entfernen
content = content.replace(/( \s*)+$/gi, '');
// [Text=...] zu
mit Markdown-Listen-Unterstützung. Muss vor **fett**/*kursiv*
// laufen, damit *-Aufzählungszeichen nicht als Kursiv-Markierung interpretiert werden.
content = content.replace(/\[Text=([^\s\]]+)\s+"([^"]*)"\s+"([^"]+)"\]/g, function(match, id, cls, text) {
return '