Configure your application
Product: Chatbot (change)
Industry Steps Here
1) Choose Application Type
Choose the type. FiberAI is available at https://agent.vizaport.com. Network Visualizer is a widget placed on your site.
2) Customize
Customize for your data, branding and features (optional). Parameters change based on widget type.
Industry
Text
Colors
Icons
Links
Text
Colors
Icons
Links
Settings
Network Visualizer Options
Property Visualizer Options
Solar Visualizer Options
There are no specific configuration options for your industry.
3) Preview
Preview your widget here before purchasing or installing on your web site.
Your plan
- Plan: –
- Assets: –
- Route miles: –
- AI training files: –
- Requests: – per mo
Monthly subscription
4) Your Widget Code
Copy and paste this onto your web page. Click here for installation help.
`;
popupCode.value = scriptString;
var encodedSettings = encodeURIComponent(scriptString);
updateChatWidgetSettings(encodedSettings)
.then(response => console.log('API Response:', response))
.catch(error => console.error('Error:', error));
}
function updateAll() {
// fix any issues with extra amp;
parameterString = parameterString.replace(/&/g, '&');
// Generic replace function to remove keys with blank values
parameterString = parameterString.replace(/([a-zA-Z0-9]+)=&/g, '');
updatePreview();
updateCopyCode();
var encodedSettings = encodeURIComponent(parameterString);
updateWidgetSettings(encodedSettings)
.then(response => console.log('API Response:', response))
.catch(error => console.error('Error:', error));
}
function formatHeightAsPixel(value) {
const parsedHeight = parseFloat(value);
return !isNaN(parsedHeight) ? parsedHeight + 'px' : value;
}
function formatHeightAsPercentage(value) {
if (value.includes('px')) {
return value; // If 'px' is already present, return the original string
}
const parsedHeight = parseFloat(value);
return !isNaN(parsedHeight) ? parsedHeight + '%' : value + 'px';
}
function uiChangeFrameDimensions() {
const widthInput = document.getElementById("iframe_width");
const heightInput = document.getElementById("iframe_height");
iframeWidthValue = formatHeightAsPercentage(widthInput.value) || '100%';
iframeHeightValue = formatHeightAsPixel(heightInput.value) || '650px';
// Update iframe dimensions
vizaportWidget.style.width = iframeWidthValue;
vizaportWidget.style.height = iframeHeightValue;
updateCopyCode();
}
function uiParamChange(checkbox) {
// Read the name and checked status of the checkbox
const paramName = checkbox.name;
const paramValue = checkbox.checked ? 'true' : 'false';
// Check if the parameter already exists in the parameterString
const regex = new RegExp(`\b${paramName}=\w+\b`);
if (regex.test(parameterString)) {
// Update the value of the existing parameter
parameterString = parameterString.replace(regex, `${paramName}=${paramValue}`);
} else {
// Add the new parameter to the parameterString
parameterString += `&${paramName}=${paramValue}`;
}
// Create the new iframe source URL with the updated parameterString
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
updateAll();
}
function uiParamChange_AI(selectedOption) {
switch (selectedOption) {
case "ai_off":
// Check and update ai_icon parameter
if (parameterString.includes("ai_icon=")) {
parameterString = parameterString.replace(/&ai_icon=w+/, "&ai_icon=false");
} else {
parameterString += "&ai_icon=false";
}
// Remove aiDefaultOn and aiOnQuery if present
parameterString = parameterString.replace(/&aiDefaultOn=w+/, "");
parameterString = parameterString.replace(/&aiOnQuery=w+/, "");
break;
case "ai_on":
// Check and update aiDefaultOn parameter
if (parameterString.includes("aiDefaultOn=")) {
parameterString = parameterString.replace(/&aiDefaultOn=w+/, "&aiDefaultOn=true");
} else {
parameterString += "&aiDefaultOn=true";
}
// Remove ai_icon if present
parameterString = parameterString.replace(/&ai_icon=w+/, "");
parameterString = parameterString.replace(/&aiOnQuery=w+/, "");
break;
case "ai_on_query":
// Check and update aiOnQuery parameter
if (parameterString.includes("aiOnQuery=")) {
parameterString = parameterString.replace(/&aiOnQuery=w+/, "&aiOnQuery=true");
} else {
parameterString += "&aiOnQuery=true";
}
// Remove aiDefaultOn and ai_icon if present
parameterString = parameterString.replace(/&aiDefaultOn=w+/, "");
parameterString = parameterString.replace(/&ai_icon=w+/, "");
break;
default:
// Handle other cases or errors if needed
break;
}
// Create the new iframe source URL with the updated parameterString
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
updateAll();
}
function uiParamChangeInput(inputElement) {
// Read the name and value of the input text field
const paramName = inputElement.name;
const paramValue = inputElement.value;
checkForAiResponseMessage(paramName, paramValue);
// Check if the parameter already exists in the parameterString
console.log("-----------" + parameterString);
const regex = new RegExp(`${paramName}=([^&"]+)`);
if (regex.test(parameterString)) {
// Update the value of the existing parameter
if (paramValue === '') {
console.log('param value: ' + paramValue);
parameterString = parameterString.replace(regex, '');
} else {
parameterString = parameterString.replace(regex, `${paramName}=${paramValue}`);
}
} else {
// Add the new parameter to the parameterString
parameterString += `&${paramName}=${paramValue}`;
}
parameterString = parameterString.replace('&&', '&');
parameterString = parameterString.replace('#', ''); // # sign for hex value needs to be removed for iFrame Widget
// Create the new iframe source URL with the updated parameterString
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
updateAll();
}
async function checkForAiResponseMessage(paramName, paramValue){
const resultJson = await getAiResponseMessage(key);
let currentTemplate = { OnNet: '', NearNet: '', OffNet: '', fiberLineColor:'', fiberRouteColor:'' };
if (resultJson) {
try {
currentTemplate = JSON.parse(resultJson);
} catch (e) {
console.error("Error parsing JSON:", e);
}
}
switch (paramName) {
case 'onNetMsg':
currentTemplate.OnNet = paramValue;
break;
case 'nearNetMsg':
currentTemplate.NearNet = paramValue;
// Inline logic to update the dynamic message
const dynamicMessage = document.querySelector('.dynamic-message');
if (paramValue.trim() === '') {
dynamicMessage.style.display = 'none'; // Hide message if input is empty
} else {
const message = paramValue
.replace(/{distance}/g, 185)
.replace(/{endGeoPoint}/g, '35.81744, -78.66099')
.replace(/{cost}/g, '3,500');
dynamicMessage.innerHTML = `Message Example: ${message}`; // Update message
dynamicMessage.style.display = 'inline'; // Show the message
}
break;
case 'offNetMsg':
currentTemplate.OffNet = paramValue;
break;
case 'fiberLineColor':
currentTemplate.fiberLineColor = paramValue;
break;
case 'fiberRouteColor':
currentTemplate.fiberRouteColor = paramValue;
break;
default:
console.log(`Unknown parameter: ${paramName}`);
break;
}
updateAiResponseMessage(key, currentTemplate);
}
function uiParamChange_units(units) {
const paramName = "defaultUnits";
const paramValue = units;
const regex = new RegExp(`\b${paramName}=\w+\b`);
if (regex.test(parameterString)) {
// Update the value of the existing parameter
parameterString = parameterString.replace(regex, `${paramName}=${paramValue}`);
} else {
// Add the new parameter to the parameterString
parameterString += `&${paramName}=${paramValue}`;
}
// Create the new iframe source URL with the updated parameterString
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
updateAll();
}
// Function to show/hide sections based on the clicked tab
function showSection(sectionId) {
const sections = ["industry_div", "text", "colors", "icons", "links", "chat-text", "chat-colors", "chat-icons", "chat-links", "defaults" ];
sections.forEach((section) => {
const tab = document.querySelector(`#tab-${section}`);
const content = document.querySelector(`#${section}`);
if (tab && content) { // Ensure both tab and content elements exist
if (section === sectionId) {
tab.classList.add("active-tab");
content.style.display = "block";
} else {
tab.classList.remove("active-tab");
content.style.display = "none";
}
} else {
console.warn(`Element not found for section: ${section}`);
}
});
}
function parseAndApplySettings(widgetCodeSettings) {
if (widgetCodeSettings) {
// Parse the query string into key-value pairs
const params = new URLSearchParams(widgetCodeSettings);
// Loop through the parameters
for (const [paramName, paramValue] of params.entries()) {
// Find the corresponding HTML element by its ID
const element = document.getElementById(paramName);
if (element) {
// Check the type of the element and set its value accordingly
if (element.type === 'checkbox' || element.type === 'radio') {
element.checked = paramValue === 'true';
} else {
element.value = paramValue;
}
}
// Special cases
//if (paramName == "launcherType") {
// const iconRadio = document.getElementById('launcherType_icon');
// const tabRadio = document.getElementById('launcherType_tab');
// if (paramValue === "tab") {
// tabRadio.checked = true;
// } else {
// iconRadio.checked = true;
// }
//}
if (paramName == "defaultPosition") {
const rightRadio = document.getElementById('defaultPosition_right');
const leftRadio = document.getElementById('defaultPosition_left');
if (paramValue === "left") {
leftRadio.checked = true;
} else {
rightRadio.checked = true;
}
}
if (paramName == "voiceInput") {
const voiceInputOnRadio = document.getElementById('voiceInput_on');
const voiceInputOffRadio = document.getElementById('voiceInput_off');
if (paramValue === "off") {
voiceInputOffRadio.checked = true;
} else {
voiceInputOnRadio.checked = true;
}
}
if (paramName == "voiceOutput") {
const voiceOutputOnRadio = document.getElementById('voiceOutput_on');
const voiceOutputOffRadio = document.getElementById('voiceOutput_off');
if (paramValue === "off") {
voiceOutputOffRadio.checked = true;
} else {
voiceOutputOnRadio.checked = true;
}
}
if (paramName == "defaultUnits") {
const metricRadio = document.getElementById('units_metric');
const imperialRadio = document.getElementById('units_imperial');
if (paramValue === "metric") {
metricRadio.checked = true;
} else {
imperialRadio.checked = true;
}
}
//if (paramName == "ai_icon") {
// const aiOffRadio = document.getElementById('ai_off');
// if (paramValue === "false") {
// aiOffRadio.checked = true;
// }
//}
//if (paramName == "aiDefaultOn") {
// const aiOnRadio = document.getElementById('ai_on');
// if (paramValue === "true") {
// aiOnRadio.checked = true;
// }
//}
//if (paramName == "aiOnQuery") {
// const aiOnQueryRadio = document.getElementById('ai_on_query');
// if (paramValue === "true") {
// aiOnQueryRadio.checked = true;
// }
//}
}
}
}
function updateHTMLFromSettings() {
getWidgetSettings(key)
.then(settings => {
console.log('Settings:', settings);
parseAndApplySettings(settings);
})
.catch(error => console.error('Error:', error));
}
function uiParamChange_popup_radio(paramName, paramValue) {
if (paramValue === '') {
return; // Don't do anything if the value is blank
}
if (popupParameterString.includes(`${paramName}=`)) {
const regex = new RegExp(`${paramName}=[^&]*`);
popupParameterString = popupParameterString.replace(regex, `${paramName}=${paramValue}`);
} else {
popupParameterString += `&${paramName}=${paramValue}`;
}
// Create the new iframe source URL with the updated parameterString
updateCopyCodePopup();
updateIframeSource();
}
function uiParamChange_popup_checkbox(paramName, checkboxElement) {
const paramValue = checkboxElement.checked ? 'true' : 'false';
if (popupParameterString.includes(`${paramName}=`)) {
const regex = new RegExp(`${paramName}=[^&]*`);
popupParameterString = popupParameterString.replace(regex, `${paramName}=${paramValue}`);
} else {
popupParameterString += `&${paramName}=${paramValue}`;
}
// Create the new iframe source URL with the updated parameterString
updateCopyCodePopup();
updateIframeSource();
}
// Replace parameters for Script
function popupParamAddOrReplace(inputElement) {
const paramName = inputElement.name;
var paramValue = inputElement.value.trim();
// Remove single quotes which can cause problems saving to the database.
paramValue = paramValue.replace(/'/g, '');
// Check if paramValue is only a number and add hex #
if (/^d+$/.test(paramValue) && parseInt(paramValue) > 99999) {
paramValue = `#${paramValue}`;
}
if (paramValue === '') {
// Remove the parameter from popupParameterString
const regex = new RegExp(`${paramName}=[^&]*(&|$)`);
popupParameterString = popupParameterString.replace(regex, '');
return;
}
if (popupParameterString.includes(`${paramName}=`)) {
const regex = new RegExp(`${paramName}=[^&]*`);
popupParameterString = popupParameterString.replace(regex, `${paramName}=${paramValue}`);
} else {
popupParameterString += `&${paramName}=${paramValue}`;
}
}
// Popup Widget change params
function uiChangePopupParams(chatTextParam) {
const chatTextInput = document.getElementById(chatTextParam);
// Special case for some elements
switch (chatTextParam) {
case 'defaultHeight':
var enteredValue = parseInt(chatTextInput.value);
if (enteredValue < 400) {
if (!chatTextInput.hasAttribute("data-alert-triggered")) {
alert("Height must be at least 400px");
chatTextInput.setAttribute("data-alert-triggered", "true");
}
return;
}
break;
case 'defaultWidth':
var enteredValue = parseInt(chatTextInput.value);
if (enteredValue < 300) {
if (!chatTextInput.hasAttribute("data-alert-triggered")) {
alert("Width must be at least 300px");
chatTextInput.setAttribute("data-alert-triggered", "true");
}
return;
}
break;
case 'baseColor':
case 'titleColor':
case 'userTextColor':
case 'chatTextColor':
var enteredValue = chatTextInput.value.trim();
if (!/^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})|)$/.test(enteredValue)) {
if (!chatTextInput.hasAttribute("data-alert-triggered")) {
alert("Please enter a valid 3 or 6 hex color code such as #abc or #abc123");
chatTextInput.setAttribute("data-alert-triggered", "true");
}
return;
}
// Remove the attribute when a valid color is entered
chatTextInput.removeAttribute("data-alert-triggered");
break;
}
if (chatTextInput) {
popupParamAddOrReplace(chatTextInput);
}
updateCopyCodePopup();
updateIframeSource();
}
copyButton.addEventListener("click", function() {
if (currentType == "popup_widget") {
popupCode.select();
popupCode.setSelectionRange(0, 99999); // For mobile devices
} else {
htmlCode.select();
htmlCode.setSelectionRange(0, 99999);
}
// Copy the selected text to the clipboard
document.execCommand("copy");
// Deselect the text
window.getSelection().removeAllRanges();
// Change button text to indicate success
copyButton.innerText = "Copied!";
setTimeout(function() {
copyButton.innerText = "Copy";
}, 2000); // Reset button text after 2 seconds
});
// Add an event listener for the "paste" event on the htmlCode textarea
htmlCode.addEventListener("paste", function(event) {
const clipboardData = event.clipboardData || window.clipboardData;
const pastedText = clipboardData.getData("text/plain");
preview.innerHTML = pastedText;
});
// All input fields that listen for enter key and call uiParamChangeInput
const inputIds = ["welcomeTextInput", "visual_baseColor", "companyLogoInput", "welcomePageUrl", "applyPageUrl", "defaultRadius", "defaultLatitude", "defaultLongitude", "onNetMsg", "nearNetMsg", "offNetMsg", "onNetRadius", "nearNetRadius", "fiberPerMeter"];
inputIds.forEach(function(id) {
const input = document.getElementById(id);
input.addEventListener("keydown", function(event) {
if (event.key === "Enter" || event.keyCode === 13) {
event.preventDefault();
uiParamChangeInput(input);
}
});
});
document.getElementById("iframe_width").addEventListener("keydown", function (event) {
if (event.key === "Enter" || event.keyCode === 13) {
uiChangeFrameDimensions();
}
});
document.getElementById("iframe_height").addEventListener("keydown", function (event) {
if (event.key === "Enter" || event.keyCode === 13) {
uiChangeFrameDimensions();
}
});
htmlCode.addEventListener("keydown", function (event) {
if (event.key === "Enter" || event.keyCode === 13) {
var latestText = htmlCode.value; // Assuming popupCode is an input element
htmlCodeTextModified(latestText);
}
});
popupCode.addEventListener("keydown", function (event) {
if (event.key === "Enter" || event.keyCode === 13) {
var latestText = popupCode.value; // Assuming popupCode is an input element
popupCodeTextModified(latestText);
}
});
// Functions to update the preview and set the parameters when text box is manually updated
function htmlCodeTextModified(latestText) {
var iframeCode = latestText;
var pattern = /src=['"](.*?)['"]/;
var matches = pattern.exec(iframeCode);
if (matches) {
var src = matches[1]; // Get the src value
// Get the parameters after the first '&' character
parameterString = "&" + src.split('&').slice(1).join('&');
parameterString = parameterString.replace(/&/g, '&');
widgetKey = 'key=' + key;
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
parseAndApplySettings(parameterString);
updateAll();
}
}
function popupCodeTextModified(latestText) {
var scriptCode = latestText;
// pull the parameter string from the popupcode that has been manually edited
var pattern = /src=['"](.*?)?(.*?)['"]/;
var matches = pattern.exec(scriptCode);
if (matches) {
popupParameterString = matches[2]; // Get the parameters
parseAndApplySettings(popupParameterString);
updateCopyCodePopup();
updateIframeSource();
}
}
// Function to add event listeners for parameter IDs - For Chat Widget (Popup) - Text only ones
function addEventListenersForChatTextParams(popup_text_paramIds) {
popup_text_paramIds.forEach((popup_text_paramId) => {
const inputElement = document.getElementById(popup_text_paramId);
if (inputElement) {
inputElement.addEventListener("keydown", function (event) {
if (event.key === "Enter" || event.keyCode === 13) {
uiChangePopupParams(popup_text_paramId);
}
});
}
});
}
// Call the function with an array of parameter IDs
const popup_text_paramIds = ['onNetMsg', 'nearNetMsg', 'offNetMsg', 'onNetRadius', 'nearNetRadius', 'fiberPerMeter', 'baseColor', 'titleColor', 'userTextColor', 'chatTextColor', 'fontSize', 'fontFamily', 'chatWelcomeText', 'tabText', 'initialPlaceholder', 'loadingMessage', 'defaultWidth', 'defaultHeight', 'livePersonLimit', 'livePersonText', 'livePersonURL', 'aiPrompt', 'aiIcon', 'defaultRadius'];
addEventListenersForChatTextParams(popup_text_paramIds);
if (industryString === "Internet Provider") {
document.getElementById("internet_provider").style.display = "flex";
document.getElementById("real_estate").style.display = "none";
document.getElementById("energy").style.display = "none";
document.getElementById("no_configs").style.display = "none";
document.getElementById('tab-industry_div').innerHTML = 'Network';
} else if (industryString === "Real Estate") {
document.getElementById("real_estate").style.display = "flex";
document.getElementById("internet_provider").style.display = "none";
document.getElementById("energy").style.display = "none";
document.getElementById("no_configs").style.display = "none";
document.getElementById('tab-industry_div').innerHTML = 'Property';
} else if (industryString === "Energy") {
document.getElementById("energy").style.display = "flex";
document.getElementById("real_estate").style.display = "none";
document.getElementById("internet_provider").style.display = "none";
document.getElementById("no_configs").style.display = "none";
document.getElementById('tab-industry_div').innerHTML = 'Solar';
} else {
industryString = "";
document.getElementById("no_configs").style.display = "flex";
document.getElementById("internet_provider").style.display = "none";
document.getElementById("real_estate").style.display = "none";
document.getElementById("energy").style.display = "none";
document.getElementById('tab-industry_div').innerHTML = 'Industry';
}
function updateParamStringByIndustry() {
var industrySelection = document.getElementById("industry").value;
const selectedIndustry = industrySettings.find(setting => setting.industry === industrySelection);
if (selectedIndustry) {
parameterString = selectedIndustry.defaultParams;
} else {
parameterString = "";
}
}
function checkMandatoryParamStringByIndustry(widgetTypeForParam) {
var industrySelection = document.getElementById("industry").value;
const selectedIndustry = mandatoryIndustrySettings .find(setting => setting.industry === industrySelection);
if (selectedIndustry) {
var mandatoryParam = selectedIndustry.mandatoryParam;
console.log('mandatory param: ' + mandatoryParam);
var checkboxElement = document.getElementsByName(mandatoryParam)[0]; // Get the checkbox element
if (checkboxElement) {
if (widgetTypeForParam == "iframe_widget") {
uiParamChange(checkboxElement); // Pass the checkbox element to uiParamChange
}
if (widgetTypeForParam == "popup_widget")
{
uiParamChange_popup_checkbox(mandatoryParam, checkboxElement);
}
}
}
}
async function getPublicAPIs() {
try {
// Step 1: Fetch JSON from the first API
const response = await fetch(widgetGetPublicAPIUrl);
const json = await response.json();
// Step 2: Sort JSON by industry and create columns
const industries = Array.from(new Set(json.map(item => item.industry))).sort();
for (const industry of industries) {
const column = document.createElement('div');
column.className = 'column';
const h4 = document.createElement('h4');
h4.textContent = industry;
column.appendChild(h4);
// Step 3: Create rows for each industry
const industryItems = json.filter(item => item.industry === industry).sort((a, b) => a.sort_order - b.sort_order);
for (const item of industryItems) {
const label = document.createElement('label');
label.innerHTML = `
${item.display_name}
${item.description}
`;
column.appendChild(label);
}
document.getElementById('apiContainer').appendChild(column);
}
// Step 4: Call the second API
const companyResponse = await fetch(`${widgetGetCustomerAPIUrl}?company_id=${company_id}`);
const companyJson = await companyResponse.json();
// Step 5: Check the checkboxes based on the second API response
const checkboxes = document.querySelectorAll('.api_checkbox');
checkboxes.forEach(checkbox => {
const keyword = checkbox.id;
const matchingItem = companyJson.find(item => item.keyword === keyword);
if (matchingItem) {
checkbox.checked = true;
}
});
} catch (error) {
console.error('Error:', error);
}
}
function updatePublicAPIs(itemId, isChecked) {
// Convert boolean isChecked to integer is_active (1 if true, 0 if false)
const isActive = isChecked ? 1 : 0;
// Construct the URL
const apiUrl = `${widgetUpdateCustomerAPIUrl}?company_id=${company_id}&public_api_id=${itemId}&is_active=${isActive}`;
fetch(apiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => {
// Handle the response data if needed
console.log(data);
})
.catch(error => {
// Handle errors
console.error('Error:', error);
});
}
var scriptExecuted = false;
function updateIframeSource() {
var iframe = document.getElementById("vizaportPopup");
if (iframe) {
//popParameterString may have "#" that needs to be encoded first.
const encodedPopupParameterString = popupParameterString.replace(/#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})b/g, (match) => encodeURIComponent(match));
iframe.src = baseWidgetUrl + "/templates/widget_popup.html?" + encodedPopupParameterString;
} else {
console.error("Iframe with ID 'vizaportPopup' not found.");
}
}
function toggleVisualOptions(shouldHide) {
var visualOptions = document.querySelectorAll('.visual_option');
// Iterate through the elements and modify visibility or display
for (var i = 0; i < visualOptions.length; i++) {
if (shouldHide) {
//visualOptions[i].style.visibility = 'hidden';
visualOptions[i].style.display = 'none';
} else {
//visualOptions[i].style.visibility = 'visible';
visualOptions[i].style.display = 'block';
}
}
var chatOptions = document.querySelectorAll('.chat_option');
// Iterate through the elements and modify visibility or display
for (var i = 0; i < chatOptions.length; i++) {
if (!shouldHide) {
chatOptions[i].style.display = 'none';
} else {
chatOptions[i].style.display = 'block';
}
}
// Handle elements with both classes
var bothOptions = document.querySelectorAll('.visual_option.chat_option');
for (var i = 0; i < bothOptions.length; i++) {
// Show the element if it matches either condition
if (!shouldHide || shouldHide) {
bothOptions[i].style.display = 'block';
}
}
}
function widgetType(type) {
const iframeWidget = document.getElementById("iframe_widget");
const popupWidget = document.getElementById("popup_widget");
const widgetOption1 = document.getElementById("widget-option-1");
const widgetOption2 = document.getElementById("widget-option-2");
const widgetCustomization1 = document.getElementById("widget-customization-1");
const widgetCustomization2 = document.getElementById("widget-customization-2");
const previewHelpText = document.getElementById("previewHelpText");
const preview_popup = document.getElementById("preview_popup");
const preview = document.getElementById("preview");
const previewTitle = document.getElementById("previewTitle");
const widgetCodeSection = document.getElementById("widget_code_section");
preview_popup.style.display='none';
if (type === 'iframe_widget') {
currentType = "iframe_widget";
setCookie('currentType', currentType, 365);
iframeWidget.checked = true;
popupWidget.checked = false;
widgetCustomization2.style.opacity = 0.5;
widgetCustomization1.style.opacity = 1;
popupCode.style.display='none';
if (is_paid) {
if (licensemodel_name === "Pro" || licensemodel_name === "Enterprise") {
htmlCode.style.display='block';
} else {
// Need to show the previewDiv block with special text.
htmlPreviewDiv.style.display = 'block';
htmlPreviewDiv.innerHTML = 'To unlock the Visual Widget, please upgrade your plan by adding Visual Widget data in the AI Training step.';
}
}
toggleVisualOptions(false);
updateAll();
preview.style.display='block';
previewTitle.style.display='block';
previewHelpText.style.display='block';
widgetCodeSection.style.display='block';
} else if (type === 'popup_widget') {
currentType = "popup_widget";
setCookie('currentType', currentType, 365);
iframeWidget.checked = false;
popupWidget.checked = true;
widgetCustomization1.style.opacity = 0.5;
widgetCustomization2.style.opacity = 1;
htmlCode.style.display='none';
if (is_paid) {
popupCode.style.display='block';
paymentDiv.style.display = 'none';
htmlPreviewDiv.style.display = 'none';
}
toggleVisualOptions(true);
preview.style.display='none';
previewTitle.style.display='none';
previewHelpText.style.display='none';
widgetCodeSection.style.display='none';
updateIframeSource();
updateCopyCodePopup();
}
if (industryString !== "") {
showSection('industry_div');
} else {
if (currentType === "popup_widget") {
showSection('chat-text');
} else {
showSection('text');
}
}
console.log('Widget Type change called',type);
}
function extractParamsFromHtmlCode(htmlCode, key) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlCode, 'text/html');
const scriptTag = doc.querySelector('script');
if (scriptTag) {
const srcAttributeValue = scriptTag.getAttribute('src');
// Extract parameters after "?"
const scriptQueryParams = srcAttributeValue.split('?')[1];
const keyParamExists = scriptQueryParams && scriptQueryParams.includes('key=');
// If key parameter doesn't exist, add it
if (!keyParamExists && key) {
const updatedQueryParams = scriptQueryParams ? `${scriptQueryParams}&key=${key}` : `key=${key}`;
return updatedQueryParams;
}
return scriptQueryParams || '';
}
return '';
}
function initializeChatWidget() {
// For the popupWidget andd the key
popupParameterString = "key=" + key;
getChatWidgetSettings(key)
.then(html_code => {
if (html_code !== '') {
popupParameterString = extractParamsFromHtmlCode(html_code, key);
checkMandatoryParamStringByIndustry("popup_widget");
updateCopyCodePopup();
updateIframeSource();
parseAndApplySettings(popupParameterString);
} else if (currentType == "popup_widget") {
// Call updateCopyCodePopup here if html_code is empty and currentType is "popup_widget"
checkMandatoryParamStringByIndustry("popup_widget");
updateCopyCodePopup();
updateIframeSource();
}
})
.catch(error => console.error('Error:', error));
}
function initAiMessageSettings(){
getAiResponseMessage(key)
.then((settings) =>{
const settingJson = JSON.parse(settings);
const onNetMsgElement = document.getElementById("onNetMsg");
const nearNetMsgElement = document.getElementById("nearNetMsg");
const offNetMsgElement = document.getElementById("offNetMsg");
const fiberLineColorElement = document.getElementById('visual_fiberLineColor');
const fiberRouteColorElement = document.getElementById('visual_fiberRouteColor');
for (const key in settingJson) {
if(key === 'OnNet' && settingJson[key]){
onNetMsgElement.value = settingJson[key];
}
if(key === 'NearNet' && settingJson[key]){
nearNetMsgElement.value = settingJson[key];
}
if(key === 'OffNet' && settingJson[key]){
offNetMsgElement.value = settingJson[key];
}
if(key === 'fiberLineColor' && settingJson[key]){
fiberLineColorElement.value = settingJson[key];
}
if(key === 'fiberRouteColor' && settingJson[key]){
fiberRouteColorElement.value = settingJson[key];
}
}
})
}
// Main body
async function main() {
try {
// Wait for the asynchronous function to complete and get the key
key = await fetchKey();
if (key !== null) {
widgetKey = 'key=' + key;
console.log("WidgetKey: " + widgetKey);
// Event listener for changing industry - resets parameters if industry changes
document.getElementById("industry").addEventListener("change", function() {
widgetKey = 'key=' + key;
parameterString = "";
updateParamStringByIndustry();
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
console.log("WidgetKey: " + widgetKey);
updateAll();
updateHTMLFromSettings();
});
// On page load check the parameters for a widget key
if (key != "") {
// Get the widget settings from key and update param string
getWidgetSettings(key)
.then(settings => {
console.log('Settings:', settings);
if (settings === null || settings === "null") {
settings = '';
}
if (settings !== '') {
parameterString = settings;
checkMandatoryParamStringByIndustry("iframe_widget");
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
} else {
widgetUrl = widgetBaseUrl + widgetKey;
if (parameterString == "") {
updateParamStringByIndustry();
widgetUrl = widgetBaseUrl + widgetKey + parameterString;
}
}
updateAll();
updateHTMLFromSettings();
widgetType(currentType);
// Initialize the Chat Widget
initializeChatWidget();
// Initialize OnNet/NearNet/OffNet msg and fiberLineColor/fiberRouteColor
initAiMessageSettings();
})
.catch(error => console.error('Error:', error));
}
}
} catch (error) {
console.error('Error in main:', error);
}
}
// Call the main function
main();
// Call the API public function
//getPublicAPIs();
// On load default is iframe widget option
widgetType(currentType);