var CBOX = CBOX || (function () {
var _url = 'https://ccchat.iacad.gov.ae'
,_apiUrl = 'https://ccchat.iacad.gov.ae'
,_botUri = 'https://chatinbox.io:5000'
,_botName = 'wit'
,arebicWebsiteIds = '2'
,overlay = null
,session ={}
,_name =null
,_bot_id =null
,_website_data =null
,_website_id=null
,_department_id
,waitTimeout
,_chatbot_transfer
,_closeChat=false
,slide_index ={}
_show_time =false
,_agent_status ='online'
,_userInfo={}
,_agentTransfer=null
,validation={}
,botMessageData={}
,_current_intent =(sessionStorage.getItem('current_intent')&&sessionStorage.getItem('current_intent') !='null'&&sessionStorage.getItem('current_intent') !='undefined')?sessionStorage.getItem('current_intent'):null;
var _CBOX_agentID =(sessionStorage.getItem('CBOX_agentID') && sessionStorage.getItem('CBOX_agentID') !='null' &&sessionStorage.getItem('CBOX_agentID') !='undefined' ) ? sessionStorage.getItem('CBOX_agentID') : null;
var _CBOX_agent_name =(sessionStorage.getItem('CBOX_agent_name')&&sessionStorage.getItem('CBOX_agent_name') !='null'&&sessionStorage.getItem('CBOX_agent_name') !='undefined')?sessionStorage.getItem('CBOX_agent_name'):null;
console.log(_CBOX_agentID);
// var ua = {};
var userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
var weekdays = new Array(7);
weekdays[0] = "Sunday";
weekdays[1] = "Monday";
weekdays[2] = "Tuesday";
weekdays[3] = "Wednesday";
weekdays[4] = "Thursday";
weekdays[5] = "Friday";
weekdays[6] = "Saturday";
var timeDate = new Date();
weekday_value = timeDate.getDay();
var userDay = weekdays[weekday_value];
var UserDate = new Date();
//wait for response from bot is not get reponse then sent message to agent
var botResponseTimer ;
var botResponseTime = 10 ; //sec
h = (UserDate.getHours() < 10 ? '0' : '') + UserDate.getHours(),
m = (UserDate.getMinutes() < 10 ? '0' : '') + UserDate.getMinutes();
s = (UserDate.getSeconds() < 10 ? '0' : '') + UserDate.getSeconds();
mm = UserDate.getMonth() + 1;
var userTime = UserDate.getFullYear() + "-" + mm + "-" + UserDate.getDate() + " " + h + ":" + m + ":" + s;
// var userTime =UserDate 2014-02-06;
// console.log(userTime);
var website_id = null;
var agentname = null;
var visitor_id = null; // use this variable only for rating at end chat
//code for speach recognition
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
var recognition ;
if (('webkitSpeechRecognition' in window)) {
recognition = new SpeechRecognition();
recognition.lang = 'en-US';
recognition.interimResults = false;
recognition.maxAlternatives = 1;
}
var _voiceEnable =false;
//end config of speech recognition
function loadjscssfile(filename, filetype) {
if (filetype == "css") { //if filename is an external CSS file
var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", filename)
}else{
var fileref = document.createElement("script")
fileref.setAttribute("type", "text/javascript")
fileref.setAttribute("src", filename)
}
document.getElementsByTagName("head")[0].appendChild(fileref)
}
// loadjscssfile(_apiUrl + "/public/assets/css/chat_widget.css", "css");
loadjscssfile(_apiUrl + "/public/assets/css/widget.css", "css");
// loadjscssfile(_apiUrl + "/public/sip.js", "js");
/*
loadjscssfile(_apiUrl + "/public/assets/js/js/jquery.min.js", "js");
loadjscssfile(_apiUrl + "/public/assets/js/js/bootstrap.min.js", "js");
loadjscssfile(_apiUrl + "/public/assets/js/js/bootstrap.min.css", "css");
loadjscssfile(_apiUrl + "/public/assets/js/js/tooltip.js", "js");
loadjscssfile(_apiUrl + "/public/assets/js/js/css.js", "js");
*/
//loadjscssfile(_url+"/chatbox/public/widget_style.css", "css");
loadjscssfile(_apiUrl + "/public/assets/css/widget_rating.css", "css");
;
var _args = []; // private
var audio = {};
var socket //made connection to socket.io
var open = false;
var actionPerform = null; //need when chatboat send url for new action perform
return {
init: function (Args) {
window.resiz
var that = this;
if (Args[4] && Args[4] == 'overlay') {
// _args = Args;
_args = JSON.parse(window.sessionStorage.getItem('CBOX_ITEM')) || Args;
_args[4] = Args[4];
} else {
_args = JSON.parse(window.sessionStorage.getItem('CBOX_ITEM')) || Args;
if(_args[0] != Args[0]){
_args = Args;
}
}
_args = Object.values(_args);
// console.log(_args);
//save client data
// if(!_args[3])
this.getclientInfo(_args[3] || null);
//get form
this.loadChatForm();
window.addEventListener('message',function(event) {
console.log(event);
if(event.data){
try{
var data = JSON.parse(event.data);
if(data.message_data||data.message){
that.appendMessage(JSON.parse(event.data));
}else if(data.bot_data){
that.botMessage(data.bot_data);
}
}catch(err) {console.log('msgEventErr',err.message); }
}
});
},
socketConnection(){
var that =this;
socket.on('connect',function(){
console.log("amol","socket on connectes -> ");
if(_CBOX_agentID&&_CBOX_agentID !='null'&&_CBOX_agentID !='undefined'&&_args[3]){
socket.emit('add_room',{agent_id:_CBOX_agentID,customer_id:_args[3]});
}
that.newVisitor();
})
socket.on('reconnect',function(){
console.log("amol","socket on Reconnect -> ");
var formData = new FormData();
formData.append('id', _args[3]);
var xhr = new XMLHttpRequest();
xhr.open("post", _apiUrl + "/check_customerchat_status");
xhr.send(formData);
xhr.onreadystatechange = function () {
try {
if (this.readyState == 4 && (this.status == 200 || this.status == 201)) {
console.log(this.responseText);
var data_x = JSON.parse(this.responseText).data;
console.log("chat_ended_reconnect",data_x);
if(data_x.chat_ended==1){
setTimeout(function(){
console.log("runnerReconnectStat",data_x.chat_ended);
var footer =document.getElementsByClassName('cb-support-chat-footer');
for (var i = 0; i < footer.length; i++) {
footer[i].style.display='none';
}
},20);
}
}
} catch (e) {
console.log("check status error",e);
}
}
})
//socket Events
//event for new message from agent
//when agent no any agent free
socket.on('agents_busy',function(data){
if(this._agentTransfer!='busy'){
that.setEventMessage(data.message);
this._agentTransfer='busy';
}
})
socket.on('chat_transfer',function(data){
if(this._agentTransfer !='chat_transfer'){
that.setEventMessage(data.message);
this._agentTransfer='chat_transfer';
}
})
socket.on('new-message', function (data) {
// console.log(data);
// that.appendMessage(data);
if(_agent_status =='agent_offline'){
return false;
}
that.appendMessage(data);
that.startRecognition();
console.log(data);
overlay&&overlay.postMessage(JSON.stringify(data),'*');
//console.log(data.message);
clearTimeout(waitTimeout);
//console.log(data.message.data);
});
//when get new message from bot
socket.on('bot_message',function(data){
that.botMessage(data);
that.startRecognition();
overlay&&overlay.postMessage(JSON.stringify({bot_data:data}),'*');
})
//when it receive end chat even from agent
socket.on('end-widget', function () {
that.endWidget();
});
socket.on('visitor_data_change',function(data){
_name = data.name||_args[3];
});
//when it receive to update the attended by
socket.on('updateAttendedBy', function(data){
console.log('Updating Attended By');
data.userData&&window.sessionStorage.setItem('CBOX_agentID', data.userData);
data.agentName&&window.sessionStorage.setItem('CBOX_agent_name', data.agentName);
_CBOX_agentID = data.userData;
_CBOX_agent_name = data.agentName;
// document.getElementById("onlineAgent").innerHTML = data.agentName;
// that.showWaitMsg();
if(document.getElementById('reset_chat'))
{
document.getElementById('reset_chat').style.display = 'none';
}
});
socket.on('agent-typing', function(data){
var elem = document.getElementById('cd-agent-typing');
if(!elem){
that.agentTyping();
}
setTimeout(function(){
that.removeTyping();
},2000);
});
recognition&&recognition.addEventListener('speechstart', () => {
console.log('Speech has been detected.');
});
recognition&&recognition.addEventListener('result', (e) => {
console.log('Result has been detected.');
let last = e.results.length - 1;
let text = e.results[last][0].transcript;
document.querySelectorAll(".cb-CBOX_msg_name")[0].value = text;
// outputYou.textContent = text;
// setTimeout(function(){
that.chatBoxsendMsg(text);
// },1000);
document.getElementById('cbMicro').style.background = '#efefef';
console.log('Confidence: ' + e.results[0][0].confidence);
// socket.emit('chat message', text);
});
recognition&&recognition.addEventListener('speechend', () => {
recognition.stop();
document.getElementById('cbMicro').style.background = '#efefef';
});
recognition&&recognition.addEventListener('error', (e) => {
alert( e.error);
document.getElementById('cbMicro').style.background = '#efefef';
});
},
chatUnMute: function () {
var xhttp4 = new XMLHttpRequest();
var CBOX_audio = 0;
var CBOX_visitorID = _args[3];
xhttp4.open("get", _apiUrl + "/widget-data-audio?data1=" + CBOX_audio + "&data2=" + _args[3], true);
xhttp4.send();
document.getElementsByClassName('cb-cbox_mute')[0].style.display = '';
document.getElementsByClassName('cb-cbox_unmute')[0].style.display = 'none';
return false;
},
chatMute: function () {
var xhttp4 = new XMLHttpRequest();
var CBOX_audio = 1;
var CBOX_visitorID = _args[3];
xhttp4.open("get", _apiUrl + "/widget-data-audio?data1=" + CBOX_audio + "&data2=" + _args[3], true);
xhttp4.send();
document.getElementsByClassName('cb-cbox_mute')[0].style.display = 'none';
document.getElementsByClassName('cb-cbox_unmute')[0].style.display = '';
return false;
},
showWaitMsg: function(){
var that = this;
clearTimeout(waitTimeout);
waitTimeout = setTimeout(function(){
var chatMessage = 'Please Wait';
if(arebicWebsiteIds.indexOf(_website_id)> -1){
// chatMessage = 'ﻱﺮﺟﻯ ﺍﻼﻨﺘﻇﺍﺭ';
chatMessage = "يرجى الانتظار";
}
that.setEventMessage(chatMessage);
that.scrollBottom();
},30000);
},
download: function (data) {
console.log(_apiUrl + '/api/v1/chat-file-download?file=' + data);
// return false;
window.location.href = _apiUrl + '/api/v1/chat-file-download?file=' + data;
},
browseFile:function(){
document.getElementsByName('msg_file_cb')[0].click();
},
filePath:function(result){
console.log(result.file_path.slice(result.file_path.lastIndexOf('/') + 1));
var extension = result.file_path.slice(result.file_path.lastIndexOf('/') + 1).split('.');
if(extension[1]&&['jpeg','jpg','gif','png'].indexOf(extension[1]) > -1){
return _apiUrl + '/api/v1/chat-file-download?file=' +result.file_path.replace(/ /g, "/");
}else{
return _apiUrl + '/public/assets/images/file.png';
}
return '';
},
sendFile: function (formElement) {
var that =this;
var formData = new FormData();
// var curentTime = new Date();
formData.append('uploadFile', document.getElementsByName('msg_file_cb')[0].files[0]);
formData.append('sender', _args[3]);
formData.append('to', _CBOX_agentID);
var xhr = new XMLHttpRequest();
xhr.open("post", _apiUrl + "/api/v1/chat-file-message");
xhr.send(formData);
xhr.onreadystatechange = function () {
if (this.readyState == 4 && (this.status == 200 || this.status == 201)) {
var result = JSON.parse(this.responseText).data;
result['sender_name'] = _name||_args[3];
console.log(result);
socket.emit('send-msgtoagent', {data: result, website_id: website_id});
if (result.file_path) {
// console.log(result.file_path.slice(result.file_path.lastIndexOf('/'))
var messageBox = `
|
`+ that.getCurrentDate() +` |
`;
}
//if message send from child window
window.opener&&window.opener.postMessage(JSON.stringify({message_data:result,sender:'none',host:'overlay'}),'*');
//if message send from paretn windpw
overlay&&overlay.postMessage(JSON.stringify({message_data:result,sender:'none',host:'overlay'}),'*');
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
var data1 = document.getElementsByClassName('cb-chatPanel')[0].innerHTML;
window.sessionStorage.setItem('CBOX_MSG', data1);
var CBOX_element = document.getElementsByClassName('cb-chatPanel')[0];
CBOX_element.scrollTop = CBOX_element.scrollHeight - CBOX_element.clientHeight;
}
}
},
//function to skip the prechatform if agent choose
skipChatForm: function (agentname, messageBox) {
_args[2] = 'start_chat';
// open =true;
var xhttp3 = new XMLHttpRequest();
xhttp3.open("get", _apiUrl + "/widget-template?param=" + _args + "&timezone=" + userTimezone + "&day=" + userDay + "&userTime=" + userTime+"&host="+location.host, true);
if(!document.getElementsByClassName("cb-chat_log")[0]){
xhttp3.send();
}else{
// if(agentname !='bot'&&agentname !='system'){
// document.getElementById("onlineAgent").innerHTML = agentname;
// }
document.getElementsByClassName("cb-maximized-chat")[0].style.display='none';
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
that.scrollBottom();
}
console.log('skipChatForm');
var that =this;
xhttp3.onreadystatechange = function () {
if (this.readyState == 4 && (this.status == 200 || this.status == 201)) {
// console.log(messageBox);
// document.getElementsByTagName('body')[0].innerHTML += this.responseText;
window.document.body.insertAdjacentHTML( 'afterbegin', this.responseText );
// if( document.getElementsByClassName("cb-chat_log")){
document.getElementsByClassName("cb-maximized-chat")[0].style.display='none';
setTimeout(function(){
// if(agentname !='bot'&&agentname !='system'){
// document.getElementById("onlineAgent").innerHTML = agentname;
// }
// document.getElementById("onlineAgent").innerHTML = agentname;
document.getElementsByClassName("cb-maximized-chat")[0].style.display='none';
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
},500)
// }
that.scrollBottom();
// console.log(document.getElementsByClassName("cb-chat_log")[0].innerHTML);
// var CBOX_element = document.getElementsByClassName('cb-chatPanel')[0];
// CBOX_element.scrollTop = CBOX_element.scrollHeight - CBOX_element.clientHeight;
// var data1 = document.getElementsByClassName('cb-chatPanel')[0].innerHTML;
// window.sessionStorage.setItem('CBOX_MSG', data1);
}
}
var asignArg = Object.assign({}, _args);
delete asignArg[4];
window.sessionStorage.setItem('CBOX_ITEM', JSON.stringify(asignArg));
},
makeid: function () {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
},
CBOX_form: function (event) {
if (event.keyCode == 13) {
if (event.shiftKey) {
event.stopPropagation();
} else if (event.target.value) {
if (event.target.value.trim() !== '') {
this.chatBoxsendMsg(event.target.value.trim());
console.log(event.srcElement.classList[2]);
if(event.srcElement.classList[2] && event.srcElement.classList[2] == 'minimize_message')
{
document.getElementById("CBOX_minimize_form").reset();
this.minimize();
}
document.getElementById("CBOX_form").reset();
}
}
}else{
var data = {
'message': event.target.value,
'sender_id': _args[3],
'sender_name': _args[3],
'receiver_id': _CBOX_agentID,
'room_name':_args[3]
};
socket.emit('visitor-typing',{data:data,website_id:website_id});
}
return false;
},
chatBoxsendMsg: function (data = null) {
// var curentTime = new Date();
var input= document.querySelectorAll(".cb-CBOX_msg_name");
var that = this;
if(data !=null){
input[0].value = that.urlify(data);
// input[0].value = data;
}else{
input[0].value = that.urlify(input[0].value);
}
if (!(input[0].value.trim())) {
return false;
}
var element = document.getElementsByClassName('cb-predefine-intent-box');
element&&element[0]&&element[0].parentNode.removeChild(element[0]);
that.removeTyping();
var message = input[0].value;
var sender = _args[3];
var to = _CBOX_agentID;
if (!JSON.parse(window.sessionStorage.getItem('CBOX_USER'))) {
return false;
}
var websiteID = JSON.parse(window.sessionStorage.getItem('CBOX_USER')).website_id;
var messageBox = `
` + input[0].value + ` |
`+ that.getCurrentDate() +` |
`;
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
if(input[0].value.trim().toUpperCase()=='RESET'){
that.resetChat();
return false;
}
console.log(data);
console.log(input[0].value);
// ********************* Validation start ***************************************
var entity_validation=validation;
var inputedValue=input[0].value;
var validation_message='';
var entityValidation=true;
console.log(entity_validation);
if(entity_validation!=undefined && entity_validation!="undefined" && Object.keys(entity_validation).length > 0)
{
if(entity_validation.min == true)
{
if(inputedValue.length < entity_validation.min_value)
{
validation_message=entity_validation.min_msg;
entityValidation = false;
}
}
if(entity_validation.max == true && entityValidation!=false)
{
if(inputedValue.length > entity_validation.max_value)
{
validation_message=entity_validation.max_msg;
entityValidation = false;
}
}
if(entity_validation.pattern==true && entity_validation.pattern_msg!='' && entityValidation!=false)
{
if(inputedValue != entity_validation.pattern_value)
{
validation_message=entity_validation.pattern_msg;
entityValidation = false;
}
}
if(entity_validation.datetime == true && entityValidation!=false)
{
if(inputedValue < entity_validation.datetime_min_value || inputedValue > entity_validation.datetime_max_value)
{
validation_message=entity_validation.datetime_msg;
entityValidation = false;
}
}
if(entityValidation == false)
{
var messageBox = `
` + validation_message + ` |
`+ that.getCurrentDate() +` |
`;
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
if(botMessageData.entity_type=='datetime'){
that.addDateTime();
}
that.scrollBottom();
return false;
}
}
// ********************* Validation end ***************************************
var data = {
'message': input[0].value,
'sender': _args[3],
'to':_CBOX_agentID,
'webID': JSON.parse(window.sessionStorage.getItem('CBOX_USER')).website_id,
'room_name':_args[3]
}
//if message send from child window
window.opener&&window.opener.postMessage(JSON.stringify({message_data:data,sender:'none',host:'overlay'}),'*');
//if message send from paretn windpw
overlay&&overlay.postMessage(JSON.stringify({message_data:data,sender:'none',host:'overlay'}),'*');
var data1 = this.parseEncode(data);
var xhttp12 = new XMLHttpRequest();
xhttp12.open("POST", _apiUrl + "/api/v1/chat-message?" + data1, true);
xhttp12.send();
//message display in box
xhttp12.onreadystatechange = function () {
if (this.readyState == 4 && (this.status == 200 || this.status == 201)) {
var result = JSON.parse(this.responseText).data;
// result['sender_name'] = result['sender_name']||_args[3];
result['sender_name'] = _name||_args[3];
console.log(result);
var data1 = document.getElementsByClassName('cb-chatPanel')[0].innerHTML;
window.sessionStorage.setItem('CBOX_MSG', data1);
that.scrollBottom();
document.getElementById("CBOX_form").reset();
if(actionPerform !=null){
// actionPerform =null;
console.log(data['message']);
setTimeout(function(){
that.sendApiMessage(actionPerform,data['message']);
},1000);
return false;
}
var CBOX_websiteID = JSON.parse(window.sessionStorage.getItem('CBOX_USER')).website_id;
console.log(_CBOX_agentID);
if( !_CBOX_agentID){
//that.agentTyping();
if(_botName=='wit'){
//check if bot is activated
if(_bot_id){
//send message to bot if bot_id exists
socket.emit('bot_message', {bot_id:_bot_id,website_id:website_id,message:message,current_intent:_current_intent,visitor_id:_args[3]});
//et timer for get message form bot but not get then send to agent
that.setBotTimer();
}else{
if(!_chatbot_transfer){
_chatbot_transfer =true;
that.newVisitor();
}
// var CBOX_data = website_id + ':' + _args[3];
// socket.emit('new_visitor', {websiteData: _website_data,chatbotTransfer:true});
}
//when use tensor flow
}else{
_chatbot_transfer =true;
that.newVisitor();
// socket.emit('new_visitor', {websiteData: _website_data,chatbotTransfer:true});
}
}else{
console.log(_CBOX_agentID);
// socket.emit('new_visitor', {websiteData: CBOX_data});
socket.emit('send-msgtoagent', { data:result, website_id: website_id});
}
// socket.emit('send-msgtoagent', {data: result, website_id: website_id});
}
}
that.showWaitMsg();
that.resizeWindow();
},
//function call when api call from user message where api is assigned in chatbot intent
//if param yes then api waiting for input otherwise direct call api
sendApiMessage:function(action,data=null){
console.log(data);
var xhttp15 = new XMLHttpRequest();
if(data !=null){
var url = this.rtrim(action,'/')+'?data='+data;
}else{
var url = this.rtrim(action,'/');
}
var that =this;
xhttp15.open("get",url, true);
xhttp15.send();
xhttp15.onreadystatechange = function() {
that.removeTyping();
actionPerform =null;
if (this.readyState == 4 && (this.status == 200||this.status == 201)) {
console.log(this.responseText);
var messageBox = `
`+ that.getCurrentDate()+`
|
`+this.responseText+` |
`;
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
var xhttp16 = new XMLHttpRequest();
xhttp16.open("POST",_apiUrl+"/api/v1/system-message", true);
xhttp16.setRequestHeader("Content-Type", "application/json");
xhttp16.send(JSON.stringify({message:this.responseText,userid:_args[3],website_id:website_id}));
xhttp16.onreadystatechange = function() {
if (this.readyState == 4 && (this.status == 200||this.status == 201)) {
console.log(this.responseText);
that.scrollBottom();
}
}
that.scrollBottom();
}
}
return false;
},
rtrim:function(str, chr) {
var rgxtrim = (!chr) ? new RegExp('\\s+$') : new RegExp(chr+'+$');
return str.replace(rgxtrim, '');
},
//use for slide left in carousal slider
nextSlide:function(key,n) {
this.displaySlides(key,slide_index[key] += n);
},
//use for slide Right in carousal slider
currentSlide:function(key,n) {
this.displaySlides(key,slide_index[key] = n);
},
//show carousal slider
displayAllSlides:function(n) {
var i;
var slider = document.querySelectorAll('.cb-slidercontainer');
if(slider.length >0){
for(item in slider){
if( slider[item].id){
var key = slider[item].id.split('_')[0];
console.log(key);
slide_index[key] =1;
var slides = document.getElementsByClassName(key+'_cb-showSlide');
if (n > slides.length) { slide_index[key] = 1 }
if (n < 1) { slide_index[key] = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slide_index[key] -1].style.display = "block";
}
}
}
},
//show carousal slider
displaySlides:function(key,n) {
var i;
slide_index[key] =n;
var slides = document.getElementsByClassName(key+'_cb-showSlide');
console.log(slides);
if (n > slides.length) { slide_index[key] = 1 }
if (n < 1) { slide_index[key] = slides.length }
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
console.log(key);
console.log(slide_index[key]);
slides[slide_index[key] -1].style.display = "block";
},
//this is test
helloWorld: function () {
console.log('Hello World! -' + _args[0]);
},
tonggleHeader: function () {
if (open) {
open = false;
document.getElementsByClassName('cb-chatinbox_body')[0].style.display = 'none';
document.getElementsByClassName('cb-chatinbox_text_box')[0].style.display = 'none';
} else {
open = true;
document.getElementsByClassName('cb-chatinbox_body')[0].style.display = '';
document.getElementsByClassName('cb-chatinbox_text_box')[0].style.display = '';
}
},
urlify:function(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url) {
return '' + url + '';
})
// or alternatively
// return text.replace(urlRegex, '$1')
},
close:function(overlay=null){
console.log('happy ending');
var messageBox ="";
var messageBoxRating ="";
var confirmMs = "Are you sure you want to end the conversation";
var ratingConfMsg = "Do you want to provide feedback?";
var eleman = document.getElementById('cb_close_chat');
eleman.setAttribute("disabled", true);
if(arebicWebsiteIds.indexOf(_website_id)> -1){
confirmMs = 'هل انت متأكد من انك تريد انهاء المحادثة';
ratingConfMsg = 'هل تريد تقديم ملاحظات؟';
messageBox = `
هل تريد انهاء المحادثة
|
`;
messageBoxRating = `
هل تريد المشاركة في تقييم المحادثة
|
`;
}
else {
messageBox = `
Are you sure you want to end the conversation?
|
`;
messageBoxRating = `
Do you want to provide feedback?
|
`;
}
// if (overlay == null && !confirm(confirmMs)) {
// return false;
// }
var myDiv = document.getElementById("cbChatPanel");
myDiv.scrollTop = myDiv.scrollHeight;
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
document.getElementById('id_confrmdiv').style.display = 'block';
document.getElementById('id_confrmdiv').scrollIntoView();
var that = this;
document.getElementById('id_falsebtn').onclick = function(){
//alert('false');
var eleman = document.getElementById('cb_close_chat');
eleman.removeAttribute("disabled");
document.getElementById('id_confrmdiv').style.display = 'none';
var elem = document.getElementById('id_confrmdiv');
if(elem){
elem.parentNode.removeChild(elem);
}
return false;
};
document.getElementById('id_truebtn').onclick = function(){
// if(!confirm(ratingConfMsg)){
// that.closeWidget();
// }
document.getElementById('id_confrmdiv').style.display = 'none';
var elem = document.getElementById('id_confrmdiv');
if(elem){
elem.parentNode.removeChild(elem);
}
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBoxRating;
document.getElementById('id_confrmdivrating').style.display = 'block';
document.getElementById('id_falsebtnrating').onclick = function(){
//alert('false');
document.getElementById('id_confrmdivrating').style.display = 'none';
var elem = document.getElementById('id_confrmdivrating');
if(elem){
elem.parentNode.removeChild(elem);
}
that.closeWidget();
return false;
};
document.getElementById('id_truebtnrating').onclick = function(){
_closeChat = true;
that.endWidget();
window.sessionStorage.removeItem("CBOX_MSG");
window.sessionStorage.removeItem("CBOX_ITEM");
window.sessionStorage.removeItem("CBOX_USER");
window.sessionStorage.removeItem("CBOX_agentID");
window.sessionStorage.removeItem("CBOX_agent_name");
};//end of true of rating
};
},
//close widget
closeWidget: function (overlay = null) {
document.getElementsByClassName('cb-maximized-chat')[0].style.display = 'none';
if (document.getElementsByClassName('cb-maximized-chat')[1]) {
document.getElementsByClassName('cb-maximized-chat')[1].style.display = 'none';
}
console.log('Thanks For Chatting Through CHATINBOX');
!window.opener&&socket.emit('visitor-left', {websiteData: _website_data});
window.sessionStorage.removeItem("CBOX_MSG");
window.sessionStorage.removeItem("CBOX_ITEM");
window.sessionStorage.removeItem("CBOX_USER");
window.sessionStorage.removeItem("CBOX_agentID");
window.sessionStorage.removeItem("CBOX_agent_name");
console.log('_args',_args);
if(overlay||_args[4]=='overlay'){
location.reload();
}
document.getElementsByClassName('cb-minimize-chat')[0].style.display = 'none';
_CBOX_agentID = null;
_CBOX_agent_name = null;
var that =this;
setTimeout(function(){
var data = document.getElementsByClassName("cb-support-chat");
for(item in data){
try{
data[item].parentNode.removeChild(data[item]);
}catch(err){}
}
var data = document.getElementsByClassName("cb-support-chat-login");
for(item in data){
try{
data[item].parentNode.removeChild(data[item]);
}catch(err){}
}
_closeChat=false;
session ={};
_name =null;
_bot_id =null;
_website_data =null;
_website_id=null;
_department_id=null;
_chatbot_transfer=null;
slide_index ={};
_show_time =false;
_agent_status ='online';
_userInfo={};
_agentTransfer=null;
validation={};
botMessageData={};
website_id = null;
agentname = null;
visitor_id = null;
_args.splice(2,2);
console.log(_args);
that.init(_args);
},1000);
},
//open window for chat
overlay: function () {
_args[4] = 'overlay';
_args[5] = _CBOX_agentID;
_args[6] = _current_intent;
// console.log(_args);
// window.sessionStorage.setItem('CBOX_ITEM',JSON.stringify(_args));
//hide maximize window
if (document.getElementsByClassName('cb-maximized-chat')[0])
document.getElementsByClassName('cb-maximized-chat')[0].style.display = 'none';
if (document.getElementsByClassName('cb-minimize-chat')[0])
document.getElementsByClassName('cb-minimize-chat')[0].style.display = '';
if(!overlay){
overlay = window.open(_apiUrl + '/overlay-widget?param=' + _args, '', 'width = 340, height = 540');
}else{
overlay.close();
overlay = null;
}
console.log(overlay);
// this.close(true);
// var elem = document.getElementsByClassName('maximized-chat')[0];
// elem.parentNode.removeChild(elem);
// document.getElementsByClassName('maximized-chat')[0].style.display='none';
},
overlayClose: function () {
_args[4] = '';
window.close();
},
//maximize and minimize widget
minimize: function () {
console.log('args',_args);
console.log('overlay',overlay);
if(overlay||_args[4]=='overlay'){
location.reload();
}
if (open) {
open = false;
if(document.getElementsByClassName('cb-maximized-chat')[0])
document.getElementsByClassName('cb-maximized-chat')[0].style.display = 'none';
if(document.getElementsByClassName('cb-minimize-chat')[0])
document.getElementsByClassName('cb-minimize-chat')[0].style.display = '';
} else {
open = true;
if(document.getElementsByClassName('cb-maximized-chat')[0])
document.getElementsByClassName('cb-maximized-chat')[0].style.display = '';
if(document.getElementsByClassName('cb-minimize-chat')[0])
document.getElementsByClassName('cb-minimize-chat')[0].style.display = 'none';
document.getElementsByClassName("small_chat_popup")[0].style.display='none';
document.getElementById("preMessage").innerHTML = '';
this.scrollBottom();
}
},
//load widget
loadChatForm: function () {
console.log(_args);
var that =this;
//called after get visitor info
console.log('called after get visitor info');
var xhttp1 = new XMLHttpRequest();
xhttp1.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
window.document.body.insertAdjacentHTML( 'afterbegin', this.responseText );
that.displayAllSlides(1);
// document.getElementsByTagName('body')[0].innerHTMagaL += this.responseText;
if (_args[4] && _args[4] == 'overlay') {
if (document.getElementsByClassName('cb-maximized-chat')[0])
document.getElementsByClassName('cb-maximized-chat')[0].style.display = '';
if (document.getElementsByClassName('cb-minimize-chat')[0])
document.getElementsByClassName('cb-minimize-chat')[0].style.display = 'none';
}
if (_args[2] == 'start_chat') {
if(document.getElementsByClassName('cb-minimize-chat')[0])
document.getElementsByClassName('cb-minimize-chat')[0].style.display = 'none';
}
}
};
//_args['userTimezone']=userTimezone;
// console.log("console--- /chatbox/widget-template?param="+_args+"&template=minimize&timezone="+userTimezone+"&day="+userDay+"&userTime="+userTime);
if(_args[4] && _args[4] == 'overlay'){
xhttp1.open("GET", _apiUrl + "/widget-template?param=" + _args + "&template=maximize&timezone=" + userTimezone + "&day=" + userDay + "&userTime=" + userTime+"&host="+location.host, true);
if(document.getElementsByClassName('cb-CBOX-form')[0]){
document.getElementsByClassName('cb-CBOX-form')[0].style.maxHeight = window.innerHeight-230 +'px';
}
}else{
xhttp1.open("GET", _apiUrl + "/widget-template?param=" + _args + "&template=minimize&timezone=" + userTimezone + "&day=" + userDay + "&userTime=" + userTime+"&host="+location.host, true);
}
xhttp1.send();
that.showOfflineForm();
},
//check form is valid or not
checkFormValidity:function(){
var formValidity = true;
var arrayData = {};
var input = document.querySelectorAll("form[name=chatbox_form] input,textarea,select");
console.log("///////////////////////////////////////////////////");
console.log(input);
//validation
for (var i = 0; i < input.length; i++)
{
if (input[i].type == 'checkbox') {
var checkedValue = '';
var inputElements = document.getElementsByName(input[i].name);
console.log(document.getElementsByName(input[i].name));
console.log(inputElements);
for (var j = 0; inputElements[j]; ++j) {
if (inputElements[j].checked) {
checkedValue += inputElements[j].value + ',';
}
}
arrayData[input[i].getAttribute('name')] = checkedValue;
} else if(input[i].type == 'radio'){
if(input[i].checked){
arrayData[input[i].getAttribute('name')] = input[i].value;
}
} else{
arrayData[input[i].getAttribute('name')] = input[i].value;
}
var elem = input[i].parentNode.getElementsByClassName('cb-validation_messsage');
if (elem.length != 0) {
elem[0].parentNode.removeChild(elem[0]);
}
var validationMs ="This field is required";
if(arebicWebsiteIds.indexOf(_website_id)> -1){
validationMs = 'هذا الحقل مطلوب';
}
if(input[i].name=='add_name' && input[i].validity.patternMismatch) {
var validationMs ="Please enter in valid format";
if(arebicWebsiteIds.indexOf(_website_id)> -1){
validationMs = 'الرجاء إدخال في شكل صحيح';
}
input[i].parentNode.innerHTML += ''+validationMs+'';
formValidity = false;
}else if(input[i].name=='add_email' && input[i].validity.patternMismatch) {
var validationMs ="Please enter in valid format";
if(arebicWebsiteIds.indexOf(_website_id)> -1){
// validationMs = ﺟﺍﺀ ﺇﺪﺧﺎﻟ ﻒﻳ ﺶﻜﻟ ﺺﺤﻴﺣ';
validationMs = "الرجاء إدخال في شكل صحيح";
}
input[i].parentNode.innerHTML += ''+validationMs+'';
formValidity = false;
} else if(input[i].name=='add_phone_number' && input[i].validity.patternMismatch){
var validationMs ="Please enter in valid format";
if(arebicWebsiteIds.indexOf(_website_id)> -1){
validationMs = 'الرجاء إدخال في شكل صحيح';
}
input[i].parentNode.innerHTML += ''+validationMs+'';
formValidity = false;
} else {
if (!input[i].checkValidity() ) {
console.log(input[i]);
input[i].parentNode.innerHTML += ''+validationMs+'';
formValidity = false;
}
}
}
// return false;
if (formValidity == false) {
return false;
}
return arrayData;
},
changeDepartment:function(){
if (document.getElementsByName('add_department')[0]) {
var CBOX_departmentVal = document.getElementsByName('add_department')[0].options[document.getElementsByName('add_department')[0].selectedIndex].innerHTML;
var CBOX_departmentID = document.getElementsByName("add_department")[0].value;
var CBOX_websiteID = JSON.parse(window.sessionStorage.getItem('CBOX_USER')).website_id;
// var CBOX_data = CBOX_websiteID + ':' + _args[3];
console.log('Department Stored');
window.sessionStorage.setItem('CBOX_DEP', CBOX_departmentID);
socket.emit('visitorDepartment', {visitorDepartment: CBOX_departmentVal, id: _website_data, department: CBOX_departmentID});
}
},
//load widget for when chat start
startChat: function (status = null) {
var arrayData = false;
var that =this;
arrayData = this.checkFormValidity();
if(!arrayData){
return false;
}
if(status){
arrayData['status'] = status;
}
// console.log(arrayData);return false;
//after validation emit the department id to agent
console.log('1a');
//if customer department select then agent department change event found
this.changeDepartment();
//end validation code
var elem = document.getElementsByClassName('cb-support-chat-login')[0];
if (status != 'agent_offline') {
elem.parentNode.removeChild(elem);
}
var xhttp2 = new XMLHttpRequest();
_args[2] = 'start_chat';
// console.log(_args[2]);
var asignArg = Object.assign({}, _args);
delete asignArg[4];
window.sessionStorage.setItem('CBOX_ITEM', JSON.stringify(asignArg));
window.opener&&window.opener.postMessage(JSON.stringify({start_chat:true,data:asignArg}),'*')
overlay&&overlay.postMessage(JSON.stringify({start_chat:true,data:asignArg}),'*')
// window.sessionStorage.setItem('CBOX_ITEM',JSON.stringify(_args));
xhttp2.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 201) {
try{
_name = JSON.parse(this.responseText).data.name||_args[3];
}catch(err){
console.log(err);
}
// var CBOX_websiteID= JSON.parse(window.sessionStorage.getItem('CBOX_USER')).website_id;
// var CBOX_websiteID= website_id;
// var CBOX_data = website_id + ':' + _args[3];
// console.log(CBOX_data);
// setTimeout(function(){
socket.emit('request_for_chat', {websiteData: _website_data});
//},2000);
if (status == 'agent_offline') {
_args[1] = 'agent_offline';
console.log('Thanks For Chatting Through CHATINBOX');
document.getElementById('offline_thanks').style.display = 'block';
document.getElementsByClassName('cb-support-account-login')[0].style.display = 'none';
// document.getElementsByClassName('support-account-login')[0].innerHTML ='Thanks For Contacting Us We will get back to you shortly
';
socket.emit('visitor-left', {websiteData: _website_data});
window.sessionStorage.removeItem("CBOX_MSG");
window.sessionStorage.removeItem("CBOX_ITEM");
window.sessionStorage.removeItem("CBOX_USER");
return false;
} else {
that.getWidgetTempalate();
}
}
};
//set data post param
arrayData['widget_id'] = _args[0];
if (_args[3] != null)
arrayData['user_id'] = _args[3];
arrayData['page_title'] = document.title;
var params = this.parseEncode(arrayData);
//end of post param code
xhttp2.open("POST", _apiUrl + "/widget-data?" + params, true);
xhttp2.send();
return false;
},
//get widget template
getWidgetTempalate:function(){
var xhttp = new XMLHttpRequest();
xhttp.open("get", _apiUrl + "/widget-template?param=" + _args + "&timezone=" + userTimezone + "&day=" + userDay + "&userTime=" + userTime+"&host="+location.host, true);
xhttp.send();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && (this.status == 200 || this.status == 201)) {
window.document.body.insertAdjacentHTML( 'afterbegin', this.responseText );
// document.getElementsByTagName('body')[0].innerHTML += this.responseText;
}
}
},
srollInBox:function(){
if(document.querySelector("form[name=chatbox_form]")&&parseInt(document.querySelector("form[name=chatbox_form]").scrollHeight) > document.getElementsByClassName("cb-CBOX-form")[0].clientHeight+10){
document.querySelector("form[name=chatbox_form]").style.overflowY = 'scroll';
}
},
updatePage:function(){
var pathWithParameter=encodeURIComponent("page="+window.location.href + "&widget_id="+_args[0]+"&visitor_id=" + _args[3]+"&page_title="+document.title);
// if(JSON.parse(window.sessionStorage.getItem('CBOX_USER'))){
var xhttp41 = new XMLHttpRequest();
xhttp41.open("get",_apiUrl+"/customer-page?parameter="+pathWithParameter , true);
xhttp41.send();
xhttp41.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText).data;
if(response.message)
{
document.getElementsByClassName('cb_welcome-message')[0].innerHTML=response.message;
document.getElementsByClassName('cb_welcome-message')[1].innerHTML=response.message;
}
socket.emit('visitor_visit', {visitorPage: window.location.href, id: _website_id+':'+ _args[3]});
}
}
// }
},
//get client info for store user-analitics data
getclientInfo: function (id = null) {
console.log('getclientInfo first');
var data = {};
var that = this;
/* navigator.geolocation.getCurrentPosition(function (position) {
// console.log(position);
if (position) {
data['latitude'] = position.coords.latitude;
data['longitude'] = position.coords.longitude;
}
});*/
data['userTimezone'] = userTimezone;
data['widget_id'] = _args[0];
data['page'] = location.href;
data['page_title'] = document.title;
if (id != null)
data['user_id'] = id;
data['ip'] = '';
var that = this;
// data['ip']='192.168.1.25';
var xhttp4 = new XMLHttpRequest();
xhttp4.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 201) {
var CBOX_Page = window.location.href;
var page_title = document.title;
var CBOX_visitorID = JSON.parse(this.responseText).data.id;
website_id = JSON.parse(this.responseText).data.website_id;
_website_id = website_id;
_args[3] = visitor_id = CBOX_visitorID;
_bot_id = JSON.parse(this.responseText).data.bot_id;
//update new page view
that.updatePage();
// _website_data = CBOX_websiteID + ':' + response.data2;
try { console.log("check end status visitor");
var data_x = JSON.parse(this.responseText).data;
console.log("chat_ended",data_x);
if(data_x.chat_ended==1){
setTimeout(function(){
console.log("runner",data_x.chat_ended);
// document.getElementById("id_truebtn").click();
var footer =document.getElementsByClassName('cb-support-chat-footer');
for (var i = 0; i < footer.length; i++) {
footer[i].style.display='none';
}
// $('.cb-ctrl-btn').hide();
},20);
}
} catch (e) {
console.log("check status error",e);
}
_userInfo = JSON.parse(this.responseText).data;
_CBOX_agentID = _userInfo.attended_by;
if(!_bot_id&&_userInfo.online_agents ==0){
// that.showOfflineForm(true);
}
//set pre intents display in chatpanel
that.addPreIntent(JSON.parse(this.responseText).data.pre_intents);
console.log(JSON.parse(this.responseText));
console.log(_args[3], website_id);
var resulta = JSON.parse(this.responseText).data.sound_notification;
if (resulta == 0) {
if (document.getElementsByClassName('cb-cbox_mute')[0])
document.getElementsByClassName('cb-cbox_mute')[0].style.display = '';
if (document.getElementsByClassName('cb-cbox_unmute')[0])
document.getElementsByClassName('cb-cbox_unmute')[0].style.display = 'none';
} else {
if (document.getElementsByClassName('cb-cbox_mute')[0])
document.getElementsByClassName('cb-cbox_mute')[0].style.display = 'none';
if (document.getElementsByClassName('cb-cbox_unmute')[0])
document.getElementsByClassName('cb-cbox_unmute')[0].style.display = '';
}
if (_args[4] != 'overlay' && JSON.parse(this.responseText).data.widget_type == 'overlay_window') {
that.overlay();
}
// if (JSON.parse(this.responseText).data.chat_ratiing == 'good') {
// if (document.querySelector('.cb-good_rating svg'))
// document.querySelector('.cb-good_rating svg').setAttribute('fill', 'blue');
// } else if(JSON.parse(this.responseText).data.chat_ratiing == 'bad'){
// if (document.querySelector('.cb-bad_rating svg'))
// document.querySelector('.cb-bad_rating svg').setAttribute('fill', 'blue');
// }
if (JSON.parse(this.responseText).data.bannedstatus == 'true') {
document.getElementsByClassName('cb-maximized-chat')[0].style.display = 'none';
if (document.getElementsByClassName('cb-maximized-chat')[1]) {
document.getElementsByClassName('cb-maximized-chat')[1].style.display = 'none';
}
document.getElementsByClassName('cb-minimize-chat')[0].style.display = 'none';
if (JSON.parse(window.sessionStorage.getItem('CBOX_USER'))) {
var CBOX_websiteID = JSON.parse(window.sessionStorage.getItem('CBOX_USER')).website_id;
_website_data = CBOX_websiteID + ':' + _args[3];
}
console.log('Thanks For Chatting Through CHATINBOX');
socket.emit('visitor-left', {websiteData: _website_data});
socket.destroy();
window.sessionStorage.removeItem("CBOX_MSG");
window.sessionStorage.removeItem("CBOX_ITEM");
window.sessionStorage.removeItem("CBOX_USER");
console.log('Your IP is Blocked.');
return false;
}
// console.log( JSON.parse(this.responseText));
_args[3] = JSON.parse(this.responseText).data.id;
console.log('customer_id',id);
if(id !=null && id != _args[3] ){
_closeChat = true;
that.closeWidget(_args[4] == 'overlay');
return ;
}
var asignArg = Object.assign({}, _args);
delete asignArg[4];
window.sessionStorage.setItem('CBOX_ITEM', JSON.stringify(asignArg));
// window.sessionStorage.setItem('CBOX_ITEM',JSON.stringify(_args));
window.sessionStorage.setItem('CBOX_USER', JSON.stringify(JSON.parse(this.responseText).data));
console.log('----------get id as below---------------');
// console.log( _args[3].id);
var CBOX_websiteID = JSON.parse(this.responseText).data.website_id;
// var CBOX_data = CBOX_websiteID + ':' + _args[3];
_website_data = CBOX_websiteID + ':' + _args[3];
console.log('Emitting Request To Socket-Server', _website_data);
if (JSON.parse(window.sessionStorage.getItem('CBOX_DEP'))) {
console.log('dep is there');
_department_id = JSON.parse(window.sessionStorage.getItem('CBOX_DEP'));
// socket.emit('new_visitor', {websiteData: CBOX_data,department:CBOX_dep});
// socket.emit('new_visitor', {websiteData: _website_data, department: CBOX_dep,bot_id:_bot_id});
that.newVisitor();
}else{
console.log('not found dep');
socket = io.connect('https://ccchat.iacad.gov.ae:8888');
// that.newVisitor();
//list on event
that.socketConnection();
// socket.emit('new_visitor', {websiteData: _website_data,bot_id:_bot_id});
}
}
}
var params = that.parseEncode(data);
xhttp4.open("POST", _apiUrl + "/widget-data?" + params, true);
xhttp4.send();
},
//emit new visitor request
newVisitor:function(){
socket.emit('new_visitor', {websiteData: _website_data,bot_id:_bot_id,department:_department_id,chatbotTransfer:_chatbot_transfer});
},
parseEncode: function (arrayData) {
return typeof arrayData == 'string' ? arrayData : Object.keys(arrayData).map(
function (k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(arrayData[k])
}
).join('&');
},
rating: function (rat, event) {
console.log("rating method called >>> ");
console.log(rat);
document.getElementsByClassName('cb-feedback')[0].style.display = 'none';
// if (rat == 'good') {
// document.querySelector('.cb-good_rating svg').setAttribute('fill', 'blue');
// document.querySelector('.cb-bad_rating svg').setAttribute('fill', '#515151');
// } else {
// document.querySelector('.cb-good_rating svg').setAttribute('fill', '#515151');
// document.querySelector('.cb-bad_rating svg').setAttribute('fill', 'blue');
// }
var data = [];
data['visitor_id'] = visitor_id;
data['rating'] = rat;
data['website_id'] = website_id;
data['agent_id'] = _CBOX_agentID;
var xhttp = new XMLHttpRequest();
var params = this.parseEncode(data);
console.log(params);
xhttp.open("POST", _apiUrl + "/update-rating?" + params, true);
xhttp.send();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var messageBox = `
Added ` + rat + ` stars rating |
`;
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
window.opener&&window.opener.postMessage(JSON.stringify({rating:rat,data:messageBox}),'*');
overlay&&overlay.postMessage(JSON.stringify({rating:rat,data:messageBox}),'*');
var result = JSON.parse(this.responseText).data;
result['sender_name'] = result['sender_name']||_args[3];
socket.emit('send-msgtoagent', {data: result, website_id: website_id});
}
}
if(_closeChat){
this.closeWidget();
}
},
clickOnLink:function(that,text=null){
console.log(that.text);
if(text!=null){
this.chatBoxsendMsg(text) ;
}else{
this.chatBoxsendMsg(that.text);
}
},
getCurrentDate:function(){
var hour = new Date().getHours();
var minute = new Date().getMinutes();
var time = 'AM';
if(hour >= 12){
hour = hour -12;
time = 'PM';
}
if(hour < 10){
hour = '0'+hour ;
// time = 'PM';
}
if(hour == '0'){
hour = 12;
time = 'AM';
}
if(minute < 10){
minute = '0'+minute;
}
if(hour =='00' && time == 'PM'){
hour = 12;
}
return hour+':'+ minute+' '+time;
},
scrollBottom:function(){
var CBOX_element = document.getElementsByClassName('cb-chatPanel')[0];
if(CBOX_element){
console.log(CBOX_element);
CBOX_element.scrollTop = CBOX_element.scrollHeight - CBOX_element.clientHeight;
}
},
startVideo:function(that){
if(document.getElementsByClassName('cb-video-box')[0].style.display == ''){
document.getElementsByClassName('cb-video-box')[0].style.display = 'none'
}else{
document.getElementsByClassName('cb-video-box')[0].style.display = '';
}
// if(ua ==null){
var options = {
'mediaConstraints': {'audio': true,'video':true},
'pcConfig': {'iceServers': [{'urls': ['stun:stun.l.google.com:19302', 'stun:stun.l.google.com:19302']}]}
};
ua.call('sip:1004@chatinbox.io', options);
// }
},
endCall:function(){
document.getElementsByClassName('cb-video-box')[0].style.display = 'none';
session.terminate();
},
muteCall:function(){
session.mute();
},
extractScreen:function(){
var video = document.getElementById('cb-video');
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen(); // Firefox
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen(); // Chrome and Safari
}
},
acceptCall:function(){
var options = {
'mediaConstraints': {'audio': true,'video':true},
'pcConfig': {'iceServers': [{'urls': ['stun:stun.l.google.com:19302', 'stun:stun.l.google.com:19302']}]}
};
document.getElementsByClassName('cb-video-box')[0].style.display = '';
session.answer(options);
},
appendMessage:function(data){
var that = this;
console.log(data);
// console.log(data.message.data.message);
if(data.message_data&&data.host =='overlay'){
if(data.sender =='none'){
if (data.message_data.file_path) {
var messageBox = `
`+ that.getCurrentDate() +`
|
|
`;
}else{
var messageBox = `
` + data.message_data.message + ` |
`+ this.getCurrentDate() +`
|
`;
}
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
}
}else if(data.message){
// console.log(data.message.data.message);
audio = new Audio(_apiUrl + '/public/notificationAudio.mp3');
if (document.getElementsByClassName('cb-cbox_mute')[0] && document.getElementsByClassName('cb-cbox_mute')[0].style.display == 'none') {
audio.play();
}
var elem = document.getElementsByClassName('cb-support-chat-login')[0];
if (_args[2] != 'start_chat' && elem) {
elem.parentNode.removeChild(elem);
}
that.removeTyping();
var agentname = data.message.data.agentName||data.message.data.sender_name;
// window.sessionStorage.setItem('CBOX_agentID', data.message.data.agentID||data.message.data.sender_id);
// _CBOX_agentID = data.message.data.agentID||data.message.data.sender_id;
// var agentname = data.message.data.sender_name;
// window.sessionStorage.setItem('CBOX_agentID', data.message.data.sender_id);
// var curentTime = new Date();
//console.log(agentname);
if (data.message.data.message) {
var messageBox = `
`+ that.getCurrentDate()+`
|
` + data.message.data.message + ` |
`;
} else if (data.message.data.file_path) {
//console.log(data.message.data.file_path.slice(data.message.data.file_path.lastIndexOf('/')+1));
var messageBox = `
`+ that.getCurrentDate() +`
|
|
`;
}
if (document.getElementsByClassName('cb-support-chat cb-maximized-chat').length == 0) {
console.log(agentname);
// setTimeout(function(){
if(agentname !='system'){
that.skipChatForm(agentname, messageBox);
}
// },1000);
} else {
// console.log(open);
// if(!open){
// document.getElementsByClassName('cb-support-chat cb-minimize-chat')[0].style.display = 'none';
// document.getElementsByClassName('cb-support-chat cb-maximized-chat')[0].style.display = 'block';
// open =true;
// }else{
// document.getElementsByClassName('cb-support-chat cb-maximized-chat')[0].style.display = 'block';
// open =true;
// }
// console.log(messageBox);
if(agentname !='system'){
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
that.scrollBottom();
}
else
{
document.getElementsByClassName("cb_welcome-message")[0].innerHTML=data.message.data.message;
document.getElementsByClassName('cb_welcome-message')[1].innerHTML=data.message.data.message;
document.getElementsByClassName("small_chat_popup")[0].style.display='block';
that.scrollBottom();
}
// var CBOX_element = document.getElementsByClassName('cb-chatPanel')[0];
// CBOX_element.scrollTop = CBOX_element.scrollHeight - CBOX_element.clientHeight;
// var data1 = document.getElementsByClassName('cb-chatPanel')[0].innerHTML;
// window.sessionStorage.setItem('CBOX_MSG', data1);
// if (agentname && agentname !='system'&&agentname !='bot') {
// document.getElementById("onlineAgent").innerHTML = agentname;
// }
}
if(!open ){
let minMessage = `
`+data.message.data.message+` |
`;
document.getElementById("preMessage").innerHTML += minMessage;
// console.log()
}
} else if(data.start_chat){
window.sessionStorage.setItem('CBOX_ITEM', JSON.stringify(data.data));
window.location.reload();
} else if(data.rating){
// if (data.rating == 'good') {
// document.querySelector('.cb-good_rating svg').setAttribute('fill', 'blue');
// document.querySelector('.cb-bad_rating svg').setAttribute('fill', '#515151');
// } else {
// document.querySelector('.cb-good_rating svg').setAttribute('fill', '#515151');
// document.querySelector('.cb-bad_rating svg').setAttribute('fill', 'blue');
// }
document.getElementsByClassName("cb-chat_log")[0].innerHTML += data.data;
}
},
resizeWindow:function(){
console.log('window.outerHeight',window.outerHeight);
if(document.getElementsByClassName('cb-chatPanel')[0])
document.getElementsByClassName('cb-chatPanel')[0].style.height = window.innerHeight-120 +'px';
if(document.getElementsByClassName('cb-CBOX-form')[0] && _args[4] != 'overlay'){
document.getElementsByClassName('cb-CBOX-form')[0].style.maxHeight = window.innerHeight-230 +'px';
}
},
agentTyping:function(){
var messageBox = ``;
if(document.getElementsByClassName("cb-chat_log")[0]) document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
this.scrollBottom();
},
removeTyping:function(){
var elem = document.getElementById('cd-agent-typing');
if(elem){
elem.parentNode.removeChild(elem);
}
},
setBotTimer:function(){
that = this;
botResponseTimer = setTimeout(function(){
if(_userInfo.online_agents ==0){
that.showOfflineForm(true);
}else{
that.removeTyping();
_chatbot_transfer =true;
that.newVisitor()
// var CBOX_data = website_id + ':' + _args[3];
// socket.emit('new_visitor', {websiteData: _website_data,chatbotTransfer:true});
var messageBox = `
`+ that.getCurrentDate() +`
|
Sometimes, I may not have the information you need. Please wait for a while, I am connecting you to our live agent. |
`;
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
that.scrollBottom();
}
},botResponseTime*1000);
},
//set pre-intent boxes
addPreIntent:function(data){
console.log(data);
var that = this;
if(data.length >0){
var string='';
if(document.getElementsByClassName("cb-chat_log")[0]){
data.forEach(function(item){
console.log(item);
string+=``+item['name']+``;
})
document.getElementsByClassName("cb-predefine-intent-box")[0].innerHTML = string;
}else{
setTimeout(function(data){
// console.log('sdddddddddddd');
that.addPreIntent(data);
},1000,data)
}
}
},
botMessage:function(data){
botMessageData=data;
validation={};
var that =this;
console.log(data);
var key = new Date().getTime();
clearTimeout(botResponseTimer);
that.removeTyping();
// if(data.current_intent){
_current_intent = data.current_intent;
sessionStorage.setItem('current_intent',_current_intent);
// }
if(data.message_type=='text'||data.message_type=='error')
{
var messageBox = `
`+ that.getCurrentDate() +`
|
`+data.message+` |
`;
validation=data.validation;
}
else if(data.message_type=='suggestion'&&data.message.response)
{
var messageBox = `
`+ that.getCurrentDate() +`
|
`+data.message.response+` |
`;
data.message.option.forEach(function(item){
if(item&&item !=''){
messageBox += ``;
}
})
messageBox +=`
`;
}else if(data.message_type=='response_option'&&data.message.length>0){
var messageBox = ``;
data.message.forEach(function(item){
if(item&&item.name&&item.name !=''&&item.value&&item.value!=''){
messageBox += ``;
}
})
messageBox +=`
`;
}else if(data.message_type=='carousal')
{
var messageBox = `
|
`;
data.message.forEach(function(item){
messageBox += `
`+item.image_title+`
`
});
messageBox += `
|
`;
}
if(data.message_type=='error'||data.message_type =='chat_transfer'){
// var CBOX_data = website_id + ':' + _args[3];
// socket.emit('new_visitor', {websiteData: _website_data,chatbotTransfer:true});
if(_userInfo.online_agents ==0){
that.showOfflineForm(true);
}else{
_chatbot_transfer =true;
that.newVisitor();
}
}
if(data.message_type =='chat_end'){
that.endWidget();
}
if(data.message_type == 'get_rating'){
var lnPlsRate = "Please rate";
var lnGood = "Good";
var lnVGood = "Very Good";
var lnAvg = "Average";
var lnBad = "Bad";
var lnVBad = "Very Bad";
if(arebicWebsiteIds.indexOf(_website_id)> -1){
lnPlsRate = "يرجى تقييم";
lnGood = "ﺞﻳﺩ";
inVGood = "ﺞﻳﺩ ﺝﺩﺍً";
lnAvg = "ﻢﺣﺎﻳﺩ";
lnVBad = "ﺲﻴﺋ ﺝﺩﺍً";
lnBad = "ﺲﻴﺋ";
}
var messageBox='';
}
var delayTime=0;
if(data.intent_id)
{
var xhttp40=new XMLHttpRequest();
var param=this.parseEncode(data);
xhttp40.open("POST",_apiUrl + "/api/v1/intent/resposne-sec?"+param,false);
xhttp40.onreadystatechange = function(){
delayTime =this.responseText;
}
xhttp40.send();
}
setTimeout(function(){
if(messageBox && messageBox!=undefined)
{
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
}
if(data.entity_type=='datetime'){
that.addDateTime();
}
if(data.message_type=='carousal'){
this.displaySlides(key,1);
}
that.scrollBottom();
},delayTime*1000);
},
setRating:function(rating){
var xttp42=new XMLHttpRequest();
var param="rating="+rating+"&app_id="+_bot_id;
xttp42.open('POST',_apiUrl+'/api/v1/rating-update?'+param,true);
xttp42.send();
var elem = document.getElementById('get_rating');
if(elem){
elem.parentNode.removeChild(elem);
}
if(_closeChat){
this.closeWidget();
}
},
endWidget:function(){
console.log('end-widget');
this.removeTyping();
if (document.getElementsByClassName('cb-end-message')[0]){
document.getElementsByClassName('cb-end-message')[0].style.display = 'block';
document.getElementsByClassName('cb-feedback')[0].style.display = 'block';
}
var CBOX_element = document.getElementsByClassName('cb-chatPanel')[0];
if (CBOX_element)
CBOX_element.scrollTop = CBOX_element.scrollHeight - CBOX_element.clientHeight;
//var CBOX_websiteID = JSON.parse(window.sessionStorage.getItem('CBOX_USER')).website_id;
// var CBOX_data = CBOX_websiteID + ':' + _args[3]
console.log('Thanks For Chatting Through CHATINBOX');
window.sessionStorage.removeItem("CBOX_MSG");
window.sessionStorage.removeItem("CBOX_ITEM");
window.sessionStorage.removeItem("CBOX_USER");
window.sessionStorage.removeItem("current_intent");
window.sessionStorage.removeItem("CBOX_agentID");
// window.sessionStorage.clear();
// _args = [];
},
showTime:function(){
_show_time =true;
// console.log(that);
var ele = document.getElementsByClassName('cb-time-select');
document.getElementById('hideTimeBtn').style="display:table";
document.getElementById('showTimeBtn').style="display:none";
for(item in ele){
ele[item].style="display:inline-flex";
}
},
hideTime:function(){
_show_time =false;
// console.log(that);
var ele = document.getElementsByClassName('cb-time-select');
document.getElementById('hideTimeBtn').style="display:none";
document.getElementById('showTimeBtn').style="display:table";
for(item in ele){
ele[item].style="display:none";
}
},
addDateTime(){
console.log('addDateTime');
var today = new Date();
var dd = today.getDate()+1;
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
var chatWidget = document.getElementsByClassName("cb-chat_log")[0];
var html = `
Select Date
Select Time (IST)
`;
chatWidget.innerHTML += html;
console.log(html);
},
sendDate:function(){
let date = document.querySelector('input[name=cb_date]').value;
if(! new Date(date) instanceof Date){
return false;
}
if(_show_time){
var time = document.querySelector('select[name=cb_time_hour]').value+':'+document.querySelector('select[name=cb_time_minute]').value+':00';
if(document.querySelector('select[name=cb_time_hour]').value =='12')
{
time = document.querySelector('select[name=cb_time_hour]').value+':'+document.querySelector('select[name=cb_time_minute]').value+':00 PM';
}
this.chatBoxsendMsg(date+' '+time);
}else{
this.chatBoxsendMsg(date);
}
var elem = document.querySelector('.cb-date-dropdown-box');
if(elem){
elem.parentNode.removeChild(elem);
}
// console.log(document)
},
addVoice:function(){
if (!('webkitSpeechRecognition' in window)) {
alert('Browser does not support');
return false;
}
_voiceEnable = !_voiceEnable;
if(_voiceEnable){
this.startRecognition();
}else{
recognition.stop();
document.getElementById('cbMicro').style.background = '#efefef';
}
},
startRecognition:function(){
if(_voiceEnable){
recognition.start();
document.getElementById('cbMicro').style.background = '#b3b3b3';
}
},
synthVoice:function(text) {
const synth = window.speechSynthesis;
const utterance = new SpeechSynthesisUtterance();
utterance.text = text;
synth.speak(utterance);
},
setEventMessage:function(m,transfer){
var messageBox = `
`;
document.getElementsByClassName("cb-chat_log")[0].innerHTML += messageBox;
},
resetChat:function(){
_current_intent =null;
socket.emit('clear_slots',{user_id:_args[3]});
var element = document.getElementsByClassName('cb-predefine-intent-box');
element&&element[0]&&element[0].parentNode.removeChild(element[0]);
document.getElementById("CBOX_form").reset();
if(document.getElementsByClassName("cb-chat_log")[0]){
var string = '
';
_userInfo.pre_intents.forEach(function(item){
console.log(item);
string+=``+item['name']+``;
});
string +='
';
document.getElementsByClassName("cb-chat_log")[0].innerHTML += string;
}
// if(sessionStorage.getItem('demo')){
// this.getDemo(sessionStorage.getItem('demo'));
// }
this.scrollBottom();
},
getDemo:function(message){
// sessionStorage.setItem('demo',message)
if(_bot_id){
if(document.getElementsByClassName('cb_welcome-message'))
{
document.getElementsByClassName('cb_welcome-message')[0].parentElement.parentElement.parentElement.parentElement.parentElement.style.display='none'
}
var element = document.getElementsByClassName('cb-predefine-intent-box');
element&&element[0]&&element[0].parentNode.removeChild(element[0]);
//send message to bot if bot_id exists
socket.emit('bot_message', {bot_id:_bot_id,website_id:website_id,message:message,current_intent:_current_intent,visitor_id:_args[3]});
//et timer for get message form bot but not get then send to agent
//this.setBotTimer();
}
},
showOfflineForm:function(agentOffline=false){
console.log(agentOffline);
var that =this;
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
window.document.body.insertAdjacentHTML( 'afterbegin', this.responseText );
that.displayAllSlides(1);
// document.getElementsByTagName('body')[0].innerHTML += this.responseText;
if (_args[4] && _args[4] == 'overlay') {
// console.log('sdasd')
if (document.getElementsByClassName('cb-maximized-chat')[0])
document.getElementsByClassName('cb-maximized-chat')[0].style.display = '';
if (document.getElementsByClassName('cb-minimize-chat')[0])
document.getElementsByClassName('cb-minimize-chat')[0].style.display = 'none';
}
if(_CBOX_agentID){
document.getElementById('reset_chat').style.display = 'none';
document.getElementById("onlineAgent").innerHTML = _CBOX_agent_name;
}
// that.addDateTime();
if (_args[2] == 'start_chat') {
open = true;
that.scrollBottom();
// if(window.sessionStorage.getItem('CBOX_MSG'))document.getElementsByClassName('chatPanel')[0].innerHTML = window.sessionStorage.getItem('CBOX_MSG');
if (document.getElementsByClassName('cb-support-chat cb-minimize-chat').length > 0) {
document.getElementsByClassName('cb-support-chat cb-minimize-chat')[0].style.display = 'none';
}
// that.addDateTime();
} else {
if(agentOffline){
if(document.getElementsByClassName('cb-online-agent')[0]){
document.getElementsByClassName('cb-online-agent')[0].style.display = 'none';
}
if(document.getElementsByClassName('cb-agent_offline')[0]){
document.getElementsByClassName('cb-agent_offline')[0].style.display = '';
}
}
setTimeout(function(){
var select = document.getElementsByName("add_department")[0];
if (select) {
var xhttpDepartment = new XMLHttpRequest();
xhttpDepartment.open("GET", _apiUrl + "/api/v1/get-department?widget_id=" + _args[0], true);
xhttpDepartment.send();
xhttpDepartment.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('department');
var departments = JSON.parse(this.responseText).data;
departments.forEach(function (item) {
var option = document.createElement("option");
option.text = item.text;
option.value = item.id;
select.appendChild(option);
})
}
}
}
if(document.getElementsByClassName('cb-agent_offline')[0]){
_agent_status = 'agent_offline';
}
},1000);
}
}
};
console.log("GET", _apiUrl + "/widget-template?param=" + _args);
xhttp2.open("GET", _apiUrl + "/widget-template?param=" + _args + "&timezone=" + userTimezone + "&day=" + userDay + "&userTime=" + userTime+"&offline_form="+agentOffline+"&host="+location.host, true);
if(_args[4] != 'overlay') {
xhttp2.send();
}
},
clickMessageLink:function(){
// console.log('')
// var that = this;
// var link = document.querySelectorAll('.cb-chatLogRenderer a');
// console.log(link);
// if(link && link.length >0){
// link.forEach(function(item){
// if(item.getAttribute('href').indexOf('http://') == -1){
// item.addEventListener('click',function(event){
// console.log(item.text);
// that.chatBoxsendMsg(item.text)
// // event.preventDefault();
// // return false;
// });
// }
// })
// }
}
};
}());
//use for when link change use for ajax page change
window.onhashchange = function () {
console.log('asdsad');
}