const root_url = 'https://localbee.aivisions.no';
const months = ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'];
const days_long = ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag','lørdag'];
const days = ['søn', 'man', 'tir', 'ons', 'tor', 'fre','lør'];
let state = 'new';
let params = new URLSearchParams(window.location.search);
let currentAudio = null; // This variable will hold the currently playing audio
let audioVolume = 1.0; // This variable will hold the currently playing audio
let socket = null;
let hivemaintenance_mode;
let currentOpenDatePickerTd; // This will hold the td that was clicked
// MAIN
$(document).ready(function() {
let savedVolumeState = get_cookie("audioVolumeState");
if (savedVolumeState) {
let $volumeButton = $('#speak_volume');
setVolumeState($volumeButton, savedVolumeState);
// If the saved state is muted, apply the shake animation
if (savedVolumeState === "muted") {
$volumeButton.addClass('fa-shake');
setTimeout(function() {
$volumeButton.removeClass('fa-shake');
}, 2500); // remove the animation classes after it completes
}
}
$('#speak_volume').click(function() {
let currentState = $(this).hasClass('fa-volume-high') ? 'muted' : 'high';
setVolumeState($(this), currentState);
});
hivemaintenance_mode = get_cookie("hivemaintenance_mode");
if ( hivemaintenance_mode === "1" ){
$("#header #hivemaintenance_mode").css('display', 'inline-block');
}
});
function newWssSocket( case_access_token ){
// If socket is already connected, close it.
if (isSocketConnected()) {
socket.close();
socket = null; // Set socket to null to ensure a fresh connection.
}
// Now create a new WebSocket connection
socket = new WebSocket('wss://www.api.legalai.as/' + case_access_token);
socket.addEventListener('message', function(e) {
console.log( 'Received data:', e.data );
if ( /^legalai\|\d+$/.test( e.data ) ){
checkCaseInfo( case_access_token );
}
});
}
function isSocketConnected(){
return socket && socket.readyState === WebSocket.OPEN;
}
function ucfirst(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
// Function to initialize tooltips
function initializeTooltips() {
$(".tooltip").tooltip({
items: ".tooltip",
content: function() {
return $(this).data("tooltiptext");
},
track: true
});
}
function formatDate(unixTimestamp) {
const date = new Date(unixTimestamp * 1000); // Convert to milliseconds
const day = date.getDate().toString().padStart(2, '0'); // Ensure the day is always 2 digits
const month = months[date.getMonth()];
const year = date.getFullYear();
const dayOfWeek = ucfirst( days[date.getDay()] );
// Extract the hours and minutes, padding with zeros if needed
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${dayOfWeek} ${day}. ${month} ${year} kl.${hours}:${minutes}`;
}
function rantokmize(text, div, delay, onComplete) {
let decodedText = htmlDecode(text);
let pieces = decodedText.split(/(?=\s|\b)/g);
clearTimeout(rantokmizeRunning);
// Add the fa-angles-down icon under the div using the ::before pseudo-element
$("#" + div).css("position", "relative").addClass("show-icon");
console.log("rantokmize: " + div);
let i = 0;
let wasClicked = false;
$("#" + div).on('click', function() {
wasClicked = true;
});
function processPiece() {
if (i >= pieces.length || wasClicked ) {
if (wasClicked) {
updateDiv(div, text, true);
$("#" + div).removeClass("show-icon");
stopSpeaking();
}
// Remove the fa-angles-down icon once writing is done
$("#" + div).removeClass("show-icon");
// Call the provided onComplete callback
if (onComplete && typeof onComplete === "function") {
onComplete();
}
return;
}
let piece = pieces[i];
if (piece.length > 5 || (piece.length > 2 && Math.random() < 0.66)) {
let randomIndex = Math.floor(Math.random() * piece.length / 1.7);
updateDiv(div, piece.substring(0, randomIndex), false);
pieces[i] = piece.substring(randomIndex);
} else {
updateDiv(div, piece, false);
i++;
}
rantokmizeRunning = setTimeout(processPiece, delay);
}
processPiece(); // Kick off the process
}
function speak(text, voice, onStarted) {
if (typeof voice === 'undefined') {
voice = 'female';
}
// Make the POST request to the text-to-speech endpoint
fetch("/api/2023-06/text2speech", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: text.replace(/[:\n]/g, '. '),
voice: voice
})
})
.then(response => response.json())
.then(data => {
stopSpeaking();
// Parse the response if needed
currentAudio = new Audio(data.mp3file);
currentAudio.volume = audioVolume;
// Add an event listener for the 'canplaythrough' event
currentAudio.addEventListener('canplaythrough', function() {
console.log('The mp3file is ready to be played without interruptions.');
// Start playing the audio
currentAudio.play();
// Call the onStarted callback after playing has started
if (onStarted && typeof onStarted === "function") {
onStarted();
}
});
})
.catch((error) => {
console.error('Error fetching mp3file:', error);
});
}
function stopSpeaking() {
if (currentAudio) {
currentAudio.pause();
// Manually trigger the 'ended' event
let event = new Event('ended');
currentAudio.dispatchEvent(event);
}
}
function copyToClipboard( element ){
let $temp = $("");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
function htmlDecode(input){
let doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
function updateDiv(div, text, shouldSet) {
$(div).slideDown();
// Replace all new line characters with HTML line breaks
text = text.replace(/\n/g, ' ');
// If shouldSet is true, set the innerHTML. Otherwise, append.
if (shouldSet) {
document.getElementById(div).innerHTML = text;
} else {
document.getElementById(div).innerHTML += text;
}
}
function get_formated_datetime( datetime ){
let dateParts = datetime.split(/[- :]/);
let year = dateParts[0].substring(2); // Get last two digits of the year
let month = months[parseInt(dateParts[1], 10) - 1]; // Month is 0-indexed in your array
let day = dateParts[2];
let time = dateParts.slice(3).join(':'); // Rejoin the time part
return day +' '+ month +'. '+ year +' '+ time;
}
function setVolumeState($speakVolumeButton, state) {
if (state === "muted" || (state === undefined && $speakVolumeButton.hasClass('fa-volume-high'))) {
$speakVolumeButton.removeClass('fa-volume-high').addClass('fa-volume-mute');
audioVolume = 0.0;
if (currentAudio) {
currentAudio.volume = 0.0; // Mute
}
set_cookie("audioVolumeState", "muted", 30, "/");
} else {
$speakVolumeButton.removeClass('fa-volume-mute').addClass('fa-volume-high');
audioVolume = 1.0;
if (currentAudio) {
currentAudio.volume = 1.0;
}
set_cookie("audioVolumeState", "high", 30, "/");
}
}
function getFontAwesomeIconForFileExtension(fileExtension) {
const iconToExtensionMap = {
'fa-file-pdf': ['pdf'],
'fa-file-word': ['doc', 'docx'],
'fa-file-excel': ['xls', 'xlsx'],
'fa-file-powerpoint': ['ppt', 'pptx'],
'fa-file-image': ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff'],
'fa-file-audio': ['mp3', 'wav', 'ogg', 'flac'],
'fa-file-video': ['mp4', 'avi', 'mkv', 'webm'],
'fa-file-csv': ['csv', 'tsv'],
'fa-file-archive': ['zip', 'rar', 'tar', 'gz', '7z'],
'fa-file-code': ['js', 'html', 'css', 'php', 'py', 'c', 'cpp', 'java', 'rb', 'xml', 'json']
};
for (let icon in iconToExtensionMap) {
if (iconToExtensionMap[icon].includes(fileExtension.replace('.', '').toLowerCase())) {
return icon;
}
}
return 'fa-file'; // Default icon
}
set_cookie = function( c_name, value, exdays, path ){
let expires = new Date();
expires.setTime( expires.getTime() + ( exdays * 86400000 ) );
let c_value = escape( value );
if ( exdays !== null ){
c_value = c_value + "; expires=" + expires.toUTCString();
}
if ( path !== null ){
c_value = c_value + "; path=" + path;
}
document.cookie = c_name + "=" + c_value;
}
get_cookie = function( c_name ){
let i,x,y,ARRcookies = document.cookie.split( ";" );
for( i=0; i 500) {
scale = 500 / viewport.width;
}
viewport = page.getViewport({ scale: scale });
let canvas = document.createElement('canvas');
canvas.width = viewport.width;
canvas.height = viewport.height;
let ctx = canvas.getContext('2d');
let renderContext = { canvasContext: ctx, viewport: viewport };
let renderTask = page.render(renderContext);
renderTask.promise.then(function() {
previewCache[url] = canvas; // Cache the rendered canvas
displayPreview(canvas, iconPosition);
});
});
});
}
function displayPreview(canvas, iconPosition) {
$('#pdf-preview').html(canvas).show();
let leftPosition = iconPosition.left - canvas.width - 10;
let topPosition = iconPosition.top;
// Calculate the potential bottom position
let bottomPosition = window.innerHeight - (iconPosition.top + $('#pdf-preview').height());
// Check if the bottom of the PDF preview would be out of the viewport
if (bottomPosition < 0) {
// Adjust the topPosition so the bottom of the preview aligns with the bottom of the icon
topPosition = iconPosition.top - $('#pdf-preview').height();
// Now check if placing at the top will make it go out of the viewport
if (topPosition < 0) {
// If so, center the preview in the viewport
topPosition = (window.innerHeight - $('#pdf-preview').height()) / 2;
}
}
$('#pdf-preview').css({
'left': leftPosition,
'top': topPosition
});
}
function openPDF(pdfPath) {
$('#pdf-embed').attr('src', pdfPath);
$('#pdf-overlay').show();
}
function cleanUrl(){
if (window.history && window.history.replaceState) {
var currentURL = window.location.href;
var baseURL = currentURL.split("#")[0];
history.replaceState({}, document.title, baseURL);
}
}
function logout(){
set_cookie("showMessage", "Du ble logget ut automatisk.", 30, "/");
top.window.location.href = '/admin';
}
function ajaxCall(url, type, payload, successCallback) {
$.ajax({
url: url,
type: type,
data: payload,
contentType: 'application/json',
success: function( data, textStatus, xhr ){
successCallback( data, xhr.status );
},
error: function(xhr, status, error) {
if (xhr.status === 403) {
logout();
} else if (xhr.status === 0) { // Assuming status 0 might indicate network issues
// Display a custom message for presumed network issues
showMessage("No connection to server", "alert");
console.error("No connection to server");
} else {
// Show default error message
showMessage(error || "An unexpected error occurred", "warning");
console.error(error);
}
}
});
}