//make script aware of itself
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
var queryString = myScript.src.replace(/^[^\?]+\??/, '');
var params = parseQuery(queryString);
function parseQuery(query) {
var Params = new Object();
if (!query) return Params; // return empty object
var Pairs = query.split(/[;&]/);
for (var i = 0; i < Pairs.length; i++) {
var KeyVal = Pairs[i].split('=');
if (!KeyVal || KeyVal.length != 2) continue;
var key = unescape(KeyVal[0]);
var val = unescape(KeyVal[1]);
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
//build the chat widget
// Inject the CSS
const style = document.createElement('style');
document.head.insertAdjacentHTML('beforeend', '');
document.head.appendChild(style);
// Create chat widget container
const chatWidgetContainer = document.createElement('div');
chatWidgetContainer.id = 'chat-widget-container';
document.body.appendChild(chatWidgetContainer);
// Inject the HTML
chatWidgetContainer.innerHTML = `
Termin anfragen.
Jetzt mit unserer KI vorbereiten. Sicher und vertraulich.
Einen Moment, link zum Kontaktformular wird vorbereitet, bitte ein wenig Geduld.
`;
const wave = `
`;
let writing_promise;
//wait for things to happen
chatBubble.addEventListener('click', function () {
togglePopup();
if (firstTime) {
document.getElementById('lexi_video').play();
firstTime = false
}
});
closePopup.addEventListener('click', function () {
togglePopup();
});
chatInput.addEventListener('keyup', function (event) {
if (event.key === 'Enter') {
chatSubmit.click();
}
});
chatInput.addEventListener('focus', function (event) {
scroll_chat_bottom();
});
//also scroll when content changes (like a new message)
const observer = new MutationObserver(scroll_chat_bottom);
observer.observe(document.querySelector('#chat-messages'), { childList: true });
chatSubmit.addEventListener('click', function () {
if (chatInput.value.trim() !== '') {
const msgText = msgerInput.value.trim();
if (!msgText) return;
appendMessage(PERSON_NAME, PERSON_IMG, RIGHT_SIDE, msgText);
msgerInput.value = "";
sendMsg(msgText)
}
});
msgerForm.addEventListener("submit", event => {
event.preventDefault();
const msgText = msgerInput.value.trim();
if (!msgText) return;
appendMessage(PERSON_NAME, PERSON_IMG, RIGHT_SIDE, msgText);
msgerInput.value = "";
sendMsg(msgText)
});
//check/start chat
startConversation()
//togglePopup();
/*
// Function to delete chat history records for a user ID using the API
function deleteChatHistory(userId) {
if (!confirm("Are you sure? Your Session and History will delete for good.")) {
return false
}
fetch('lexi/deleteHistory?user=' + USER_ID, {
method: 'DELETE',
headers: {'Content-Type': 'application/json'}
})
.then(response => {
if (!response.ok) {
throw new Error('Error deleting chat history: ' + response.statusText);
}
deleteAllCookies()
location.reload(); // Reload the page to update the chat history table
})
.catch(error => console.error(error));
}
// Event listener for the Delete button click
const deleteButton = document.querySelector('#delete-button');
deleteButton.addEventListener('click', event => {
event.preventDefault();
deleteChatHistory(USER_ID);
});*/
// Function to send a message to the API
function getHistory() {
var formData = new FormData();
fetch('https://anwalt.rechtecheck.com/anwalt/lexi/get_history', {method: 'POST', body: formData})
.then(response => response.json())
.then(chatHistory => {
if (chatHistory.error > 0) {
startConversation()
} else {
for (const row of chatHistory) {
appendMessage(PERSON_NAME, PERSON_IMG, RIGHT_SIDE, row.human);
appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, row.ai, "");
}
}
})
.catch(error => {
appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, 'Es scheint ein Irrtum zu geben', "");
appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, ' Bitte laden Sie die Seite neu.', "");
});
}
function startConversation() {
console.log('patata');
appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, 'Hallo, mein Name ist Lexi, die KI-Assistenz der Kanzlei. Wie können wir Ihnen heute helfen?', "");
}
function sendMsg(msg) {
changeVideo();
var formData = new FormData();
formData.append('anwalt_id', ANWALT_ID);
formData.append('lexi_chat_id', CHAT_ID);
formData.append('msg', msg);
fetch('https://anwalt.rechtecheck.com/anwalt/lexi/send_message', {method: 'POST', body: formData})
.then(response => response.json())
.then(data => {
if (data.is_chat_ended) {
appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, data.message.content, "");
msgerChat.insertAdjacentHTML("beforeend", chat_ended_msg);//no se usa la funcion porque el stilo difiere de un mensaje normal
awaitreply();
zusammenfassung();
} else if (data.message.content != "") {
appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, data.message.content, "");
}
/*
let uuid = uuidv4()
const eventSource = new EventSource(`https://anwalt.rechtecheck.com/anwalt/lexi/event_stream?chat_history_id=${data.id}&id=${encodeURIComponent(USER_ID)}`);
console.log(eventSource);
awaitReplyElement.remove();
appendMessage(BOT_NAME, BOT_IMG, "left", "", uuid);
changeVideo();
const div = document.getElementById(uuid);
eventSource.onmessage = function (e) {
if (e.data == "[DONE]") {
msgerSendBtn.disabled = false
eventSource.close();
} else {
let txt = JSON.parse(e.data).choices[0].delta.content
if (txt !== undefined) {
div.innerHTML += txt.replace(/(?:\r\n|\r|\n)/g, ' ');
}
}
};
eventSource.onerror = function (e) {
msgerSendBtn.disabled = false
console.log(e);
let txt = JSON.parse(e.data).choices[0].delta.content
if (txt !== undefined) {
div.innerHTML += txt.replace(/(?:\r\n|\r|\n)/g, ' ');
}
eventSource.close();
};*/
})
.catch(error => {
appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, 'Es scheint ein Irrtum zu geben. \n Bitte laden Sie die Seite neu.', "");
});
}
async function writeText(content, container) {
writing_promise = null;
var contentArray = content.split(""),
current = 0,
elem = container;
return isinterval = setInterval(function () {
if (current < contentArray.length) {
elem.innerHTML += contentArray[current++];
scroll_chat_bottom();
} else {
chatInput.disabled = false;
// chatInput.focus();
clearInterval(isinterval);
isinterval = undefined;
scroll_chat_bottom();
}
}, 20);
}
function appendMessage(name, img, side, text, id) {
chatInput.disabled = true
const msgHTML = `
`;
let replyElement = document.getElementById('await-reply-container')
if (replyElement) {
replyElement.remove();
}
msgerChat.insertAdjacentHTML("beforeend", msgHTML);
if (side === 'bot') {
writing_promise = writeText(text, document.getElementById('last_msg'));
document.getElementById('last_msg').setAttribute('id', '')
} else {
document.getElementById('last_msg').innerHTML = text;
document.getElementById('last_msg').setAttribute('id', '')
chatInput.value = '';
awaitreply();
}
scroll_chat_bottom();
}
function zusammenfassung() {
/* appendMessage(BOT_NAME, BOT_IMG, LEFT_SIDE, 'Vielen Dank für die Vorbereitung zu Ihrem Fall. Wir rufen jetzt das Formular zur Adresseingabe auf, das aus Datenschutzgründen getrennt ist \n ' +
'Link zum Kontaktformular wird vorbereitet, bitte ein wenig Geduld.', "");*/
var formData = new FormData();
formData.append('anwalt_id', ANWALT_ID);
formData.append('lexi_chat_id', CHAT_ID);
zusammenfassung_call(formData)
/* navigator.geolocation.getCurrentPosition(function (position) {
formData.append('lat', position.coords.latitude);
formData.append('long', position.coords.longitude);
});*/
}
let firstzusammenfassung_call = true;
function zusammenfassung_call(formData) {
fetch('https://anwalt.rechtecheck.com/anwalt/lexi/zusammenfassung', {method: 'POST', body: formData})
.then(response => response.json())
.then(response => {
msgerChat.insertAdjacentHTML("beforeend", response.link);
removeawaitreply();
scroll_chat_bottom();
})
.catch(error => {
removeawaitreply();
zusammenfassung_call(formData);
scroll_chat_bottom();
});
}
// Utils
function get(selector, root = document) {
return root.querySelector(selector);
}
function formatDate(date) {
const h = "0" + date.getHours();
const m = "0" + date.getMinutes();
return `${h.slice(-2)}:${m.slice(-2)}`;
}
function random(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function uuidv4() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
function deleteAllCookies() {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i];
const eqPos = cookie.indexOf("=");
const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
function awaitreply() {
const replyElement = document.createElement('div');
chatInput.disabled = true;
replyElement.className = 'flex mb-3';
replyElement.innerHTML = `
${wave}
`;
chatMessages.appendChild(replyElement);
chatMessages.scrollTop = chatMessages.scrollHeight;
scroll_chat_bottom();
}
function removeawaitreply() {
const replyElement = document.getElementById('await-reply-container');
replyElement.remove();
chatInput.disabled = false;
}
function changeVideo() {
let video = document.getElementById('lexi_video');
let oldSource = document.getElementById('video_here');
let newSource = document.createElement('source');
newSource.setAttribute('id', 'video_here');
newSource.setAttribute('type', 'video/mp4');
newSource.setAttribute('src', 'https://anwalt.rechtecheck.com/anwalt/assets/lexi/Finish_01.mp4');
newSource.setAttribute('loop', 'true');
oldSource.remove();
video.appendChild(newSource);
video.load();
}
//open close chat
function togglePopup() {
// const chatPopup = document.getElementById('chat-popup');
chatPopup.classList.toggle('hidden');
if (!chatPopup.classList.contains('hidden')) {
// document.getElementById('chat-input').focus();
}
}
function lexiSleep(ms) {
var esperarHasta = new Date().getTime() + ms;
while (new Date().getTime() < esperarHasta) continue;
}
function scroll_chat_bottom() {
document.getElementById('chat-messages').scrollTop = document.getElementById('chat-messages').scrollHeight;
}
function fromHTML(html, trim = true) {
// Process the HTML string.
html = trim ? html.trim() : html;
if (!html) return null;
// Then set up a new template element.
const template = document.createElement('template');
template.innerHTML = html;
const result = template.content.children;
// Then return either an HTMLElement or HTMLCollection,
// based on whether the input HTML had one or more roots.
if (result.length === 1) return result[0];
return result;
}
window.visualViewport.addEventListener("resize", () => {
const chatBox = document.querySelector("#chat-popup");
if (chatBox) {
chatBox.style.bottom = `${window.innerHeight - window.visualViewport.height }px`;
}
});