var synalio = (function(){ var version = "1.12"; var cKey = "_rslgvry"; var isCancelling = false; var design_height_mobile = ''; var design_width_mobile = ''; var design_button_color = ''; var design_text_color2 = ''; var design_sub_color = ''; var design_width = ''; var design_height = ''; // var design_close_type = ''; var design_close_type = 'img'; var display_type = 'box'; var isClosedWindowChat = false; var firstClick = false; var cssText = ''; var objectCss = {}; var positionTimeOut = null; var isHideChatBox = false; var isAutoDisplayBanner = false; var isOpenedChat = false; var iframeStylePosition = "left: auto;right: 0px;"; var windowPosition = "right"; var iframeStyle = "z-index: 999999998;position:fixed; bottom: 0px;border: 0px;background: none;" + iframeStylePosition; var iframeStyleHeightOpen = "height: " + getWindowHeight() + "px;"; // "height: 550px;"; var iframeStyleWidthClose; var iframeStyleHeightClose = "height: 52px;"; var iframeStyleWidthOpen = "width: " + getWindowWidth() + "px;"; var iframeStyleHeightImgClose; var position_close_box_value = '0'; var position_close_box_type = 'px'; var isMobile = false; var isFullScreen = false; var isLogMessage = false; var animationEndEvent = whichAnimationEndEvent(); var transitionEndEvent = whichTransitionEndEvent(); var closeImageLoaded = false; var closeImageWidth; var closeImageHeight; var closeImageBadgeHeight = 25; // 25 is spacing for displaying badge number var initFooterHeight; var loadingInterval = 1000; var appid = "26a0e54b727f425d9094f462d4ea44d6"; var is_sent_init = false; var is_toggled = false; var keyPressMode = 1; var textAreaHeight = 60; var socket; var logs = []; var richMenu = null; var richMenuInit = false; var headerText = ""; var characterImage = "https://s3-ap-northeast-1.amazonaws.com/rebot-line-resized/1/799d4d39749b4e80921596b9d5786097.png/origin"; var unread_ids = []; var windowElement; var windowToggled; var synalioDocument; var synalioParentDocument; var synalioParentWindow; var header; var body; var bodyInner; var bodyOuter; var bodyDefaultWidth = 341; // from synalio.css var bodyDefaultHeight = 347; // from synalio.css var widthDelta; var footer; var rowSize; var toggleStatus = -1; var xhrs; var isHttpLoadingStarted; var httpLoadingTimer; var reservation; var reservation_autoreplies = []; var skipReservation = false; var retryCount = 0; var hiddenStyle = ""; var backToHome = "メニューに戻る"; var ext = {}; var json = "None"; var cookies = (json !== 'None') ? JSON.parse(json.replace(/'/g, '"')) : []; var errorCheckbox; var errorCheckboxMessage = "チェックを入れてください"; var carouselLastId = 0; var scrollBarWidth = 20; var mobileInnerWidth = isFullScreen ? 100 : 89.33333; // % var isSentFinishSignalAtLoading = false; var currentScrollPosition = {}; var isFocusInput = false; var chat_msg_common_tmpl = '
@1
'; var chat_msg_l_tmpl = '
...
@1
'; var chat_msg_r_tmpl = '
@1
'; var chat_msg_c_tmpl = '
@1
'; var chat_msg_c_img_tmpl = '
'; var chat_reply_wrap = '
@1
'; var chat_loading_tmpl = '
...
'; var chat_msg_f_tmpl = '
...
@1
'; var chat_msg_f_edit_button_tmpl = '
...
@1
'; var chat_cs_form_tmpl = '
...
ご利用ありがとうございます。
よろしければ、今後の改善のため、オペレータに対する評価をお願いいたします。
'; var chat_message_carousel_tmpl = '
<
>
'; var chat_message_carousel_item_tmpl = '
  • @3

    @1

    @2

    @4
  • '; var chat_message_carousel_item_image_tmpl = '
    '; var chat_message_carousel_button_tmpl = '
    @1
    '; var chat_message_rich_menu_button_tmpl = '
    '; var chat_feedback_form_tmpl = '
    '; var chat_msg_f_names = []; var btnCharLen = 11; var maxConvNum = 30; var isDemo = 0; var isPublish = 1; var s = ''; var scenario_id = -1; var canOpenOnReceiveLog = true; var refererUrl = location.href; var cntKey = '_rslgvry_conv_cnt'; var sessionId = ''; var pvNum = 0; var isSafari = /^((?!chrome|android|crios).)*safari/i.test(navigator.userAgent); var naCloseChatOpened = false; var nanalyticsParams = {}; var nanalyticsRetryCount = 0; function uuidv4() { var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); return uuid; } function getOrCreateUserId() { s = isSafari ? localStorage.getItem(cKey) : getCookie(cKey); if (!s) { s = uuidv4(); saveUserId(s); } } function saveUserId(uid) { if (isSafari) { localStorage.setItem(cKey, uid); } else { if (!uid) { setCookie(synalioParentDocument, cKey, '', null, 'Thu, 01 Jan 1970 00:00:00 UTC'); } else { setCookie(synalioParentDocument, cKey, uid); } } } function increaseConvCount() { var convCountStr = isSafari ? localStorage.getItem(cntKey) : getCookie(cntKey); var convCount = parseInt(convCountStr); if (isNaN(convCount)) { convCount = 0; } setConvCount(convCount + 1); } function setConvCount(cnt) { if (isSafari) { localStorage.setItem(cntKey, cnt.toString()); } else { setCookie(synalioParentDocument, cntKey, cnt.toString()); } } function updateNanalyticsParams(params) { sessionId = params.session_id || null; pvNum = params.pv_num || 0; var keys = ['site_id', 'user_id', 'browser_width', 'browser_height', 'language', 'session_id', 'session_num', 'session_start_time', 'session_channel_url', 'source', 'medium', 'browser_time', 'url', 'referer_url', 'keyword', 'campaign']; for(var i = 0; i < keys.length; i++) { nanalyticsParams[keys[i]] = params[keys[i]] || ''; } nanalyticsParams['chatbot_talk'] = getCookie(cntKey) || 0; } function htmlToElement(html, isMenu) { var template = document.createElement('template'); template.innerHTML = html; if(template.content) { // return template.content.firstChild; return template.content; } else{ if(!isMenu){ return template.firstElementChild; } else { return template; } } } function decorateMessage(tmplType, messageHtml) { return messageHtml; if(tmplType == 'c') { return messageHtml.replace(/@5/g, design_button_color).replace(/@6/g, design_text_color2) } else if(tmplType == 'l'){ return messageHtml.replace(/@2/g, design_text_color2) } else if(tmplType == 'r'){ return messageHtml.replace(/@2/g, design_sub_color).replace(/@3/g, design_text_color2) } return ''; } function initHttpLoading(){ isHttpLoadingStarted = false; if(httpLoadingTimer){ clearTimeout(httpLoadingTimer); httpLoadingTimer = null; } if(!isRtchat()){ httpLoadingTimer = setTimeout(function(){ isHttpLoadingStarted = true; stopLoading(); writeLoading(); scroll(1); }, 2000); } } function sendFinishRtChatSignal() { var msg = 'finish_rtchat'; scroll(1); toggleChatBodyScroll(0); var isButton = true; var isInitMsg = true; var image, mime_type, extraParams; xhr = new XMLHttpRequest(); xhr.onreadystatechange = httpStateChange; xhr.onerror = httpError; xhr.ontimeout = httpError; xhr.open('POST', 'https://synalio.com/api/web'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(createParam(msg, isButton, isInitMsg, image, mime_type, extraParams)) setTimeout(function(){ if(!isRtchat()){ toggleChatBodyScroll(1); } }, 500); } function sendMessage(msg, skip_msg, isButton, isInitMsg, image, mime_type, extraParams){ if(!skip_msg) { writeMessage(htmlToElement(decorateMessage('r', chat_msg_r_tmpl).replace(/@1/g, msg.replace(/\r?\n/g, '
    ')))); scroll(1); toggleChatBodyScroll(0); } skipReservation = true; if(reservation){ clearTimeout(reservation); } xhr = new XMLHttpRequest(); xhr.onreadystatechange = httpStateChange; xhr.onerror = httpError; xhr.ontimeout = httpError; xhr.open('POST', 'https://synalio.com/api/web'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(createParam(msg, isButton, isInitMsg, image, mime_type, extraParams)) initHttpLoading(); if(!isRtchat()){ toggleChatBodyScroll(1); } increaseConvCount(); } function initData(){ if(!is_sent_init){ is_sent_init = true; sendMessage("メニュー", true, true, true, null, null, {'home': 1}); deleteSubmitForms(); var postData = { 'event_type': 'chat_opened', 'event_data': { 'unique_id': appid, 'user_id': s, } }; sendAnalyticsData(postData); } } function openLink(url, target){ if (!url.match(/^https?:\/\//i)) { url = '//' + url; } if (window.synalytics) { url = window.synalytics.getUrl(url); } window.open(url, target); } function sendPageinfo(){ if (skipReservation) { return; } xhr_page = new XMLHttpRequest(); xhr_page.onreadystatechange = receiveReserve; xhr_page.open('POST', 'https://synalio.com/api/web/26a0e54b727f425d9094f462d4ea44d6/move_page'); xhr_page.setRequestHeader('Content-Type', 'application/json'); var params = { s: s, title: synalioParentDocument.title, url: location.href }; if(checkDemo() == 1){ params['demo'] = 1; } if (Object.keys(ext).length > 0) { params.ext = ext; } xhr_page.send(JSON.stringify(params)); } function sendAnalyticsData(data){ if(checkDemo() != 1){ var xhr = new XMLHttpRequest(); if (data['event_data'] && synalioWindow.Nanalytics) { data['event_data']['session_id'] = sessionId; data['event_data']['pv_num'] = pvNum; data['nanalytics'] = nanalyticsParams; } xhr.open('POST', 'https://synalio.com/api/analytics'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); } } var afterGetLogsFunc = function() { setTimeout(function() { if (!isSentFinishSignalAtLoading) { isSentFinishSignalAtLoading = true; sendFinishRtChatSignal(); } if (!socket) {openWs();} }, 1500); }; //re-define afterGetLogsFunc to ignore 'isSentFinishSignalAtLoading' param. function resetAfterGetLogsFunc() { afterGetLogsFunc = function() { setTimeout(function() { sendFinishRtChatSignal(); if (!socket) {openWs();} }, 1500); }; } function getLogs(s, session_id){ synalioDocument = synalioParentDocument.getElementById('synalio-iframe').contentDocument; windowElement = synalioDocument.getElementsByClassName("window-box")[0]; if(scenario_id > 0){ windowElement.style.visibility = "visible"; loadRichMenu(); return; } var isNeed = 'None' != '-1'; if(!isNeed){ return; } xhrs = new XMLHttpRequest(); xhrs.onreadystatechange = receiveLogs; xhrs.open('POST', 'https://synalio.com/api/web/26a0e54b727f425d9094f462d4ea44d6/chat_logs'); xhrs.setRequestHeader('Content-Type', 'application/json'); xhrs.send(JSON.stringify({s:s, session_id: session_id, url: refererUrl})) } function sendReserveMessageInfo(s, state, response, buttons, node, scenario_response){ xhr_state = new XMLHttpRequest(); xhr_state.open('POST', 'https://synalio.com/api/web/26a0e54b727f425d9094f462d4ea44d6/auto_message'); xhr_state.setRequestHeader('Content-Type', 'application/json'); var params = {s:s, session_id: sessionId, state:state, response:response, buttons:buttons, node:node, scenario_response:scenario_response}; if(checkDemo() == 1){ params['demo'] = 1; } xhr_state.send(JSON.stringify(params)); } function sendSatisfactionSurvey(params){ xhr_state = new XMLHttpRequest(); xhr_state.open('POST', 'https://synalio.com/api/web/26a0e54b727f425d9094f462d4ea44d6/satisfaction_survey'); xhr_state.setRequestHeader('Content-Type', 'application/json'); xhr_state.send(JSON.stringify(params)) } function sendFeedbackResponse(params){ xhr_state = new XMLHttpRequest(); xhr_state.open('POST', 'https://synalio.com/api/web/26a0e54b727f425d9094f462d4ea44d6/feedback_response'); xhr_state.setRequestHeader('Content-Type', 'application/json'); xhr_state.send(JSON.stringify(params)) } function receiveLogs(){ switch(xhrs.readyState) { case 4: // リクエスト成功 if (((200 <= xhrs.status && xhrs.status < 300) || (xhrs.status == 304)) && xhrs.responseText) { var json = JSON.parse(xhrs.responseText); s = json.s; logs = json.logs; richMenu = json.rich_menu; // Check rtchat status if(json.is_rtchat){ openWs(); } toggleRtchatStatus(json.is_rtchat); var is_open = getCookie('r_window'); // Continue from session if(logs.length > 0){ is_sent_init = true; var clearedMessages = false; if(retryCount > 0){ clearMessages(); clearedMessages = true; } if (!isMobile && !clearedMessages) { isLogMessage = true; } // if reservation_autoreplies set, check admin user replying or not. // ※ if last admin_message is after system_message, think "replied from admin" var isNotRepliedFromAdmin = false; var index = 0; var isSendSignal = false; logs.forEach(function(log){ index++; if (log.type == 'system') { isNotRepliedFromAdmin = true; } else if (log.type == 'admin_user') { isNotRepliedFromAdmin = false; } writeMessageProcess(log); //if finished_rtchat, send "finish_rtchat" signal for next scenario. if (logs.length === index && log.type === 'system' && log.text === 'オペレータ対応が終了しました') { afterGetLogsFunc(); } }); if (reservation_autoreplies && reservation_autoreplies.length > 0 && !isNotRepliedFromAdmin) { // Cancel reservation message reservation_autoreplies.forEach(function(timer){ clearTimeout(timer); }); } var log = logs[logs.length - 1]; if((log.type === 'bot' || log.type === 'admin_user' || log.type === 'end_user' || log.type === 'system') && log.buttons){ menu_process(log); } isLogMessage = false; windowElement.style.visibility = "visible"; if(is_open === 'on'){ if (canOpenOnReceiveLog) { synalio.toggle(0); } } else { if(unread_ids.length > 0){ setBadge(); } } // CHANGED /*setTimeout(function(){ synalio.resize(windowElement.offsetHeight); scroll(1); }, 300);*/ } else { if( is_open === 'on') { if (canOpenOnReceiveLog) { synalio.toggle(0); } } windowElement.style.visibility = "visible"; var postData = { 'event_type': 'page_start', 'event_data': { 'unique_id': appid, 'user_id': s } }; if (synalioWindow.Nanalytics && Object.keys(nanalyticsParams).length == 0) { synalioWindow.Nanalytics('get',function(params) { updateNanalyticsParams(params); sendAnalyticsData(postData); }); } else { sendAnalyticsData(postData); } } // Send title and url sendPageinfo(); // Open Websocket if(retryCount == 0){ // openWs(); } retryCount = 0; // rich menu loadRichMenu(); } break; } } function receiveReserve(){ if (skipReservation) { return; } switch(xhr_page.readyState) { case 4: // リクエスト成功 if (((200 <= xhr_page.status && xhr_page.status < 300) || (xhr_page.status == 304)) && xhr_page.responseText) { var json = JSON.parse(xhr_page.responseText); s = json.s; if(json.reserve){ // Reserve logic reservation = setTimeout(function(){ var postData = { 'event_type': 'chat_opened', 'event_data': { 'unique_id': appid, 'user_id': s, } }; sendAnalyticsData(postData); reserveProcess(json.reserve, s, true); }, json.reserve.time * 1000); } } break; } } function reserveProcess(message, s, showLoading){ var lastResElem; deleteReplyOptions(); deleteSubmitForms(); is_sent_init = true; if(message.is_open){ synalio.toggle(0); } var cnt = 0; var responses = message.response; var responsesString = JSON.stringify(responses); responseProcess(function(){ menu_process(message, lastResElem); sendReserveMessageInfo(s, message.state, JSON.parse(responsesString), message.buttons, message.node, message.scenario_response) }); function responseProcess(callback){ if(cnt == 0){ cnt++; if(responses.length == 0){ if(callback){ callback(); } return; } var response = responses[0]; writeMessageProcess({ 'text': response, 'type': message.type, }, showLoading); responses.shift(); setTimeout(function(){ responseProcess(callback); }, loadingInterval); } else { stopLoading(); cnt = 0; responseProcess(callback); } } } function setFocusInput(status) { isFocusInput = status; } function writeMessageProcess(message, showLoading){ var match; var isForm = false; var lastResElem; var chat_msg_template = (message.text.indexOf('id="chat-form-submit"') != -1) ? chat_msg_f_edit_button_tmpl : chat_msg_f_tmpl; if(message.message_type && message.message_type === 'form_ui'){ isForm = true; } else { match = message.text.match(/^##form:(.+)##/); if(match && match.length >= 2){ isForm = true; } } if(!isForm){ msg = message.text.replace(/\r?\n/g, '
    '); } var isCarousel = false; if(message.message_type && message.message_type === 'carousel' || message.text.indexOf('##carousel##') == 0){ isCarousel = true; } if(message.type === 'end_user'){ writeMessage(htmlToElement(decorateMessage('r', chat_msg_r_tmpl).replace(/@1/g, msg))); } else if (message.type === 'bot'){ if(isForm){ if(match && match.length >= 2){ lastResElem = writeMessage(htmlToElement(chat_msg_template.replace(/@1/g, message.text.replace(match[0], '')).replace(/@2/g, match[1])), showLoading); chat_msg_f_names.push(match[1]); } else { lastResElem = writeMessage(htmlToElement(chat_msg_template.replace(/@1/g, message.text).replace(/@2/g, 'input')), showLoading); chat_msg_f_names.push('input'); } } else if(isCarousel){ carousel_process(message.text); } else{ lastResElem = writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_tmpl).replace(/@1/g, msg).replace(/@2/g, headerText).replace(/@3/g, characterImage)), showLoading); } } else if (message.type === 'admin_user'){ var nm = message.sender ? message.sender : headerText; var img = message.sender_image ? message.sender_image : characterImage; writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_tmpl).replace(/@1/g, msg).replace(/@2/g, nm).replace(/@3/g, img)), showLoading); if(!message.is_read){ // Unread messages unread_ids.push(message.msg_id); } } else if(message.type === 'system'){ writeMessage(htmlToElement(chat_msg_common_tmpl.replace(/@1/g, message.text))); } return lastResElem; } function getFormData(form){ var formData={}; var formElements = form.elements; for (var i = 0; i < formElements.length; i++) if (formElements[i].type != 'button') formData[formElements[i].name]=formElements[i].value; return JSON.stringify(formData); } function startHttpFakeLoading(){ if(!isHttpLoadingStarted){ // reply time < 2 secs if(httpLoadingTimer){ clearTimeout(httpLoadingTimer); httpLoadingTimer = null; } writeLoading(); // start fake loading } } function httpStateChange(){ switch(xhr.readyState){ case 4: // リクエスト成功 if(((200 <= xhr.status && xhr.status < 300) || (xhr.status == 304)) && xhr.responseText) { var json = JSON.parse(xhr.responseText); s = json.s; var responses = json.response; var responseLength = responses.length; var lastResElem; var cnt = 0; startHttpFakeLoading(); // Check rtchat status if(json.is_rtchat){ openWs(); } var callback = !json.is_rtchat ? null : function(){ if(json.is_rtchat){ writeMessage(htmlToElement(chat_msg_common_tmpl.replace(/@1/g, 'オペレータ対応が開始しました'))); toggleRtchatStatus(true); } }; if (typeof json.input_show_status !== 'undefined' && json.input_show_status !== null ) { overrideHideInputSetting(json.input_show_status) } message_process(callback); // reserve if(json.reserve){ json.reserve.forEach(function(r){ var timer = setTimeout(function(){ reserveProcess(r, s, true); }, r.time * 1000); reservation_autoreplies.push(timer); }); } if(json.script){ for(var i=0;i= 2){ lastResElem = writeMessage(htmlToElement(chat_msg_template.replace('@1', res.replace(match[0], '')).replace(/@2/g, match[1])), true); scroll(1); chat_msg_f_names.push(match[1]); } else if(res.indexOf('##carousel##') == 0){ stopLoading(); carousel_process(res, json); scroll(1); } else{ lastResElem = writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_tmpl).replace(/@1/g, res).replace(/@2/g, headerText).replace(/@3/g, characterImage)), true); scroll(1); } if(responseLength == responses.length){ // scroll(1); } responses.shift(); setTimeout(function(){ message_process(callback); }, timer); } else { stopLoading(); cnt = 0; message_process(callback); } } } else { toggleChatBodyScroll(0); } break; } } function appendMenuToLastResponse(menuHtml, lastResElem){ if(!lastResElem){ var targets = synalioDocument.getElementsByClassName('chat-message-body'); if(targets.length <= 0) { return; } lastResElem = targets[targets.length - 1]; } deleteReplyOptions(); // var menu = '
    ' + menuHtml + '
    '; if(lastResElem.className.indexOf('left-talk-box') != -1){ var elem = htmlToElement(menuHtml, true); while(elem.childNodes.length > 0){ var childElem = elem.childNodes[0]; ensureShowElement(childElem); lastResElem.appendChild(childElem); } } else { if(lastResElem.className.indexOf('custom-outer-box') == -1){ writeMessage(htmlToElement(chat_reply_wrap.replace(/@1/g, menuHtml), true), false, true); } } } function stopLoading(){ var targets = synalioDocument.querySelectorAll('[data-loading="on"]'); for(var i = 0; i <= targets.length - 1; i++){ if(targets[i].children.length >= 2){ targets[i].setAttribute('data-loading', 'complete'); } else if(targets[i].children.length > 0 && targets[i].children[0].className == 'loading-box'){ if(targets[i].parentNode){ targets[i].parentNode.removeChild(targets[i]); } } } scroll(1); } function existLoading(){ var targets = synalioDocument.querySelectorAll('[data-loading="on"]'); return targets.length > 0 ? true : false; } function getLastLoading(){ var targets = synalioDocument.querySelectorAll('[data-loading="on"]'); var loading = targets.length > 0 ? targets[targets.length-1] : null; if(!loading){ loading = writeLoading(); } return loading; } function menu_process(json, lastResElem){ var menu_count = 0; if(json.buttons && json.buttons.length > 0){ var l = []; var replyDecos = json.reply_deco || []; var j = 0; for (var i = 0; i < json.buttons.length; i++) { var decoClass = ''; if(replyDecos.length > j){ decoClass = replyDecos[j]; } j++; var val1 = json.buttons[i].img ? json.buttons[i].img : json.buttons[i].label.replace(/"/g,'"'); var tmpl = json.buttons[i].img ? chat_msg_c_img_tmpl : chat_msg_c_tmpl; var val2 = json.buttons[i].url ? json.buttons[i].url : json.buttons[i].msg.replace(/"/g,'"'); var val3 = json.buttons[i].url && json.buttons[i].url_target ? json.buttons[i].url_target : ''; l.push(decorateMessage('c', tmpl).replace(/@1/g, val1).replace(/@2/g, val2).replace(/@3/g, decoClass).replace(/@4/g, val3)); } appendMenuToLastResponse(l.join(''), lastResElem); menu_count = l.length; } else if(!json.no_button) { var elm = decorateMessage('c', chat_msg_c_tmpl).replace(/@1/g, backToHome).replace(/@2/g, backToHome).replace(/@3/g, ''); if(chat_msg_f_names.length == 0){ menu_count++; appendMenuToLastResponse(elm, lastResElem); } } if (typeof json.is_feedback !== 'undefined' && json.is_feedback !== null && json.is_feedback && json.feedback_log_id && lastResElem) { var state = json.switch_state ? json.switch_state : json.dialogue_history[json.dialogue_history.length-1].state_name; var actionName = json.state[state] && json.state[state].response ? json.state[state].response : json.action; var feedback_form = htmlToElement(chat_feedback_form_tmpl.replace(/@2/g, '

    回答に問題がある場合、以下のどちらだったかを教えてください。回答精度向上にフィードバックを活かします。

    ').replace(/@3/g, '見当違いな回答').replace(/@4/g, '正しいが不十分な回答').replace(/@5/g, '

    フィードバックありがとうございました。
    回答内容改善の参考にさせて頂きます。

    ').replace(/@6/g, actionName).replace(/@7/g, state).replace(/@8/g, json.feedback_log_id), true); lastResElem.appendChild(feedback_form); var feedbackBtns = lastResElem.getElementsByClassName('feedbackBtn-'+json.feedback_log_id); if (feedbackBtns.length > 0) { var maxWidth = feedbackBtns[0].offsetWidth; for (var j = 0; j < feedbackBtns.length; j++) { maxWidth = feedbackBtns[j].offsetWidth <= maxWidth ? maxWidth : feedbackBtns[j].offsetWidth; } for (var j = 0; j < feedbackBtns.length; j++) { feedbackBtns[j].style.width = maxWidth + 'px'; } } } } function isObject(obj) { return obj && !Array.isArray(obj) && typeof obj === 'object'; } function carousel_process(res, json){ var carouselData = []; try{ var index = res.indexOf('##carousel##'); if(index != -1){ var carouselString = res.substr(index); var arr = carouselString.split('##carousel##'); if(arr.length > 1){ carouselString = arr[1]; carouselData = JSON.parse(carouselString); } } }catch(ex){ } if(carouselData.length == 0){ return; } carousel.deleteButtons(); var carouselItems = []; for (var i = 0; i < carouselData.length; i++) { var decoClass = ''; var buttons = []; for(var j = 0; j < carouselData[i].buttons.length; j++){ if (carouselData[i].buttons[j].reply_link_target && carouselData[i].buttons[j].reply_link_target === 1) { carouselData[i].buttons[j].uri_target = '_self' } var btnVal1 = carouselData[i].buttons[j].label.replace(/"/g,'"'); //var btnVal2 = carouselData[i].buttons[j].uri ? carouselData[i].buttons[j].uri : carouselData[i].buttons[j].text.replace(/"/g,'"'); var btnVal2 = (carouselData[i].buttons[j].type=='uri' && carouselData[i].buttons[j].uri) ? carouselData[i].buttons[j].uri : carouselData[i].buttons[j].text.replace(/"/g,'"'); var btnVal3 = carouselData[i].buttons[j].uri && carouselData[i].buttons[j].uri_target ? carouselData[i].buttons[j].uri_target : ''; var btnVal5 = carouselData[i].buttons[j].reply_deco && carouselData[i].buttons[j].reply_deco === 1 ? 'style="font-weight: bold"' : '' ; buttons.push(chat_message_carousel_button_tmpl.replace(/@1/g, btnVal1).replace(/@2/g, btnVal2).replace(/@3/g, decoClass).replace(/@4/g, btnVal3).replace('@5', btnVal5)); } if(buttons.length > 0){ buttonValue = buttons.join(''); } var itemVal1 = carouselData[i].title.replace(/"/g,'"'); var itemVal2 = carouselData[i].text.replace(/"/g,'"'); chat_message_carousel_item_image_tmpl var itemVal3 = ''; if(carouselData[i].image_url){ itemVal3 = chat_message_carousel_item_image_tmpl.replace(/@1/g, carouselData[i].image_url); } var itemVal4 = buttons.join(''); carouselItems.push(chat_message_carousel_item_tmpl.replace(/@1/g, itemVal1).replace(/@2/g, itemVal2).replace(/@3/g, itemVal3).replace(/@4/g, itemVal4)); } carouselLastId += 1; var carouselItemsHtml = carouselItems.join(''); var carouselHtml = chat_message_carousel_tmpl.replace(/@1/g, carouselLastId).replace(/@2/g, carouselItemsHtml); var lastResElem = writeMessage(htmlToElement(carouselHtml), false, false); carousel.show(carouselLastId); if (isObject(json) && typeof json.is_feedback !== 'undefined' && json.is_feedback !== null && json.is_feedback && json.feedback_log_id && lastResElem) { var state = json.switch_state ? json.switch_state : json.dialogue_history[json.dialogue_history.length-1].state_name; var actionName = json.state[state] && json.state[state].response ? json.state[state].response : json.action; var feedback_form = htmlToElement(chat_feedback_form_tmpl.replace(/@2/g, '

    回答に問題がある場合、以下のどちらだったかを教えてください。回答精度向上にフィードバックを活かします。

    ').replace(/@3/g, '見当違いな回答').replace(/@4/g, '正しいが不十分な回答').replace(/@5/g, '

    フィードバックありがとうございました。
    回答内容改善の参考にさせて頂きます。

    ').replace(/@6/g, actionName).replace(/@7/g, state).replace(/@8/g, json.feedback_log_id), true); var wrapDiv = document.createElement("DIV"); wrapDiv.className = "left-talk-box"; wrapDiv.setAttribute('data-talkshow', 'talkshow'); wrapDiv.appendChild(feedback_form); lastResElem.parentNode.appendChild(wrapDiv); var feedbackBtns = wrapDiv.getElementsByClassName('feedbackBtn-'+json.feedback_log_id); if (feedbackBtns.length > 0) { var maxWidth = feedbackBtns[0].offsetWidth; for (var j = 0; j < feedbackBtns.length; j++) { maxWidth = feedbackBtns[j].offsetWidth <= maxWidth ? maxWidth : feedbackBtns[j].offsetWidth; } for (var j = 0; j < feedbackBtns.length; j++) { feedbackBtns[j].style.width = maxWidth + 'px'; } } } } function httpError(){ var msg = "
  • 送信に失敗しました。
    ネットワーク接続をご確認いただくか、お時間おいて再度お試しください。
  • "; writeMessage(htmlToElement(msg)); } function createParam(msg, isButton, isInitMsg, image, mime_type, extraParams){ if(!s) { // In case no s. s = new Date().getTime().toString(16) + Math.floor(1000 * Math.random()).toString(16) } var params = []; var cookieValue = null; params.push("appid=" + appid); params.push("content=" + encodeURIComponent(msg)); params.push("mode=web"); params.push("s=" + s); params.push("session_id=" + sessionId); params.push("pv_num=" + pvNum); params.push("url=" + refererUrl); if(checkDemo() == 1){ params.push("demo=1"); } if(isButton){ params.push("button=1"); } if(isInitMsg){ params.push("init=1"); } if(image){ params.push("image=" + image); } if(image){ params.push("mime_type=" + mime_type); } if (Object.keys(ext).length > 0){ params.push("ext=" + JSON.stringify(ext)); } if (scenario_id != ""){ params.push("scenario_id="+scenario_id) } for(var i = 0; i < cookies.length; i++) { cookieValue = getCookie(cookies[i].cookie_key); if (cookieValue) params.push(cookies[i].cookie_key + "=" + cookieValue); } if(extraParams){ for(arg in extraParams){ params.push(arg + '=' + extraParams[arg]); } } return params.join('&'); } function writeLoading(){ // writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_tmpl).replace(/@1/g, chat_loading_tmpl).replace(/@2/g, headerText).replace(/@3/g, characterImage))); var elem = synalioDocument.getElementById('synalio-chat-message'); var loadingElem = htmlToElement(chat_loading_tmpl); elem.appendChild(loadingElem); return elem.lastChild; } function deleteReplyOptions(){ var chatMessageBody; var options = synalioDocument.getElementsByClassName('reply-option'); while(options.length > 0){ if(options[0].parentNode){ if(!chatMessageBody){ chatMessageBody = options[0].parentNode; } options[0].parentNode.removeChild(options[0]); } } if(chatMessageBody && chatMessageBody.childNodes.length > 0){ var lastChild = chatMessageBody.childNodes[chatMessageBody.childNodes.length - 1]; lastChild = lastChild.nodeName == 'TEMPLATE' ? lastChild.childNodes[lastChild.childNodes.length - 1] : lastChild; if((!lastChild.className || (lastChild.className != 'chat-block' && lastChild.className != 'form-block')) && chatMessageBody.parentNode){ chatMessageBody.parentNode.removeChild(chatMessageBody); } } } function deleteSubmitForms(){ do{ var formName = chat_msg_f_names.shift(); if(formName != undefined) deleteSubmitForm(formName); }while(formName != undefined); } function deleteSubmitForm(formName){ var forms = synalioDocument.getElementsByName(formName) for(var i = 0; i < forms.length; i++){ var removeElem = forms[i].parentElement; var parentElem = removeElem.parentElement; parentElem.removeChild(removeElem); var rootElem = parentElem.parentElement; rootElem.removeChild(parentElem); } } function clearMessages(){ var elem = synalioDocument.getElementById('synalio-chat-message'); while (elem.firstChild) { elem.removeChild(elem.firstChild); } } // fix menu does not show function ensureShowElement(elem){ elem.addEventListener(animationEndEvent,(function(){ return function f(e){ elem.className += ' comp-anime-stop'; elem.removeEventListener(animationEndEvent, f, false); } })(1), false); } function writeMessage(chat_message, showLoading, isMenu){ /* if(showLoading && existLoading()){ setTimeout(function(){ writeMessage(chat_message, showLoading) }, loadingInterval); return; } stopLoading(); */ var elem = synalioDocument.getElementById('synalio-chat-message'); if(!isMenu){ if(!showLoading){ elem.appendChild(chat_message); } else{ var loading = getLastLoading(); if(loading){ try{ loading.appendChild(chat_message.childNodes[0].lastChild); }catch(ex){ loading.appendChild(chat_message.lastChild); } } else { elem.appendChild(chat_message); } } } else { while(chat_message.childNodes.length > 0){ elem.appendChild(chat_message.childNodes[0]); } } if(!isLogMessage){ ensureShowElement(elem.lastChild); // fix sent message does not show if(showLoading){ elem.lastChild.setAttribute('data-loading', 'on'); } elem.lastChild.setAttribute('data-talkshow', 'talkshow'); } if(elem.childElementCount > maxConvNum){ elem.removeChild(elem.children[0]); } return elem.lastChild; } function writeButton(btn){ deleteReplyOptions(); var elem = synalioDocument.getElementsByClassName('foot-box')[0]; elem.appendChild(btn); } function scroll(type){ var scrollContainer = synalioDocument.getElementsByClassName("over-talk-box")[0]; if(scrollContainer.style.overflowY == 'hidden'){ scrollContainer.style.overflowY = 'visible'; } var targets = synalioDocument.getElementsByClassName("chat-message-body"); if(targets.length - type >= 0){ var target = targets[targets.length - type]; var chatHeader = synalioDocument.getElementsByClassName("header-box")[0]; var chatBody = synalioDocument.getElementsByClassName("over-talk-box")[0]; // chat_body.scrollTop = target.offsetTop - chat_header.offsetHeight; //smoothScr.step = (target.offsetTop - chatHeader.offsetHeight - chatBody.scrollTop) / 15.0; smoothScr.stopShow(); smoothScr.anim(target, chatBody, chatHeader); } } function scrollOnLoad(){ var targets = synalioDocument.getElementsByClassName("chat-message-body"); var chatBody = synalioDocument.getElementsByClassName("over-talk-box")[0]; var chatHeader = synalioDocument.getElementsByClassName("header-box")[0]; var messageContainer = synalioDocument.getElementById('synalio-chat-message'); if(targets.length > 0){ setTimeout(function(){ chatBody.scrollTop = targets[targets.length - 1].offsetTop; // scroll(1); }, 50); } } var freezeVp = function(e) { e.preventDefault(); }; function setCurrentScrollPosition() { let doc = document.documentElement; let left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0); let top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); if (!currentScrollPosition.top) { currentScrollPosition.top = top; currentScrollPosition.left = left; } else if (currentScrollPosition.top > 0 && top > 0 && !isFocusInput) { currentScrollPosition.top = top; currentScrollPosition.left = left; } } function scrollToPosition() { if (currentScrollPosition.top) { let top = currentScrollPosition.top; window.scrollTo(0, top); } } function stopBodyScrolling(bool){ if (bool === true) { if (!firstClick) { firstClick = true; objectCss = { position: synalioParentDocument.body.style.position, width: synalioParentDocument.body.style.width, overflow: synalioParentDocument.body.style.overflow }; } synalioParentDocument.body.style.position = 'fixed'; synalioParentDocument.body.style.width = '100%'; synalioParentDocument.body.style.overflow = 'hidden'; // synalioParentDocument.body.setAttribute('style', "position:fixed;overflow:hidden;width:100%;"); setTimeout(function () { let mainBox = synalioDocument.getElementsByClassName('main-box')[0] if (mainBox) { mainBox.click(); } },200) } else { synalioParentDocument.body.style.overflow = objectCss.overflow ; scrollToPosition(); } } function isScrolling(){ return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 10; } function getElement(className){ return synalioDocument.getElementsByClassName(className)[0]; } function getElementHeight(className){ var elem = getElement(className); var height = elem.clientHeight; if(elem.style.paddingTop){ height -= parseInt(elem.style.paddingTop.replace('px', '')); } if(elem.style.paddingBottom){ height -= parseInt(elem.style.paddingBottom.replace('px', '')); } return height; } function getWindowWidth(){ return parseInt(design_width); } function getWindowHeight(){ return parseInt(design_height); } function getWindowWidthMobile(){ return parseInt(design_width_mobile); } function getWindowHeightMobile(){ return !isFullScreen ? parseInt(design_height_mobile) : 100; } function getScreenSize(){ if(!isMobile){ return {width: getWindowWidth(), heigh: getWindowHeight()}; } else { return {width: window.innerWidth, height: window.innerHeight}; } } function getScrollBarWidth() { if(isFullScreen){ return 0; } var inner = synalioDocument.createElement('p'); inner.style.width = "100%"; inner.style.height = "200px"; var outer = synalioDocument.createElement('div'); outer.style.position = "absolute"; outer.style.top = "0px"; outer.style.left = "0px"; outer.style.visibility = "hidden"; outer.style.width = "200px"; outer.style.height = "150px"; outer.style.overflow = "hidden"; outer.appendChild(inner); synalioDocument.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 == w2) { w2 = outer.clientWidth; } synalioDocument.body.removeChild(outer); return (w1 - w2); } function whichAnimationEndEvent(){ var t, el = document.createElement("fakeelement"); var animations = { 'animation' : 'animationend', 'OAnimation' : 'oAnimationEnd', 'MozAnimation' : 'animationend', 'WebkitAnimation': 'webkitAnimationEnd' } for (t in animations){ if (el.style[t] !== undefined){ return animations[t]; } } } function whichTransitionEndEvent(){ var t, el = document.createElement("fakeelement"); var transitions = { 'transition' : 'transitionend', 'OTransition' : 'oTransitionEnd', 'MozTransition' : 'transitionend', 'WebkitTransition': 'webkitTransitionEnd' } for (t in transitions){ if (el.style[t] !== undefined){ return transitions[t]; } } } function addMultiLine() { var mainBox = synalioDocument.getElementsByClassName('main-box')[0]; mainBox.style.height = "calc(100vh - " + (header.offsetHeight + footer.offsetHeight + 20*2) + "px)"; // padding: 20 mainBox.style.transition = "none"; } function resetMultiLine(){ footer.style.height = initFooterHeight + 'px'; synalioDocument.getElementById('synalio-chat-text-input').style.height = textAreaHeight + 'px'; var mainBox = synalioDocument.getElementsByClassName('main-box')[0]; mainBox.style.height = "calc(100vh - " + (header.offsetHeight + initFooterHeight + 20*2) + "px)"; // padding: 20 mainBox.style.transition = ''; } function changeCloseHeight(displayType) { if(displayType != 'img'){ iframeStyleHeightClose = 'height: ' + (windowElement.offsetHeight + 4) + 'px;'; } else { iframeStyleHeightClose = iframeStyleHeightImgClose; } if(design_close_type == 'img'){ iframeStyleHeightClose = "height: " + synalioDocument.getElementsByClassName('img-box')[0].offsetHeight + "px;"; } } function alignCloseImagePosition() { synalioDocument.getElementsByClassName("img-box")[0].setAttribute("style", imgClosePosition); } function onChatBodyScroll(){ window.lastScrollTime = new Date().getTime(); } function toggleChatBodyScroll(e){ if(e === 1){ synalioDocument.getElementsByClassName("over-talk-box")[0].style.overflowY = 'hidden'; } else { synalioDocument.getElementsByClassName("over-talk-box")[0].style.overflowY = 'visible'; } } function initMobileSize(iframe, windowBox){ iframe.style.width = '100vw'; iframe.style.height = getWindowHeightMobile() + '%'; iframe.style.bottom = 0; windowBox.style.width = '100vw'; windowBox.style.height = '100vh'; synalioDocument.getElementsByClassName('main-box')[0].style.height = 'calc(100vh - ' + (getElementHeight('header-box') + getElementHeight('foot-box')) + 'px)'; } function customChatSize(){ var self = this; var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; if (positionTimeOut) { clearTimeout(positionTimeOut); } windowBox.removeEventListener(animationEndEvent, customChatSize, false); windowBox.setAttribute('data-wtype', 'chat'); windowBox.setAttribute('data-first', true); windowBox.removeAttribute('style'); getElement('main-box').removeAttribute('style'); synalioDocument.getElementsByClassName('outer-talk-set-box')[0].removeAttribute('style'); if(isMobile){ initMobileSize(iframe, windowBox); }else{ iframe.style.width = getWindowWidth() + 'px'; iframe.style.height = getWindowHeight() + 'px'; var mainBox = getElement('main-box'); mainBox.removeAttribute('style'); resizeFitBrowser(synalioParentWindow); iframe.style.bottom = 0; } var contentElements = synalioDocument.getElementsByClassName('chat-message-body'); for(var i = 0; i < contentElements.length; i++){ if(!contentElements[i].getAttribute('data-talkshow')){ contentElements[i].setAttribute('data-talkshow', 'talkshow'); } } // scroll(1); scrollOnLoad(); } function customCloseSize(displayType) { var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; windowBox.setAttribute('data-wtype', displayType); if(isMobile){ if(displayType === 'img'){ let heightWindowBoxClose = closeImageHeight + closeImageBadgeHeight + 'px'; iframe.style.width = closeImageWidth + 'px'; iframe.style.height = heightWindowBoxClose; iframe.style.bottom = position_close_box_value + position_close_box_type; windowBox.style.width = closeImageWidth + 'px'; windowBox.style.height = heightWindowBoxClose; windowBox.style.padding = '0px'; }else{ windowBox.removeAttribute('style'); getElement('main-box').removeAttribute('style'); getElement('outer-talk-set-box').removeAttribute('style'); if(displayType != 'max-min'){ iframe.style.width = '100%'; } else { iframe.style.width = '27.47%'; } var frameHeight = 68; if (window.innerWidth != window.screen.width) { frameHeight = frameHeight * window.innerWidth / window.screen.width; } iframe.style.height = frameHeight + 'px'; if (isClosedWindowChat) { iframe.style.bottom = position_close_box_value + position_close_box_type; } else { isClosedWindowChat = true; } } }else{ windowBox.removeAttribute('style'); getElement('main-box').removeAttribute('style'); getElement('outer-talk-set-box').removeAttribute('style'); if(displayType === 'img'){ let heightWindowBoxClose = closeImageHeight + closeImageBadgeHeight + 'px'; iframe.style.width = closeImageWidth + 'px'; iframe.style.height = heightWindowBoxClose; iframe.style.bottom = position_close_box_value + position_close_box_type; windowBox.style.width = closeImageWidth + 'px'; windowBox.style.height = heightWindowBoxClose; windowBox.style.padding = '0px'; }else{ iframe.style.width = windowBox.offsetWidth + 'px'; let heightWindowBoxClose = getElement('outer-box').offsetHeight + (windowBox.style.paddingTop ? windowBox.style.paddingTop.replace('px', '') : 10) * 2 + 20 + 'px'; let heightWindowBoxCloseNew = 'calc(' + heightWindowBoxClose + ' + ' + position_close_box_value + position_close_box_type +')'; if (isClosedWindowChat) { iframe.style.height = heightWindowBoxCloseNew; windowBox.style.height = heightWindowBoxClose; // windowBox.style.bottom = position_close_box_value + position_close_box_type; positionTimeOut = setTimeout(function () { iframe.style.height = heightWindowBoxClose; iframe.style.bottom = position_close_box_value + position_close_box_type; }, 1000); } else { windowBox.style.height = heightWindowBoxClose; iframe.style.height = heightWindowBoxClose; isClosedWindowChat = true; } } } } function toggle(e, event){ // 0: open, 1: close, event: DOM's event synalio.toggle(e, event); } function resizeTextArea(evt){ var oldHeight = evt.target.offsetHeight || parseInt(evt.target.style.height.replace('px', '')); // Resize Text Area if(evt.target.scrollHeight >= evt.target.offsetHeight){ if(evt.target.scrollHeight < textAreaHeight + 20 + 8){ if (evt.target.scrollHeight > 0) { evt.target.style.height = evt.target.scrollHeight + "px"; } } else { evt.target.style.height = (textAreaHeight + 20 + 8) + "px"; } }else{ var height; for (var i = 0; i <= 10; i++){ height = Number(evt.target.style.height.split("px")[0]); evt.target.style.height = height - textAreaHeight + "px"; if(evt.target.scrollHeight > evt.target.offsetHeight){ if(evt.target.scrollHeight > textAreaHeight){ evt.target.style.height = evt.target.scrollHeight + "px"; } else { evt.target.style.height = textAreaHeight + "px"; } break; } } } if(!initFooterHeight){ initFooterHeight = footer.offsetHeight || parseInt(footer.style.height.replace('px', '')) } footer.style.height = (parseInt(evt.target.style.height.replace('px', '')) + 1) + 'px'; var newHeight = evt.target.offsetHeight || parseInt(evt.target.style.height.replace('px', '')); if(newHeight != oldHeight){ addMultiLine(); } // CHANGED // synalio.resize(windowElement.offsetHeight); } function fixPlaceholderOnIE() { var chat_text_input = synalioDocument.getElementById("synalio-chat-text-input"); chat_text_input.placeholder = chat_text_input.placeholder; } function resizeFitBrowser(windowObj){ fixPlaceholderOnIE(); /* scale window height fit inside browser for PC only */ if(synalioDocument.getElementsByClassName('window-box')[0].getAttribute('data-wtype') != 'chat'){ return; } if(windowObj.innerHeight < getWindowHeight()){ synalioParentDocument.getElementById('synalio-iframe').style.height = windowObj.innerHeight + 'px'; } else{ synalioParentDocument.getElementById('synalio-iframe').style.height = getWindowHeight() + 'px'; } } function startsWith(str, word){ return str.lastIndexOf(word, 0) === 0; } function isInRtchat(){ return synalioDocument.getElementsByClassName("window-box")[0].getAttribute('data-operation') == 'on'; } var runningOfflineCheck = false; function openWs(){ if(socket && socket.readyState == WebSocket.OPEN){ return; } var prtcl = "https:" == synalioParentDocument.location.protocol ? "wss" : "ws"; var host = "//synalio.com"; if(startsWith(host, "http")){ socket = new WebSocket("//synalio.com/chat/enduser/".replace(/https?/g, prtcl) + appid + "/" + s ); } else { socket = new WebSocket(prtcl + "://synalio.com/chat/enduser/" + appid + "/" + s ); } socket.onmessage = onWsMessage; socket.onopen = onWsOpen; socket.onclose = onWsClose; } function closeWs() { if(socket && socket.readyState == WebSocket.OPEN){ socket.close(); socket = undefined; } } function onWsMessage(e){ var msg = JSON.parse(e.data); if(msg.disconnect){ writeMessage(htmlToElement(chat_msg_common_tmpl.replace(/@1/g, 'オペレータ対応が終了しました'))); toggleRtchatStatus(false); var isCsFormShowed = false; if(msg.is_finish_rtchat_link == 1){ setTimeout(function(){ sendMessage("finish_rtchat", true, true, true); }, isCsFormShowed ? loadingInterval : 0); }else{ menu_process({buttons:[{'label':'メニューへ戻る', 'msg':'メニューに戻る'}]}); scroll(1); } } else { is_sent_init = true; var operatorIcon = msg.sender_image ? msg.sender_image : '//synalio.com/static/img/chat/operator_icon.png'; synalioDocument.getElementById('operator_icon').src = operatorIcon; var img = msg.sender_image ? msg.sender_image : characterImage; writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_tmpl).replace(/@1/g, msg.text.replace(/\r?\n/g, '
    ')).replace(/@2/g, msg.sender).replace(/@3/g, img))); scroll(1); // Notify that you read the message unread_ids.push(msg.msg_id); if(synalioParentDocument.hasFocus()){ sendReadNotice(); } // Set Badge setBadge(); if(!isInRtchat()){ writeMessage(htmlToElement(chat_msg_common_tmpl.replace(/@1/g, 'オペレータ対応が開始しました'))); } // Toggle Rtchat status toggleRtchatStatus(true); } // Cancel reservation message reservation_autoreplies.forEach(function(timer){ clearTimeout(timer); }); } function onWsOpen(){ isCancelling = false; // If it is retry connection, refresh the conversation data again if(retryCount > 0){ resetAfterGetLogsFunc(); getLogs(s, sessionId); } // If there's unread messages setTimeout(sendReadNotice, 1500); } function onWsClose(){ retryCount++; if(retryCount < 50){ //try to reconnect var waitMilliSeconds = function(retryCount) { if (retryCount <= 10) { // before 10s, reconnect every 2s. return 2000; } else { return (retryCount - 10) * 2000; } } setTimeout(function(){ openWs(); }, waitMilliSeconds(retryCount)); } } function updateCheckboxCustomValidity(form) { var checkbox = null; var checkedCount = 0; for (i = 0; i < form.elements.length; i = i + 1) { if (form.elements[i].name === "") { continue; } if((form.elements[i].nodeName == 'INPUT') && (form.elements[i].getAttribute('type') == 'checkbox')) { // Move to another checkbox group if (checkbox && checkbox.name != form.elements[i].name) { if (checkedCount == 0) { // There was an invalid checkboxes group, so top here break; } else { // Need to reset this before checking new group checkbox = null; checkedCount = 0; } } if (!checkbox && form.elements[i].className.indexOf('required') != -1) { checkbox = form.elements[i]; } if (checkbox && form.elements[i].checked) { checkedCount++; } } } var result = true; errorCheckbox = checkbox; if (errorCheckbox) { if (checkedCount == 0) { errorCheckbox.setCustomValidity(errorCheckboxMessage); result = false; } else { errorCheckbox.setCustomValidity(''); } } return result; } function validateFormFields(form) { var result = typeof document.createElement('input').checkValidity == 'function'; if (result) { for (var i = 0; i < form.elements.length; i++) { var element = form.elements[i]; if (!element.checkValidity() && (!element.validationMessage || element.validationMessage === null || element.validationMessage === '')) { return false; } } } return result; } function sendReadNotice(){ if(unread_ids.length == 0) return; if(toggleStatus != 0) return; var msg = {'type':'read', 'msg_ids':unread_ids}; if(socket && socket.readyState == WebSocket.OPEN){ socket.send(JSON.stringify(msg)); unread_ids = []; } } function removeReadBadge(){ if(toggleStatus != 0) return; var badgeClasses = synalioDocument.getElementsByClassName('synalio-chat-window-notice-badge'); for(var i = 0; i < badgeClasses.length; i++){ badgeClasses[i].style.display = 'none'; } } function getCookie( name ) { var result = null; var cookieName = name + '='; var allcookies = synalioParentDocument.cookie; var position = allcookies.indexOf( cookieName ); if( position != -1 ) { var startIndex = position + cookieName.length; var endIndex = allcookies.indexOf( ';', startIndex ); if( endIndex == -1 ) { endIndex = allcookies.length; } result = decodeURIComponent( allcookies.substring( startIndex, endIndex ) ); } return result; } function isIpAddress(str) { let reg = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/ return reg.test(str) } function setCookie(doc, key, val, period, expires) { var cookie; if (expires) { cookie = key + '=' + val + ';expires=' + expires + ';path=/;'; } else { var maxAge = period || 2 * 365 * 24 * 60 * 60; cookie = key + '=' + val + ';max-age=' + maxAge + ';path=/;'; } if (!setCookie.domain) { let domainName = 'domain=.'; if (isIpAddress(location.hostname)) { setCookie.domain = location.hostname; domainName = 'domain=' } else { var components = location.hostname.split('.'); if (components.length > 2) { components.shift(); } setCookie.domain = components.join('.'); } doc.cookie = cookie + domainName + setCookie.domain; var savedVal = getCookie(key); if (savedVal != val) { setCookie.domain = location.hostname; doc.cookie = cookie + domainName + setCookie.domain; } } else { let domainName = 'domain=.'; if (isIpAddress(location.hostname)) { domainName = 'domain=' } doc.cookie = cookie + domainName + setCookie.domain; } } function setBadge(){ if(toggleStatus != 0 && unread_ids.length > 0){ var chatWindow = synalioDocument.getElementsByClassName("window-box")[0]; var badge; if(chatWindow.getAttribute('data-wtype') == 'img'){ badge = synalioDocument.getElementById('synalio-chat-window-notice-badge-img'); } else { badge = synalioDocument.getElementById('synalio-chat-window-notice-badge'); } if(badge){ badge.innerHTML = unread_ids.length; badge.parentElement.style.display = 'block'; } } } function toggleRtchatStatus(isRtchat) { var chat_window = synalioDocument.getElementsByClassName("window-box")[0]; var homeLink = synalioDocument.getElementById("home-link"); if (isRtchat) { isCancelling = false // synalioDocument.getElementById('synalio-chat-footer-rtchat').style.display = 'block'; chat_window.setAttribute("data-operation", "on"); chat_window.setAttribute("data-footer", "on"); updateChatBoxMobile(); if(homeLink){ homeLink.style.display = 'none'; } } else { // synalioDocument.getElementById('synalio-chat-footer-rtchat').style.display = 'none'; chat_window.setAttribute("data-operation", ""); chat_window.setAttribute("data-footer", ""); if(homeLink){ homeLink.style.cursor = 'pointer'; homeLink.style.display = ''; } if (sessionStorage.getItem("alwayshide") === 'true') { chat_window.setAttribute("data-footer", ""); } } // CHANGED // synalio.resize(windowElement.offsetHeight); } function overrideHideInputSetting(input_show_status) { var chat_window = synalioDocument.getElementsByClassName("window-box")[0]; var footerContainer = synalioDocument.getElementById('synalio-chat-footer-container'); var footMain = null; for (var i = 0; i < footerContainer.childNodes.length; i++) { if (footerContainer.childNodes[i].className == "foot-main") { footMain = footerContainer.childNodes[i]; footMain.style.display = ''; // Fix for IE11: don't show placeholder of chatbox-text-input on firsttime fixPlaceholderOnIE(); } } if (input_show_status === 1 ){ chat_window.setAttribute("data-footer", "on"); } else { chat_window.setAttribute("data-footer", ""); } synalio.resize(windowElement.offsetHeight); updateChatBoxMobile(); } function updateChatBoxMobile() { if (isMobile) { synalioDocument.getElementsByClassName('main-box')[0].style.height = 'calc(100vh - ' + (getElementHeight('header-box') + getElementHeight('foot-box')) + 'px)'; } } function isRtchat(){ return synalioDocument.getElementsByClassName('window-box')[0].getAttribute('data-operation') == 'on'; } function checkUrl(s) { if (s !== undefined && s != null){ var httpPrefix = 'http://'; var httpsPrefix = 'https://'; var str = s.replace(/\[.+\]/g, ''); if((str.length > httpPrefix.length && str.substr(0 ,httpPrefix.length) == httpPrefix) || (str.length > httpsPrefix.length && str.substr(0, httpsPrefix.length) == httpsPrefix)){ return true; } } return false; } function checkDemo(){ var demoValue = isDemo; var demoElem = synalioParentDocument.getElementById('synalio-demo'); if(demoElem){ try{ demoValue = parseInt(demoElem.value); }catch(ex){} } return demoValue; } smoothScr = { iterr : 20, // set timeout miliseconds ..decreased with 1ms for each iteration tm : null, //timeout local variable step : null, lastScrollTop: null, stopShow: function() { clearTimeout(this.tm); // stopp the timeout this.iterr = 15; // reset milisec iterator to original value }, anim : function (target, chatBody, chatHeader) // the main func { var step = (target.offsetTop - chatHeader.offsetHeight - chatBody.scrollTop) / 20.0; chatBody.scrollTop += step; if(this.iterr > 1) this.iterr -= 1; else this.itter = 0; if(this.lastScrollTop != chatBody.scrollTop && step > 1 && chatBody.scrollTop < target.offsetTop - chatHeader.offsetHeight){ this.lastScrollTop = chatBody.scrollTop; this.tm = window.setTimeout(function() { smoothScr.anim(target, chatBody, chatHeader); }, this.iterr); } else { this.stopShow(); } } }; toggleChatWindow = { closeType: design_close_type, initDisplayType: display_type, synalio: this, setting: { "chatH":600, "chatW":500, "chatHsp":100, "headerH":76, "footerH":64, "orignImgH":90, "orignImgW":170, }, closeMaxMin: function(e){ var self = this; var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; //極小からchatサイズに変型 windowBox.setAttribute('data-chatanime', 'max-min_chat'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "ChangeOpacityMaxMin"){ customChatSize(); windowBox.removeEventListener(animationEndEvent, f, false); } } })(1), false); if(logs.length == 0){ initData(); } }, closeMin: function(e){ //小さくなる //極小サイズに変型 var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; windowBox.setAttribute('data-chatanime', 'min_max-min'); if(!isMobile){ windowBox.addEventListener(transitionEndEvent, function(){ iframe.style.width = windowBox.offsetWidth + 'px'; }); customCloseSize('max-min'); } else { windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "ChangeOpacityBefoer"){ customCloseSize('max-min'); windowBox.removeEventListener(animationEndEvent, f, false); } } })(1), false); } }, closeTalk: function(e){ //極小サイズに変型 var self = this; var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; windowBox.setAttribute('data-chatanime', 'talk_max-min'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "setTimerOpacity" || e.animationName == "setTimerOpacity2" || e.animationName == "ChangeOpacityBefoer"){ customCloseSize('max-min'); if(!isMobile){ iframe.style.width = windowBox.offsetWidth + 'px'; } windowBox.removeEventListener(animationEndEvent, f, false); } } })(1), false); }, closeBox: function(e){ //極小サイズに変型 if(e){ e.preventDefault(); e.stopImmediatePropagation(); } var self = this; var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; getElement('main-box').style.overflow = 'hidden'; windowBox.setAttribute('data-chatanime', 'box_max-min'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "setTimerOpacity" || e.animationName == "ChangeOpacityBefoer"){ windowBox.removeEventListener(animationEndEvent,f,false); customCloseSize('max-min'); //$(".outer-talk-set-box").css({height: $(".over-talk-box").innerHeight(true) + "px"}); } } })(1),false); }, closeChat: function(e){ var self = this; var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; //chatサイズを閉じる if(isMobile){ if(this.closeType === 'img'){ windowBox.setAttribute('data-chatanime', 'chat_img'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "NoDispOpacity"){ if (isAutoDisplayBanner) { self.toggleCloseChat(iframe, windowBox); } else { customCloseSize('img'); } windowBox.removeEventListener(animationEndEvent,f,false); } } })(1), false); } else{ windowBox.setAttribute('data-chatanime', 'chat_max-min'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == 'NoDispOpacity'){ if (isAutoDisplayBanner) { self.toggleCloseChat(iframe, windowBox); } else { customCloseSize('max-min'); } windowBox.removeEventListener(animationEndEvent, f, false); } } })(1),false); } } else{ if(this.closeType === 'img'){ windowBox.setAttribute('data-chatanime', 'chat_img'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "setTimerOpacity"){ if (isAutoDisplayBanner) { self.toggleCloseChat(iframe, windowBox); } else { customCloseSize('max-min'); } windowBox.removeEventListener(animationEndEvent, f, false); }else if(e.animationName == "ChangeOpacityBefoer"){ if (isAutoDisplayBanner) { self.toggleCloseChat(iframe, windowBox); } else { customCloseSize('img'); } windowBox.removeEventListener(animationEndEvent, f, false); } } })(1),false); } else{ windowBox.setAttribute('data-chatanime', 'chat_max-min'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "setTimerOpacity"){ if (isAutoDisplayBanner) { self.toggleCloseChat(iframe, windowBox); } else { customCloseSize('max-min'); } windowBox.removeEventListener(animationEndEvent, f, false); }else if(e.animationName == "ChangeOpacityBefoer"){ if (isAutoDisplayBanner) { self.toggleCloseChat(iframe, windowBox); } else { customCloseSize('max-min'); } windowBox.removeEventListener(animationEndEvent, f, false); } } })(1),false); } } synalio.hideChat(); }, toggleCloseChat: function(iframe, windowBox){ windowBox.setAttribute('data-show', ''); if(!isMobile){ windowBox.setAttribute('data-first', ''); } windowBox.setAttribute('data-chatanime', ''); windowBox.removeAttribute('style'); iframe.style.display = 'none'; }, onCloseClick: function(e){ if(e && !(e.target.id.indexOf('close') != -1 || (e.target.parentElement && e.target.parentElement.id.indexOf('close') != -1))){ return false; } if(e){ e.stopPropagation(); } var self = this; var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; var displayType = windowBox.getAttribute('data-wtype'); if(displayType == 'max-min'){ this.closeMaxMin(e); } else if(displayType == 'min'){ this.closeMin(e); } else if(displayType == 'talk'){ this.closeTalk(e); } else if(displayType == 'box'){ this.closeBox(e); } else if(displayType == 'chat'){ this.closeChat(e); } if(displayType != 'max-min') { if(isMobile){ stopBodyScrolling(false); } } else { if(isMobile){ stopBodyScrolling(true); } } return false; }, onOpenClick: function(e){ if(e && (e.target.id.indexOf('close') != -1 || (e.target.parentElement && e.target.parentElement.id.indexOf('close') != -1))){ return false; } var self = this; var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; var displayType = windowBox.getAttribute('data-wtype') isClosedWindowChat = true; if(displayType == 'max-min'){ windowBox.setAttribute('data-chatanime', 'max-min_chat'); windowBox.addEventListener(animationEndEvent, customChatSize); } else if(displayType == 'min'){ windowBox.setAttribute('data-chatanime', 'min_chat'); windowBox.addEventListener(animationEndEvent, customChatSize, false); } else if(displayType == 'talk'){ if(isMobile){ windowBox.setAttribute('data-chatanime', 'talk_chat'); windowBox.addEventListener(animationEndEvent, customChatSize); }else{ // getElement('main-box').style.height = getElement('main-box').clientHeight + 'px'; windowBox.setAttribute('data-chatanime', 'talk_chat'); windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "setTimerOpacity2"){ getElement('main-box').removeAttribute('style'); customChatSize(); windowBox.removeEventListener(animationEndEvent, f, false); } } })(1),false); } } else if(displayType == 'box'){ if(e){ e.preventDefault(); e.stopImmediatePropagation(); } if(isMobile){ windowBox.setAttribute('data-chatanime', 'box_chat'); // windowBox.addEventListener(animationEndEvent, customChatSize); windowBox.addEventListener(animationEndEvent,(function(){ return function f(c){ if(c.animationName == "ChangeOpacityMaxMin"){ /*var mainBox = getElement('main-box'); mainBox.removeAttribute('style');*/ customChatSize(); windowBox.removeEventListener(animationEndEvent, f, false); } } })(1),false); }else{ windowBox.setAttribute('data-chatanime', 'box_chat'); windowBox.addEventListener('animationstart',function(c){ if(c.animationName == 'setTimerOpacity2'){ console.time('anim'); } }); windowBox.addEventListener(animationEndEvent,(function(){ return function f(c){ if(c.animationName == 'setTimerOpacity2'){ console.timeEnd('anim'); getElement('main-box').removeAttribute('style'); customChatSize(); windowBox.removeEventListener(animationEndEvent, f, false); } } })(1),false); //$(".main-box").css({height:$(".main-box").height() + "px"}); } } else if(displayType == 'img'){ windowBox.setAttribute('data-chatanime', 'img_chat'); windowBox.addEventListener(animationEndEvent, customChatSize, false); } }, initEvent: function(eventName, classNames, eventFunc){ for(var i = 0; i < classNames.length; i++){ var element = getElement(classNames[i]); if(element.firstElementChild && element.firstElementChild.tagName == 'a'){ element.firstElementChild.addEventListener(eventName, eventFunc, false); } else { element.addEventListener(eventName, eventFunc, false); } } }, initIframe: function(iframe, windowBox, retryCount){ var self = this; if(this.initDisplayType === 'img' && !closeImageLoaded){ if(!retryCount){ retryCount = 0; } else if(retryCount > 5){ return; } setTimeout(function(){ self.initIframe(iframe, windowBox, retryCount + 1); }, 1000) return; } if(isMobile){ if(this.initDisplayType === 'img'){ if (!isOpenedChat) { windowBox.style.width = closeImageWidth + 'px'; windowBox.style.height = closeImageHeight + closeImageBadgeHeight + 'px'; windowBox.style.padding = '0px'; if(iframe.style.visibility != 'hidden'){ windowBox.setAttribute('data-show', 'show'); } iframe.style.width = closeImageWidth + 'px'; iframe.style.height = closeImageHeight + closeImageBadgeHeight + 'px'; } }else{ if(iframe.style.visibility != 'hidden'){ windowBox.setAttribute('data-show', 'show'); } iframe.style.width = '100%'; iframe.style.height = !isFullScreen ? (windowBox.offsetHeight + 'px') : '100%'; } }else{ if(this.initDisplayType === 'img'){ if (!isOpenedChat) { windowBox.style.width = closeImageWidth + 'px'; windowBox.style.padding = '0px'; if(iframe.style.visibility != 'hidden'){ windowBox.setAttribute('data-show', 'show'); } iframe.style.width = closeImageWidth + 'px'; iframe.style.height = closeImageHeight + closeImageBadgeHeight + 'px'; windowBox.style.height = closeImageHeight + closeImageBadgeHeight + 'px'; } }else{ var delta = 0; if(this.initDisplayType == 'talk' && getElement('outer-talk-set-box').offsetHeight > 55){ // >= 2 lines of text delta = 20; } iframe.style.width = windowBox.offsetWidth + 'px'; windowBox.style.height = getElement('outer-box').offsetHeight + (windowBox.style.paddingTop ? windowBox.style.paddingTop.replace('px', '') : 10) * 2 + delta + 'px'; iframe.style.height = getElement('outer-box').offsetHeight + (windowBox.style.paddingTop ? windowBox.style.paddingTop.replace('px', '') : 10) * 2 + delta + 'px'; if(iframe.style.visibility != 'hidden'){ windowBox.setAttribute('data-show', 'show'); } } } }, initScrollEvents: function(iframe){ var s = { insideIframe: false } iframe.addEventListener('mouseenter', function(e) { s.insideIframe = true; s.scrollX = e.scrollX; s.scrollY = e.scrollY; }); iframe.addEventListener('mouseleave', function() { s.insideIframe = false; }); document.addEventListener('scroll', function(e) { setCurrentScrollPosition(); if (s.insideIframe){ try{ e.scrollTo(s.scrollX, s.scrollY); }catch(ex){} } else{ e.preventDefault(); } }); }, onCloseChatWindow: function() { let closeWindowChat = Date.now(); if (!localStorage.getItem('closeWindowChat')) { localStorage.setItem('closeWindowChat', closeWindowChat) if (naCloseChatOpened && synalioWindow.Nanalytics) { synalioWindow.Nanalytics('send','event', {category: 'chatbot', action: 'close', label: 'close_chatbot'}, {close_chatbot: '1'}); } } }, initEvents: function(iframe, windowBox){ let self = this; this.initEvent('click', ['btn-open-close'], function(e){ synalioParentDocument.body.style.position = objectCss.position; synalioParentDocument.body.style.width = objectCss.width; synalioParentDocument.body.style.overflow = objectCss.overflow; if (!synalioParentDocument.body.style.cssText){ synalioParentDocument.body.removeAttribute('style') } firstClick = false; objectCss = {}; self.onCloseChatWindow(); toggle(1, e); }); this.initEvent('click', ['header-box', 'main-box', 'inner-box-btn-box', 'outer-talk-set-box', 'outer-box-set-box', 'img-box'], function(e){ toggle(0, e); }); if(isMobile){ this.initScrollEvents(iframe); } synalioDocument.getElementsByClassName("over-talk-box")[0].addEventListener('scroll', onChatBodyScroll); }, init: function(){ var self = this; if (synalio.session_closed) { return; } var iframe = synalioParentDocument.getElementById('synalio-iframe'); var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; if(iframe.style.display == 'none'){ iframe.style.visibility = 'hidden'; iframe.style.display = ''; } this.initIframe(iframe, windowBox); var displayType = windowBox.getAttribute('data-wtype'); windowBox.setAttribute('data-pos', windowPosition); if(!isMobile && displayType != 'img'){ iframe.style.width = getWindowWidth() + 'px'; } var outerBoxSetBox = getElement('outer-box-set-box'); outerBoxSetBox.style.height = getElementHeight('outer-box-set-box') + 'px'; if(displayType === 'box'){ var mainBox = getElement('main-box'); mainBox.style.height = getElementHeight('main-box') + 'px'; if(!isMobile){ windowBox.style.height = (getElement('outer-box').offsetHeight + 40) + 'px'; iframe.style.height = (getElement('outer-box').offsetHeight + 40) + 'px'; } } else if(displayType === 'chat'){ windowBox.removeAttribute('style'); if(!isMobile){ iframe.style.height = getWindowHeight() + 'px'; } else { initMobileSize(iframe, windowBox); } } let iframeHeight = iframe.offsetHeight; iframe.style.height = 'calc(' + iframe.offsetHeight + 'px + ' + position_close_box_value + position_close_box_type + ')'; if(iframe.style.visibility == 'hidden'){ iframe.style.display = 'none'; iframe.style.visibility = ''; } //一発目のアニメーション判定 windowBox.addEventListener(animationEndEvent,(function(){ return function f(e){ if(e.animationName == "MoveBottomYRe"){ if (!isClosedWindowChat) { if (displayType !== 'img') { iframe.style.height = iframeHeight + 'px'; } else { iframe.style.height = windowBox.offsetHeight + 'px'; } iframe.style.bottom = position_close_box_value + position_close_box_type }; windowBox.removeEventListener(animationEndEvent, f, false); windowBox.setAttribute('data-first', true); scroll(1); if(isFullScreen){ toggle(0); } } } })(1),false); this.initEvents(iframe, windowBox); }, }; function createChatWindowIframe() { var iframe = document.createElement("iframe"); iframe.setAttribute("id", 'synalio-iframe'); iframe.setAttribute("scrolling", "no"); // // hiddenStyle = "display:none;"; // iframe.setAttribute("style", "border: 0px;background: none;" + hiddenStyle); // iframe.setAttribute("src", "//synalio.com/api/chatwindow?appid=26a0e54b727f425d9094f462d4ea44d6"); getOrCreateUserId(); var url = "//synalio.com/api/chatwindow"; var request = new XMLHttpRequest(); var chatwindowData = { 's': s, 'appid': "26a0e54b727f425d9094f462d4ea44d6", 'url': refererUrl }; chatwindowData['nanalytics'] = nanalyticsParams; if(isFullScreen){ chatwindowData['fs'] = 1; } request.open('POST', url); request.setRequestHeader('Content-Type', 'application/json'); request.send(JSON.stringify(chatwindowData)); request.responseType = "document"; request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { if(window.navigator.userAgent.toLowerCase().indexOf('firefox') != -1){ iframe.contentWindow.document.open('text/html', 'replace'); } else { iframe.contentWindow.document.open(); } var iframeHtml = '' + request.response.getElementsByTagName('html')[0].innerHTML + ''; iframe.contentWindow.document.write(iframeHtml); // iframe.contentWindow.document.write(new XMLSerializer().serializeToString(request.response)); iframe.contentWindow.document.close(); if (synalioWindow.Nanalytics) { var visualId = request.response.getElementById('synalio-chat-visual-id'); visualId = visualId ? visualId.value : ''; var visualCreativeId = request.response.getElementById('synalio-chat-visual-creative-id'); visualCreativeId = visualCreativeId ? visualCreativeId.value : '' synalioWindow.Nanalytics('send','event', {category: 'chatbot', action: 'show', label: 'show_chatbot'}, {show_chatbot: '1', visual_id:visualId, visual_creative_id:visualCreativeId}); } } }; var chat_window = document.createElement("div"); chat_window.appendChild(iframe); synalioParentDocument.body.appendChild(chat_window); } function loadRichMenu(){ if(!richMenu){ var richMenuToggle = getElement('switch-menu-btn-box'); richMenuToggle.style.display = 'none'; } else { toggleRichMenu(); synalioDocument.querySelectorAll(".rich-disp-btn-box span")[0].addEventListener("click", toggleRichMenu, false); synalioDocument.querySelector(".switch-menu-btn-box").addEventListener("click", toggleRichMenu, false); } } function toggleRichMenu(){ var windowBox = synalioDocument.querySelector('.window-box'); if(!windowBox){ setTimeout(function(){ toggleRichMenu(); }, 500); return; } var richmenu = synalioDocument.querySelector('.rich-menu'); var richmenuin = synalioDocument.querySelector('.rich-menu > div'); var richbtnbox = synalioDocument.querySelector('.sbtn-box'); var mainchatpad = synalioDocument.querySelector('.inner-talk-set[data-talktype="chat"]'); var outerbox = synalioDocument.querySelector('.over-talk-box'); var screenSize = getScreenSize(); if(!isMobile){ var richMenuWidth = getWindowWidth() - 40; }else { var richMenuWidth = mobileInnerWidth * screenSize.width / 100; } if(windowBox.getAttribute('data-richdisp') == 'on'){ richmenu.removeAttribute('style'); outerbox.removeAttribute('style'); mainchatpad.removeAttribute("style"); windowBox.setAttribute('data-richdisp', 'off'); }else { // var rH = Math.round((richdispw.clientWidth / 16) * 9) + 'px'; var rH = Math.round((richMenuWidth / 16) * 9) + 'px'; richbtnbox.style.height = richmenuin.style.height = richmenu.style.height = rH; outerbox.style.height = 'calc(100% - ' + rH + 1 + ')'; mainchatpad.style.paddingBottom = rH; windowBox.setAttribute('data-richdisp', 'on'); //めんどくさいからjqueryで書いちゃった // TODO: to be confirmed with Ishihara-san scrollRichMenu(); // $('.over-talk-box').animate({scrollTop: mainchatpad.clientHeight + 'px'}, 200); } if(!richMenuInit){ richMenuInit = true; var rH = Math.round((richMenuWidth / 16) * 9) + 'px'; richbtnbox.style.height = richmenuin.style.height = richmenu.style.height = rH; outerbox.style.height = 'calc(100% - ' + rH + 1 + ')'; showRichMenu(windowBox); } } function showRichMenu(windowBox){ windowBox.setAttribute('data-richdisp', 'on'); var richMenuImage = getElement('rich-bg-img'); richMenuImage.setAttribute('src', richMenu.image_url); var buttonsContainer = getElement('sbtn-box'); buttonsContainer.setAttribute('data-selectnum', richMenu.display); var decoClass = ''; for(var i = 0; i < richMenu.buttons.length; i++){ var btnVal1 = richMenu.buttons[i].type == 'text' ? richMenu.buttons[i].value.replace(/"/g,'"') : ''; var btnVal2 = richMenu.buttons[i].type == 'url' ? richMenu.buttons[i].value : richMenu.buttons[i].value.replace(/"/g,'"'); var btnVal3 = richMenu.buttons[i].type == 'url' && richMenu.buttons[i].value && richMenu.buttons[i].uri_target ? richMenu.buttons[i].uri_target : ''; var buttonValue = chat_message_rich_menu_button_tmpl.replace(/@1/g, btnVal1).replace(/@2/g, btnVal2).replace(/@3/g, decoClass).replace(/@4/g, btnVal3); buttonsContainer.appendChild(htmlToElement(buttonValue)); } } function scrollRichMenu(){ scroll(1); scrollRichMenuOnTop(); } function scrollRichMenuOnTop(count){ /* ensure scroll to bottom of above rich menu */ if(!count){ count = 0; } else if(count > 20){ return; } var chatBody = synalioDocument.getElementsByClassName("over-talk-box")[0]; setTimeout(function(){ chatBody.scrollTop += 20; scrollRichMenuOnTop(count + 1) }, 15); } /** carousel start **/ carousel = { data: {}, init: function(id){ this.data[id] = { carlist: null, carnum: null, listw: null, maxlistw: null, carpad: null, zsize: null, optionobj: null, changelate: null, beforemovex: null, startX: 0, scrollX: 0, scrollY: 0, peascrollY: 0, beforeMove: 0, nowMove: 0, moveX: null, rmoveflg: false, lmoveflg: false }; }, show: function(id){ this.init(id); var chatbase = synalioDocument.querySelectorAll('.over-talk-box')[0]; var outerbases = synalioDocument.querySelectorAll('.custom-outer-box'); var outerbase = outerbases[outerbases.length - 1]; var carbases = synalioDocument.querySelectorAll('[data-cbtype="carousel"]'); var carbase = carbases[carbases.length - 1]; var caruls = synalioDocument.getElementsByClassName('swiper-container'); var carul = caruls[caruls.length - 1]; this.data[id].carlist = carul.children; this.data[id].carnum = this.data[id].carlist.length; this.data[id].carpad = !isMobile ? 10 : (isFullScreen ? 40 : 10);;//list between size this.data[id].zsize = !isMobile ? 0.9 : (isFullScreen ? 0.8 : 0.85); this.data[id].changelate = 0.2; carbase.setAttribute('data-index', (this.data[id].carnum - 1)); carbase.setAttribute('data-active', 0); // main-box max width var listbase = synalioDocument.querySelector('.inner-talk-set[data-talktype="chat"]'); var screenSize = getScreenSize(); if(!isMobile){ var listwidth = this.data[id].listw = (getWindowWidth() - 100) * this.data[id].zsize - scrollBarWidth; outerbase.style.width = (getWindowWidth() - 40 - scrollBarWidth) + 'px'; outerbase.style.marginLeft = '-30px'; // from css calc(100% - 60px) var chatbaseWidth = parseInt(outerbase.style.width.replace('px', '')); }else { var chatbaseWidth = mobileInnerWidth * screenSize.width / 100; var listwidth = this.data[id].listw = chatbaseWidth * this.data[id].zsize; outerbase.style.width = chatbaseWidth + 'px'; //cssから切り替え outerbase.style.marginLeft = -0.08/2 * screenSize.width + 'px'; // from css calc(100% - 8vw) } if(this.data[id].carnum > 1){ if('ontouchstart' in document.documentElement){ carul.addEventListener('touchstart', carouselMouseDown, false); }else{ carul.addEventListener('mousedown', carouselMouseDown, false); } var optionobjParent = synalioDocument.getElementById('option-arr-box-' + id); var optionobj = optionobjParent.children; for(var i = 0 ; i < optionobj.length; i++){ optionobj[i].addEventListener("click", carouselChangeArrMove, false); } carbase.setAttribute('data-list-none', 'left'); }else{ carbase.setAttribute('data-list-none', 'all'); } carbase.style.width = this.data[id].maxlistw = (listwidth + this.data[id].carpad) * this.data[id].carnum - (this.data[id].carpad) + ((chatbaseWidth - listwidth) / 2) + 'px'; this.data[id].maxlistw = this.data[id].maxlistw.replace('px', ''); for(var i = 0 ; i < this.data[id].carnum; i++){ this.data[id].carlist[i].style.width = listwidth + 'px'; if(this.data[id].carlist[i].firstElementChild.classList.contains("header-block")){ this.data[id].carlist[i].firstElementChild.style.height = Math.round(listwidth / 16 * 9) + 'px'; this.data[id].carlist[i].lastElementChild.style.height = 'calc(100% - ' + this.data[id].carlist[i].firstElementChild.style.height.replace('px', '') + 'px)'; } } carul.style.marginLeft = (chatbaseWidth - listwidth) / 2 + 'px'; }, deleteButtons: function(){ var options = synalioDocument.getElementsByClassName('option-block'); while(options.length > 0){ if(options[0].parentNode){ options[0].parentNode.removeChild(options[0]); } } } }; function carouselMouseDown(e){ var id = this.getAttribute('data-id'); carousel.data[id].beforemovex = 0; this.classList.add('drag'); if(e.type === 'mousedown') { var event = e; }else{ var event = e.changedTouches[0]; } var tx = this.style.transform.split(',')[0]; if(tx != ""){ tx = tx.replace('translate3d(','').replace('px', ''); }else{ tx = 0; } carousel.data[id].startX = event.pageX - tx; carousel.data[id].startPageX = event.pageX; carousel.data[id].moveX = event.pageX - tx; carousel.data[id].scrollX = carousel.data[id].scrollY = 0; carousel.data[id].scrollX = event.pageX; carousel.data[id].scrollY = event.pageY; carousel.data[id].peascrollY = getElement('over-talk-box').scrollTop; var drag = synalioDocument.getElementById('custom-outer-box-' + id); drag.addEventListener('mouseup', carouselMouseUp, false); drag.addEventListener('mousemove', carouselMouseMove, false); drag.addEventListener('touchmove', carouselMouseMove, false); drag.addEventListener('mouseleave', carouselMouseUp, false); drag.addEventListener('touchleave', carouselMouseUp, false); drag.addEventListener('touchend', carouselMouseUp, false); } function carouselMouseMove(e){ var id = this.getAttribute('data-id'); var drag = synalioDocument.getElementById('swiper-container-' + id); if(e.type === 'mousemove') { var event = e; } else { var event = e.changedTouches[0]; } var tempx = event.pageX; var tempy = event.pageY; var absx = Math.round(Math.abs(tempx - carousel.data[id].scrollX)); var absy = Math.round(Math.abs(tempy - carousel.data[id].scrollY)); if(absx > absy){ drag.style.transform = 'translate3d(' + (event.pageX - carousel.data[id].moveX + 'px') + ',0,0)'; var carbase = synalioDocument.getElementById('custom-box-' + id); //changeActiveList(id, carbase, event.pageX - carousel.data[id].moveX); } } function carouselMouseUp(e){ var id = this.getAttribute('data-id'); if(e.pageX == undefined){ e.pageX = e.changedTouches[0].pageX; } if(e.type === 'mousemove' || e.type === 'mouseup' || e.type === 'mouseleave') { var event = e; }else { var event = e.changedTouches[0]; } var carbase = synalioDocument.getElementById('custom-box-' + id); changeActiveList(id, carbase, event.pageX - carousel.data[id].moveX,event.pageX); var drag = synalioDocument.getElementById('custom-outer-box-' + id); drag.removeEventListener('mouseup', carouselMouseUp, false); drag.removeEventListener('touchend', carouselMouseUp, false); drag.removeEventListener('mousemove', carouselMouseMove, false); drag.removeEventListener('touchmove', carouselMouseMove, false); drag.removeEventListener('mouseup', carouselMouseUp, false); drag.removeEventListener('touchend', carouselMouseUp, false); drag.removeEventListener('mouseleave', carouselMouseUp, false); drag.classList.remove('drag'); var carbase = synalioDocument.getElementById('custom-box-' + id); checkMoveMax(carbase); } function carouselChangeArrMove(e){ //e.preventDefault(); var tt = e.currentTarget; var id = this.getAttribute('data-id'); var carbase = synalioDocument.getElementById('custom-box-' + id); var nact = carbase.getAttribute('data-active'); if(tt.getAttribute('data-arr') == 'left'){//左に移動 changeActiveListArr(carbase, parseInt(nact) - 1); }else{//右に移動 changeActiveListArr(carbase, parseInt(nact) + 1); } } function setArrObj(carbase, t){ carbase.setAttribute('data-list-none', t); } function checkMoveMax(carbase){ var id = carbase.getAttribute('data-id'); var active = carbase.getAttribute('data-active'); var carul = synalioDocument.getElementById('swiper-container-' + id); carul.classList.add('caru-transition'); var carnum = carousel.data[id].carnum; if(active == 0 ){//max left list carul.style.transform = 'translate3d(0px,0,0)'; setArrObj(carbase, 'left'); }else if(parseInt(active) >= carnum - 1 ){//max right list carul.style.transform = 'translate3d(-' + (carousel.data[id].maxlistw - (carousel.data[id].listw + parseInt(carul.style.marginLeft.replace('px', '')))) + 'px,0,0)'; setArrObj(carbase, 'right'); }else{//other carul.style.transform = 'translate3d(-' + ((carousel.data[id].listw + carousel.data[id].carpad) * carbase.getAttribute('data-active')) + 'px,0,0)'; setArrObj(carbase, ''); } carousel.data[id].rmoveflg = false; carousel.data[id].lmoveflg = false; carul.addEventListener('transitionend', removeTransitionClass, false); } function removeTransitionClass(){ this.removeEventListener('transitionend', removeTransitionClass); this.classList.remove('caru-transition'); } function changeActiveListArr(carbase, l){ carbase.setAttribute('data-active', l); checkMoveMax(carbase); } /** * mx : trasnlateXの移動距離。 * **/ function changeActiveList(id, carbase, mx,_nowX){ var aindex; var now_active = parseInt(carbase.getAttribute("data-active")); var _margin = 50; if(carousel.data[id].startPageX < _nowX){// Left Card if((carousel.data[id].startPageX + _margin) < _nowX){ now_active += -1; } }else{//Right Crad if((carousel.data[id].startPageX - _margin) > _nowX){ now_active += 1; } } if(now_active < 0){ now_active = 0; } if(now_active >= carousel.data[id].carnum){ now_active = carousel.data[id].carnum - 1; } aindex = now_active; if(aindex !== undefined){ carbase.setAttribute('data-active', aindex); } } /** carousel end **/ return { onFocusInput: function(){ setFocusInput(true); }, onBlurInput: function(){ setFocusInput(false); }, onLoadEvent: function(){ if (!synalioWindow.Nanalytics && nanalyticsRetryCount < 10) { nanalyticsRetryCount++; setTimeout(function() { synalio.onLoadEvent(); }, 100); return; } if(window.parent){ // In case script is embeded in iframe synalioParentDocument = window.parent.document; synalioParentWindow = window.parent } else { synalioParentDocument = document; synalioParentWindow = window; } getOrCreateUserId(); var isDemoPage = window.location.pathname === '/demo' ? 1 : 0; const gambitGalleryIsInView = function (el) { if (el) { const scroll = window.scrollY || window.pageYOffset const boundsTop = el.getBoundingClientRect().top + scroll const viewport = { top: scroll, bottom: scroll + window.innerHeight, }; const bounds = { top: boundsTop, bottom: boundsTop + el.clientHeight, }; return ( bounds.bottom >= viewport.top && bounds.bottom <= viewport.bottom ) || ( bounds.top <= viewport.bottom && bounds.top >= viewport.top ); } else { return false } }; var createWindowAction = function() { if (createWindowAction.wasCalled) { return; } createWindowAction.wasCalled = true; if (isDemoPage === 1 || isPublish === 1) { hiddenStyle = "display:none;"; var is_open = getCookie('r_window'); var displayTime = 0; hiddenStyle = ""; if (is_open === 'on') { createChatWindowIframe() } else { setTimeout(createChatWindowIframe, displayTime * 1000); } } else { isHideChatBox = true } } if (synalioWindow.Nanalytics) { synalioWindow.Nanalytics('get',function(params) { updateNanalyticsParams(params); createWindowAction(); }); setTimeout(function () { createWindowAction(); }, 500); } else { createWindowAction(); } }, loadChatVisual: function(design) { design_height_mobile = design.height_mobile; design_button_color = design.button_color; design_text_color2 = design.text_color2; design_sub_color = design.sub_color; design_width = design.width; design_height = design.height; design_width_mobile = design.width_mobile; design_close_type = design.close_type; display_type = design.display_type; toggleChatWindow.closeType = design.close_type; toggleChatWindow.initDisplayType = design.display_type; }, changeIframeStyle: function(){ synalioDocument = synalioParentDocument.getElementById('synalio-iframe').contentDocument; windowElement = synalioDocument.getElementsByClassName("window-box")[0]; header = synalioDocument.getElementsByClassName("header-box")[0]; body = synalioDocument.getElementsByClassName("main-box")[0]; bodyInner = synalioDocument.getElementsByClassName("over-talk-box")[0]; bodyOuter = synalioDocument.getElementsByClassName("outer-box")[0]; footer = synalioDocument.getElementsByClassName("foot-box")[0]; synalioParentDocument.getElementById('synalio-iframe').setAttribute("style", iframeStyle + hiddenStyle); scrollBarWidth = getScrollBarWidth(); toggleChatWindow.init(); windowElement.style.visibility = "hidden"; var ta = synalioDocument.getElementById("synalio-chat-text-input"); // CHANGED ta.addEventListener("input", resizeTextArea); ta.innerHTML = ''; synalioParentWindow.addEventListener('resize', function(e){ resizeFitBrowser(e.target); }); }, onAfterIframeLoad: function(){ getLogs(s, sessionId); synalio.onCompleteLoad(); synalio.onCheckClosedWindowChat(); /* var is_open = getCookie('r_window'); if(is_open === 'on') { if (canOpenOnReceiveLog) { isAutoDisplayBanner = true; synalio.toggle(0); } }*/ }, onKeyPressed: function(e){ var mode = -1; if (e.keyCode == 13 && (e.shiftKey || e.metaKey || e.ctrlKey)){ mode = keyPressMode == 1 ? 1 : 0; e.preventDefault(); } else if (e.keyCode == 13) { mode = keyPressMode == 1 ? 0 : 1; e.preventDefault(); } if (mode == 0){ var chat_input = synalioDocument.getElementById("synalio-chat-text-input"); if (chat_input.value){ var msg = chat_input.value; sendMessage(msg); chat_input.value = ""; deleteReplyOptions(); deleteSubmitForms(); resetMultiLine(); } // CHANGED // e.target.style.height = textAreaHeight + 'px'; // resizeTextArea(e); } else if (mode == 1) { var chat_input = synalioDocument.getElementById("synalio-chat-text-input"); chat_input.value += "\n"; // CHANGED resizeTextArea(e); } }, onPressLink: function(e){ var dataValue = e.getAttribute('data-val'); var dataValueTarget = e.getAttribute('data-val-target'); var isUrl = checkUrl(dataValue); if(richMenu && richMenu.auto_close){ var windowBox = getElement('window-box'); if(windowBox.getAttribute('data-richdisp') == 'on'){ toggleRichMenu(); } } if(isUrl){ var postData = { 'event_type': 'chat_message_sent', 'event_data': { 'unique_id': appid, 'user_id': s, "behaviour": "link_clicked", "message": "[link]" + e.getAttribute('data-val-label'), "url": dataValue } }; sendAnalyticsData(postData); openLink(dataValue, dataValueTarget); setCookie(synalioParentDocument, 'r_window', 'off', 1800); return; } sendMessage(dataValue, false, true); deleteReplyOptions(); deleteSubmitForms(); carousel.deleteButtons(); }, onPressCloseRtchat: function(){ if (!isCancelling) { isCancelling = true; var msg = {'type':'close_rtchat'}; if(checkDemo() == 1){ msg['demo'] = 1; } if(socket && socket.readyState == WebSocket.OPEN){ socket.send(JSON.stringify(msg)); } return false; } }, toggle: function(e, event){ if (navigator.userAgent.match(/(iPhone|iPod|iPad)/i)) { setTimeout(function(){ updateChatBoxMobile(); },500) } var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; if(windowBox.getAttribute('data-wtype') != 'max-min'){ if(toggleStatus == e){ return; } toggleStatus = e; } else { toggleStatus = 0; } var r_window = toggleStatus == 1 ? "off" : "on"; setCookie(synalioParentDocument, 'r_window', r_window, 1800); if(e == 1){ if(!event){ toggleChatWindow.closeChat(event); } else { toggleChatWindow.onCloseClick(event); } } else if (!isHideChatBox) { isOpenedChat = true; if(!event){ var iframe = synalioParentDocument.getElementById('synalio-iframe') var windowBox = synalioDocument.getElementsByClassName('window-box')[0]; iframe.style.display = ''; windowBox.setAttribute('data-show', 'show'); var contentElements = synalioDocument.getElementsByClassName('chat-message-body'); for(var i = 0; i < contentElements.length; i++){ if(!contentElements[i].getAttribute('data-talkshow')){ contentElements[i].setAttribute('data-talkshow', 'talkshow'); } } resizeFitBrowser(synalioParentWindow); toggleChatWindow.onOpenClick(event); } else { toggleChatWindow.onOpenClick(event); naCloseChatOpened = false; if (synalioWindow.Nanalytics) { synalioWindow.Nanalytics('send','event', {category:'chatbot', action:'click', label:'click_chatbot'}, {click_chatbot: '1'}); } } initData(); // Scroll // CHANGED if(!is_toggled){ // new design alway need always scroll is_toggled = true; // scroll(1); } } // Send unread ids sendReadNotice(); // Remove unread badge // CHANGED removeReadBadge(); synalio.onCompleteToggle(e); }, onPressButton: function(){ var chat_input = synalioDocument.getElementById("synalio-chat-text-input"); if (chat_input.value){ var msg = chat_input.value; sendMessage(msg); deleteSubmitForms(); chat_input.value = ""; var ta = synalioDocument.getElementById("synalio-chat-text-input"); ta.style.height = textAreaHeight + 'px'; deleteReplyOptions(); carousel.deleteButtons(); // CHANGED // synalio.resize(windowElement.offsetHeight); } sendReadNotice(); }, onPressCheckbox: function(){ var chat_send_type = synalioDocument.getElementById("synalio-chat-send-type-checkbox"); var chat_input = synalioDocument.getElementById("synalio-chat-text-input") if(chat_send_type.checked){ keyPressMode = 1; chat_input.placeholder = chat_input.placeholder.replace("Shift + Enter", "Enter"); } else { keyPressMode = 0; chat_input.placeholder = chat_input.placeholder.replace("Enter", "Shift + Enter"); } }, onPressUpload: function(imagePath, file, mime_type){ var img = ''; writeMessage(htmlToElement(decorateMessage('r', chat_msg_r_tmpl).replace(/@1/g, img))); scroll(1); sendMessage('画像受信', true, false, false, file, mime_type) }, onPressGoHome: function(){ sessionStorage.removeItem("alwayshide") if (!isInRtchat()) { sendMessage(backToHome, true, true, null, null, null, {'home': 1}); deleteReplyOptions(); deleteSubmitForms(); carousel.deleteButtons(); } }, onCloseImageLoad: function(e){ if(design_close_type != 'img'){ return 0; } var img = new Image(); img.onload = function() { newWidth = this.width / 2; newHeight = this.height / 2; iframeStyleWidthClose = "width:" + newWidth + "px;"; iframeStyleHeightClose = "height: " + newHeight + "px;"; iframeStyleHeightImgClose = iframeStyleHeightClose; closeImageWidth = newWidth; closeImageHeight = newHeight; closeImageLoaded = true; } img.src = e.target.src; }, onCompleteWriteMessage: function(responses){ }, onCompleteToggle: function(e){ }, onCompleteLoad: function(){ }, onCheckClosedWindowChat: function() { let windowBox = synalioDocument.getElementsByClassName('window-box')[0]; let displayType = windowBox.getAttribute('data-wtype'); let closeWindowChat = localStorage.getItem('closeWindowChat'); windowBox.style.visibility = "visible"; if (closeWindowChat) { let now = Date.now(); let diffTime = now - closeWindowChat; if (diffTime > 3 * 3600 * 1000) { localStorage.removeItem('closeWindowChat') if (displayType !== 'img') { naCloseChatOpened = true; } isClosedWindowChat = false; } else { if (displayType !== 'img') { isClosedWindowChat = true; customCloseSize('max-min'); } } } else if (displayType !== 'img') { naCloseChatOpened = true; } }, resize: function(chatWindowHeight){ // body.style.height = (chatWindowHeight - header.offsetHeight - footer.offsetHeight) + "px"; }, onFormChanged: function(form){ if (!form || form.nodeName !== "FORM") { return; } var i, j, q = [], checkboxDict = {}, selectboxDict = {}, radioDict = {}; for (i = form.elements.length - 1; i >= 0; i = i - 1) { if (form.elements[i].name === "") { continue; } if(form.elements[i].nodeName == 'INPUT'){ var input_type = form.elements[i].getAttribute('type'); if(input_type == 'checkbox'){ if(!(form.elements[i].name in checkboxDict)){ checkboxDict[form.elements[i].name] = []; } if (form.elements[i].checked) { checkboxDict[form.elements[i].name].push(encodeURIComponent(form.elements[i].value)); } if (errorCheckbox) { errorCheckbox.setCustomValidity(''); errorCheckbox = null; } } else if(input_type == 'radio'){ if(!(form.elements[i].name in radioDict)){ radioDict[form.elements[i].name] = ''; } if (form.elements[i].checked) { radioDict[form.elements[i].name] = encodeURIComponent(form.elements[i].value); } } else{ q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); } } else if(form.elements[i].nodeName == 'TEXTAREA'){ q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); } else if(form.elements[i].nodeName == 'SELECT'){ if (form.elements[i].type == 'select-one') { q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); } else if (form.elements[i].type == 'select-multiple'){ if(!(form.elements[i].name in selectboxDict)){ selectboxDict[form.elements[i].name] = []; } for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) { if (form.elements[i].options[j].selected) { selectboxDict[form.elements[i].name].push(encodeURIComponent(form.elements[i].value)); } } } } else if(form.elements[i].nodeName == 'BUTTON'){ var input_type = form.elements[i].getAttribute('type'); if (input_type == 'button') { q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value)); } } } for(var checkboxName in checkboxDict){ q.push("checkbox_" + checkboxName + "=" + JSON.stringify(checkboxDict[checkboxName])); } for(var selectboxName in selectboxDict){ q.push("selectbox_" + selectboxName + "=" + JSON.stringify(selectboxDict[selectboxName])); } for(var radioName in radioDict){ q.push(radioName + "=" + radioDict[radioName]); } var data = q.join("&"); synalioDocument.getElementById(form.getAttribute('name') + '-form-data').value = data; }, onSubmitForm: function(submitComponent){ var formName = submitComponent.getAttribute("form-name"); var form = synalioDocument.getElementById(formName); if(!form || !updateCheckboxCustomValidity(form) || !form.checkValidity()){ return validateFormFields(form) } var formDataId = submitComponent.getAttribute("form-data-id"); var formData = synalioDocument.getElementById(formDataId).value; if(!formData || formData === ''){ synalio.onFormChanged(form); formData = synalioDocument.getElementById(formDataId).value; } if(formData){ var msg = '##form:' + formName + '##' + formData; sendMessage(msg, true); deleteSubmitForms(); } deleteReplyOptions(); return false; }, onFocusEvent: function(){ sendReadNotice(); var windowBox = synalioDocument.querySelector('.window-box'); if(windowBox.getAttribute('data-richdisp') == 'on'){ toggleRichMenu(); } }, showCSForm: function(){ var ratingElements = synalioDocument.getElementsByClassName("cs-rating"); for(var i = 0; i < ratingElements.length; i++){ if(ratingElements[i].style.display != 'none'){ var removeNode = ratingElements[i].parentNode.parentNode.parentNode; removeNode.parentNode.removeChild(removeNode); } } writeMessage(htmlToElement(chat_cs_form_tmpl), true); scroll(1); setTimeout(function(){ stopLoading(); scroll(1); }, loadingInterval); }, onSubmitCSForm: function(){ var csForm = synalioDocument.getElementById('cs-form'); var formData = synalioDocument.getElementById('cs-form-form-data').value; var params = {'s': s}; if(formData){ var fields = formData.split('&'); for(var i = 0; i < fields.length; i++){ var nameValue = fields[i].split('='); params[nameValue[0]] = nameValue[1]; } } var ratingElements = synalioDocument.getElementsByClassName("cs-rating"); if(ratingElements.length > 0){ ratingElements[ratingElements.length - 1].style.display = 'none'; } var ratingDoneElements = synalioDocument.getElementsByClassName("cs-rating-done") if(ratingDoneElements.length > 0){ ratingDoneElements[ratingDoneElements.length - 1].style.display = 'block'; } if(checkDemo() == 1){ params['demo'] = 1; } sendSatisfactionSurvey(params); return false; }, onSubmitFeedbackForm: function(value, id){ var action = synalioDocument.getElementById('feedback-form-form-data-action-'+id).value; var state = synalioDocument.getElementById('feedback-form-form-data-state-'+id).value; var params = {'s': s}; params['feedback'] = value; params['action'] = action; params['state'] = state; params['feedback_log_id'] = id; var feedbackElements = synalioDocument.getElementsByClassName("feedback-form-"+id); if(feedbackElements.length > 0){ feedbackElements[feedbackElements.length - 1].style.display = 'none'; } var responseDoneElements = synalioDocument.getElementsByClassName("feedback-done-"+id) if(responseDoneElements.length > 0){ responseDoneElements[responseDoneElements.length - 1].style.display = 'block'; } if(checkDemo() == 1){ params['demo'] = 1; } sendFeedbackResponse(params); return false; }, addExtVal: function(key, val){ ext[key] = val; }, hideChat: function() { }, sendSessionCloseChat: function() { sendMessage("close-session", true, true, null, null, null, {'session_closed': 1}); } }; })(); var synalioWindow = window.parent ? window.parent : window; // Load Chat window if(document.readyState == 'complete'){ synalio.onLoadEvent(); } else { synalioWindow.addEventListener('load', synalio.onLoadEvent, true); } // synalioWindow.addEventListener('focus', synalio.onFocusEvent);