
/*
Cypress will embed our webpage into aut-iframe.
*/

var secCHUAPlatformVersion = 'unknown';
if (navigator.userAgentData && navigator.userAgentData.getHighEntropyValues) {
  navigator.userAgentData.getHighEntropyValues(
    ['platform', 'platformVersion'],
  ).then(function(ua) {
      if (ua && ua.platformVersion) {
        secCHUAPlatformVersion = ua.platformVersion;
      }
    }
  );
}

var cypressIframes = window.top.document.getElementsByClassName("aut-iframe");
var synalio = (function(){
    var isHideChatting = 0;
    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 chatbox_zindex = '999999997';
    var hide_input = false;
    
        hide_input = true;
    
    var show_rtchat_survey = false;
    
    // var design_close_type = '';
    var design_close_type = 'img';
    var display_type = 'box';
    var isClosedWindowChat = false;
    var currentPageParams = getUrlParams(window.location.href);
    var currentPageHasParam = hasParam(currentPageParams);
    var nonce = '';

    var firstClick = false;
    var cssText = '';
    var objectCss = {};
    var positionTimeOut = null;
    var isHideChatBox = false;
    var isAutoDisplayBanner = false;
    var isOpenedChat = false;
    var feedbackBtnFixWidth = '165px';
    var display_as_modal = false;
    var no_minimize_visual = false;
    var cookie_modal_key = 'as_modal';
    var isOffline = false;
    const threeHourTimestamp = 3 * 3600 * 1000;
    // for case open link
    var cookie_modal_key_bk = 'as_modal_bk';
    

    
        
            var iframeStylePosition = "left: auto;right: 0px;";
            var windowPosition = "right";
        
        
        var iframeStyle = "z-index:" + chatbox_zindex + ";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 = '0px';
    var userState;
    var autoOpenTime = 0;
    var isMobile = false;
    var isTabLetOrMobile = 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 closeImageMinimizeHeight = 15; // 15 is spacing for close visual icon
    var initFooterHeight;
    var loadingInterval = 1000;
    var appid = "880e0d55cf6a4afd9b67ee06d1fe176d";
    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://d2ixvq6dqmuoso.cloudfront.net/9e13a23/static/img/chat/chatbot_no_character.png";
    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 xhr;
    var xhr_page;
    var xhr_state;
    var isHttpLoadingStarted;
    var httpLoadingTimer;
    var reservation;
    var reservation_autoreplies = [];
    var countInterval = 0;
    var idInterval = null;
    var skipReservation = false;
    var retryCount = 0;
    var hiddenStyle = "";
    var backToHome = "メニューに戻る";
    var ext = {};
    var json = "None";
    var jsonInheritanceParams = "None";
    var cookies = (json !== 'None') ? JSON.parse(json.replace(/'/g, '"')) : [];
    var inheritanceParams = (jsonInheritanceParams !== 'None' && jsonInheritanceParams > '') ? getInheritanceParams(JSON.parse(jsonInheritanceParams.replace(/'/g, '"'))) : [];
    var needProcessParams = getNeedProcessParams();
    var errorCheckbox;
    var errorCheckboxMessage = "チェックを入れてください";
    var carouselLastId = 0;
    var scrollBarWidth = 20;
    var mobileInnerWidth = isFullScreen ? 100 : 89.33333; // %
    var isSentFinishSignalAtLoading = false;

    var currentScrollPosition = {};
    var isFocusInput = false;
    ///Action suggestion
    var isShowSuggestion = false;
    var delayThreshold = 5000; //3000ms delay threshold to determint when should call api after last key typed.
    var currentSuggestionLine = -1;
    var suggestionLength = 0;
    var lastInputText = null;
    var actionGroupName = null;
    ///End Action suggestion

var chat_msg_common_tmpl = '<div class="common-talk-box chat-message-body">	@1</div>';	var chat_msg_l_tmpl = '<div class="left-talk-box chat-message-body" data-loading="off">    <div class="loading-box"><span>.</span><span>.</span><span>.</span></div>    <div class="chat-block" data-test="chat-block" onclick="parent.synalio.onPressMessageLink(this)">        @1    </div></div>';    var chat_msg_l_img_tmpl = '<div class="left-talk-box chat-message-body" data-loading="off">    <div class="loading-box"><span>.</span><span>.</span><span>.</span></div>    <div class="chat-block" data-test="chat-block" onclick="parent.synalio.onPressMessageLink(this)">        <img src="@1" />    </div></div>';    var chat_msg_r_tmpl = '<div class="right-talk-box chat-message-body">  <div class="chat-block" data-test="chat-block">      @1  </div></div>';    var chat_msg_c_tmpl = '<div class="choice-block reply-option @3 @7" style="@8 background-color:@5;color:@6;" onclick="parent.synalio.onPressLink(this)" data-val="@2" data-val-label="@1" data-val-target="@4" style="cursor:pointer;">    <span>@1</span></div>';    var chat_msg_c_img_tmpl = '<div class="reply-option synalio-chat-message-button-image" onclick="parent.synalio.onPressLink(this)" data-val="@2" data-val-target="@4" data-val-label="@9">    <img src="@1" /></div>';    var chat_reply_wrap = '<div class="left-talk-box reply-options chat-message-body">  @1</div>';    var chat_loading_tmpl = '<div class="left-talk-box chat-message-body" data-loading="on" data-talkshow="talkshow">	<div class="loading-box"><span>.</span><span>.</span><span>.</span></div></div>';    var chat_msg_f_tmpl = '<div class="left-talk-box chat-message-body" data-loading="off">	<div class="loading-box"><span>.</span><span>.</span><span>.</span></div>    <div class="form-block">	    <form id="@2" name="@2" class="synalio-chat-form" onChange="parent.synalio.onFormChanged(this)">	        @1	        <div class="chat-form-group">	            <button class="btn btn-send" form-name="@2" form-data-id="@2-form-data" onClick="return parent.synalio.onSubmitForm(this)">送信</button>	        </div>	    </form>	    <input type="hidden" id="@2-form-data" />	</div></div>';    var chat_msg_f_edit_button_tmpl = '<div class="left-talk-box chat-message-body" data-loading="off">	<div class="loading-box"><span>.</span><span>.</span><span>.</span></div>    <div class="form-block">	    <form id="@2" name="@2" class="synalio-chat-form" onChange="parent.synalio.onFormChanged(this)">	        @1	    </form>	    <input type="hidden" id="@2-form-data" />	</div></div>';    var chat_cs_form_tmpl = '<div class="left-talk-box chat-message-body" data-loading="off">	<div class="loading-box"><span>.</span><span>.</span><span>.</span></div>	<div class="form-block">		<form id="cs-form" name="cs-form" class="synalio-chat-form" style="margin-bottom: 8px; font-size: 13px;" onChange="parent.synalio.onFormChanged(this)">		    <div class="chat-form-group cs-rating" id="rating">		        <div class="chat-form-group" style="">		            ご利用ありがとうございます。<br>よろしければ、今後の改善のため、オペレータに対する評価をお願いいたします。		        </div>		        <div class="chat-form-group">		            <label>評価：</label>		            <div style="font-size:13px;margin-top:5px;">						<label style="display:inline-block;"><input type="radio" name="evaluation" value="5">満足</label>						<label style="display:inline-block;"><input type="radio" name="evaluation" value="4">やや満足</label>						<label style="display:inline-block;"><input type="radio" name="evaluation" value="3">普通</label>						<label style="display:inline-block;"><input type="radio" name="evaluation" value="2">やや不満</label>						<label style="display:inline-block;"><input type="radio" name="evaluation" value="1">不満</label>		            </div>		        </div>		        <div class="chat-form-group">		            <label>自由コメント：</label>		            <textarea name="freeComment"></textarea>		        </div>		        <div class="chat-form-group" style="text-align:center;">		            <button class="btn btn-send" onclick="return parent.synalio.onSubmitCSForm()" style="width:150px;">送信</button>		        </div>		    </div>		    <div class="chat-form-group cs-rating-done" id="rating-done" style="display:none; margin-top: 0">		        評価ありがとうございます。<br/>今後の改善に役立たせていきます。		    </div>		    <input type="hidden" id="cs-form-form-data" />		</form>	</div></div>';    var chat_message_carousel_tmpl = '<div id="custom-outer-box-@1" class="custom-outer-box chat-message-body" data-id="@1" data-talkshow="talkshow" data-loading="complete">  <div id="custom-box-@1" class="custom-box" data-id="@1" data-cbtype="carousel" data-list-none="">    <ul id="swiper-container-@1" data-id="@1" class="swiper-container">    	@2    </ul>  </div>  <div id="option-arr-box-@1" class="option-arr-box">    <div class="arr-left" data-id="@1" data-arr="left"><span><</span></div>    <div class="arr-right" data-id="@1" data-arr="right"><span>></span></div>  </div></div>';    var chat_message_carousel_item_tmpl = '<li class="car-box">	@3	<div class="inner-body-box">		<div class="text-block">	  		<p class="main-text">@1</p>	  		<p>@2</p>		</div>		<div class="option-block">			@4		</div>	</div></li>';    var chat_message_carousel_item_image_tmpl = '<div class="header-block" style="background: url(@1); background-repeat: no-repeat;background-position: center; background-size: @2; @3" @4></div>';    var chat_message_carousel_button_tmpl = '<div class="btn-box" @5 onclick="parent.synalio.onPressLink(this)" data-val="@2" data-val-label="@1" data-val-target="@4" style="cursor:pointer;">	<span>@1</span></div>';    var chat_message_rich_menu_button_tmpl = '<div class="select-btn" onclick="parent.synalio.onPressLink(this)" data-val="@2" data-val-label="@1" data-val-target="@4" style="cursor:pointer;"></div>';    var chat_feedback_form_tmpl = '<div class="form-block" style="padding:0;margin:auto;">    <form id="cs-form" name="feedback-form-@8" class="synalio-chat-form" style="border:0;font-size:13px;" onChange="parent.synalio.onFormChanged(this)">        <div class="chat-form-group">            <div class="chat-form-group feedback-form" style="padding: 20px;background: #fafafa;text-align: center;">                <div class="feedback-form-@8 feedback_form_new">                    <label>@2</label>                    <div style="font-size:13px;margin-top:5px;text-align:center;">                        <button class="btn btn-send feedbackBtn-@8" onclick="return parent.synalio.onSubmitFeedbackForm(1, @8)">@3</button>                        <button class="btn btn-send feedbackBtn-@8" onclick="return parent.synalio.onSubmitFeedbackForm(2, @8)">@4</button>                    </div>                </div>                <div class="chat-form-group feedback-done-@8" id="feedback-done" style="font-size:13px;margin-top:5px;display:none;">                    @5                </div>            </div>        </div>        <input type="hidden" id="feedback-form-form-data-action-@8" value="@6"/>        <input type="hidden" id="feedback-form-form-data-state-@8" value="@7"/>    </form></div>';    var chat_suggestion_line_tmpl = '<p class="suggestion-line" data-text="@3" onClick="parent.synalio.onSuggestionLineSelect(@2)"                                      　onMouseOver="parent.synalio.onSuggestionLineHover(event.target)">  @1</p>';    var chat_message_markdown_tmpl = '<div class="left-talk-box chat-message-body" data-loading="off">  <div class="loading-box"><span>.</span><span>.</span><span>.</span></div>  <div class="chat-bot markdown-body">    @1  </div></div>';

    var chat_msg_f_names = [];
    var btnCharLen = 11;
    var maxConvNum = 99;
    var isDemo = 0;
    var isPublish = 1;
    var s = '';
    var demo_scenario_id = -1;
    var scenario_id = 0;
    var canOpenOnReceiveLog = true;
    var refererUrl = location.href;

    var cntKey = '_rslgvry_conv_cnt';
    var sessionId = '';
    var sessionIdChanged = false;
    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 getNeedProcessParams() {
        var needProcess = {};
        if (currentPageHasParam && inheritanceParams.length > 0) {
            for (pName in currentPageParams) {
                if (inheritanceParams.indexOf(pName) > -1) {
                    needProcess[pName] = currentPageParams[pName];
                }
            }
        }
        return needProcess;
    }

    function getInheritanceParams(jsonParams) {
        params = [];
        for (var i = 0; i < jsonParams.length; i++) {
            params.push(jsonParams[i].param);
        }
        return params;
    }

    function getUrlParams(url) {
        var params = {};
        var parser = document.createElement('a');
        parser.href = url;
        var query = parser.search.substring(1);
        if (query > '') {
            var vars = query.split('&');
            for (var i = 0; i < vars.length; i++) {
                if (typeof vars[i] !== undefined && vars[i].indexOf('=') >= 0) {
                    var pair = vars[i].split('=');
                    var param_name = pair[0].replace('amp;', '');
                    params[param_name] = decodeURIComponent(pair[1]);
                }
            }
        }
        return params;
    }

    function hasParam(objParams) {
        var hasParam = false;
        for (key in objParams) {
            if (objParams.hasOwnProperty(key)) {
                hasParam = true;
                break;
            }
        }
        return hasParam;
    }

    function updateLinksInHTML(html) {
        // no pram need process
        if (needProcessParams.length == 0) {
            return html;
        }

        var regex = /href\s*=\s*(['"])(https?:\/\/.+?)\1/ig;
        var link;
        var allLink = [];
        var allHref = [];
        while((link = regex.exec(html)) !== null) {
            if (link > '') {
                allHref.push(link[0]);
                allLink.push(link[2]);
            }
        }
        for (var i = 0; i < allLink.length; i++) {
            var addParamStr = createParamQS(allLink[i], needProcessParams);
            if (addParamStr > '') {
                var newLink = allLink[i] + addParamStr;
                var newHref = allHref[i].replace(allLink[i], newLink);
                html = html.replace(allHref[i], newHref);
            }
        }
        return html;
    }

    function createParamQS(url, needProcessParams) {
        var addParamStr = '';
        var linkParams = getUrlParams(url);
        var linkHasParam = hasParam(linkParams);
        if (linkHasParam) {
            for (addParam in needProcessParams) {
                if (addParam in linkParams) {
                    continue;
                }
                addParamStr = addParamStr + '&' + addParam + '=' + needProcessParams[addParam];
            }
        } else {
            for (addParam in needProcessParams) {
                var andConnect = (addParamStr > '') ? '&' : '';
                addParamStr = addParamStr + andConnect + addParam + '=' + needProcessParams[addParam];
            }
            if (addParamStr > '') {
                addParamStr = '?' + addParamStr;
            }
        }
        return decodeURIComponent(addParamStr);
    }

    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) {
        var storeSessionId = localStorage.getItem("synalio.nasid");
        if (storeSessionId != params.session_id) {
            sessionIdChanged = true;
            localStorage.setItem("synalio.nasid", params.session_id);
        }

        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');
        html = updateLinksInHTML(html);
        template.innerHTML = html;
        if(template.content) {
            // return template.content.firstChild;
            return template.content;
        } else{
        	if(!isMenu){
        		return template.firstElementChild;
        	} else {
        		return template;
        	}
        }
    }


    function decodeSystemMarks(text) {
        text = text.replace(/\[\[c\]\]/g, ",")
                   .replace(/\[\[dq\]\]/g, '"')
                   .replace(/\[\[sq\]\]/g, "'")
                   .replace(/\[\[s\]\]/g, " ");
        return text;
    }

    function decodeMail(text) {
        
        if (text.match(/javascript:void\(location.href='mailto:/i))
            text = text.replace(/%0A/g, "'+escape('\\r\\n')+'");
        
        return text;
    }

    function decorateMessage(tmplType, messageHtml) {
    	return messageHtml;
    }

    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);
    }

    /**
     * escape html end user message 
     * @param {*} str 
     * @returns 
     */
    function escapeHTML(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    function sendMessage(msg, skip_msg, isButton, isInitMsg, image, mime_type, extraParams){
        if(!skip_msg) {
            const message = msg.replace(/\r?\n/g, '<br />');
            writeMessage(htmlToElement(decorateMessage('r', chat_msg_r_tmpl).replace(/@1/g, escapeHTML(message))));
            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.setRequestHeader('SecCHUAPlatformVersion', secCHUAPlatformVersion);
        xhr.send(createParam(msg, isButton, isInitMsg, image, mime_type, extraParams))
        initHttpLoading();
        if(!isRtchat()){
        	toggleChatBodyScroll(1);
        }
        increaseConvCount();
        hideActionSuggestion();
    }

    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,
                    'scenario_id': scenario_id,
                }
            };
            sendAnalyticsData(postData);
        }
    }

    function openLink(url, target){
        if (!url.match(/^https?:\/\//i)) {
            url = '//' + url;
        }
        if (window.synalytics) {
            url = window.synalytics.getUrl(url);
        }
        // if short url
        if (url.indexOf(s) > -1) {
            var paramStr = JSON.stringify(needProcessParams);
            if (paramStr && paramStr != '{}') {
                var linkHasParam = hasParam(getUrlParams(url));
                var connectChar = linkHasParam ? '&' : '?';
                url = url + connectChar + 'url_params=' + paramStr;
            }
        } else {
            var addParamStr = createParamQS(url, needProcessParams);
            url = url + addParamStr;
        }
        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/880e0d55cf6a4afd9b67ee06d1fe176d/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;
        }
        // modal flg
        params['display_as_modal'] = display_as_modal ? "1" : "0";
        if (userState){
            params['u_st'] = userState;
        }
        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();
            }
        }, 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(demo_scenario_id > 0){
            windowElement.style.visibility = "visible";
            loadRichMenu();
            if (display_as_modal) {
                synalio.toggle(0);
            }
            return;
        }
        var isNeed = 'None' != '-1';
        if(!isNeed){
            return;
        }
        xhrs = new XMLHttpRequest();
        xhrs.onreadystatechange = receiveLogs;
        xhrs.open('POST', 'https://synalio.com/api/web/880e0d55cf6a4afd9b67ee06d1fe176d/chat_logs');
        xhrs.setRequestHeader('Content-Type', 'application/json');
        xhrs.setRequestHeader('SecCHUAPlatformVersion', secCHUAPlatformVersion);
        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/880e0d55cf6a4afd9b67ee06d1fe176d/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/880e0d55cf6a4afd9b67ee06d1fe176d/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/880e0d55cf6a4afd9b67ee06d1fe176d/feedback_response');
        xhr_state.setRequestHeader('Content-Type', 'application/json');
        xhr_state.send(JSON.stringify(params))
    }

    function sendActionSuggestionRequest(text){
        text = text.trim();
        if(text != ""){
            isShowSuggestion = true;
            xhr_page = new XMLHttpRequest();
            xhr_page.onreadystatechange = receiveActionSuggestion;
            xhr_page.open('POST', 'https://synalio.com/api/apps/880e0d55cf6a4afd9b67ee06d1fe176d/action/suggestion/');
            xhr_page.setRequestHeader('Content-Type', 'application/json');
            var params = {
                "q":text,
                "is_demo":isDemo,
                "groups": actionGroupName
            }
            xhr_page.send(JSON.stringify(params))
        }else{
            hideActionSuggestion();
        }
    }

    function sendRtchatSurveyFlagRequest(){
        xhr_page = new XMLHttpRequest();
        xhr_page.onreadystatechange = receiveRtchatSurveyFlag;
        xhr_page.open('POST', 'https://synalio.com/api/apps/880e0d55cf6a4afd9b67ee06d1fe176d/settings/');
        xhr_page.setRequestHeader('Content-Type', 'application/json');
        // in future can also check other setting
        var params = {"setting_type": "rtchat_survey_flag"};
        xhr_page.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;
                    if (json.u_st) {
                        userState = json.u_st;
                    }
                    richMenu = json.rich_menu;
                    // Check rtchat status
                    if(json.is_rtchat){
                        openWs();
                        if (json.reserve) {
                            let ci = localStorage.getItem('countInterval')
                            if (ci) {
                                countInterval = parseInt(ci)
                                if (idInterval) {
                                    clearInterval(idInterval);
                                    countInterval = 0;
                                }
                                setAutoReplies(json.reserve)
                            }
                        }
                    }
                    toggleRtchatStatus(json.is_rtchat);
                    var is_open = getCookie('r_window');
                    let isModalAndDemo = display_as_modal && isDemo;
                    // 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();
                            }
                            // check input show status of latest log
                            if (index === logs.length
                                && typeof log.input_show_status !== 'undefined'
                                && log.input_show_status !== null) {
                                overrideHideInputSetting(log.input_show_status);
                            }
                        });
                        if (reservation_autoreplies && reservation_autoreplies.length > 0 && !isNotRepliedFromAdmin) {
                            // Cancel reservation message
                            if (idInterval) {
                                clearInterval(idInterval);
                                countInterval = 0;
                                localStorage.removeItem('countInterval')
                            }
                            reservation_autoreplies.forEach(function(timer){
                               clearTimeout(timer);
                            });
                        }

                        // final log => process menu
                        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' || isModalAndDemo){
                            if (canOpenOnReceiveLog || isModalAndDemo) {
                                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' || isModalAndDemo) {
                           if (canOpenOnReceiveLog || isModalAndDemo) {
                               synalio.toggle(0);
                           }
                        }
                        windowElement.style.visibility = "visible";
                        var postData = {
                            'event_type': 'page_start',
                            'event_data': {
                                'unique_id': appid,
                                'user_id': s,
                                'scenario_id': scenario_id,
                            }
                        };
                        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();

                    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
                        const time = autoOpenTime > 0 ? autoOpenTime : json.reserve.time;
                        reservation = setTimeout(function(){
                            var postData = {
                                'event_type': 'chat_opened',
                                'event_data': {
                                    'unique_id': appid,
                                    'user_id': s,
                                    'scenario_id': scenario_id,
                                }
                            };
                            sendAnalyticsData(postData);
                            if (typeof json.input_show_status !== 'undefined' && json.input_show_status !== null ) {
                                overrideHideInputSetting(json.input_show_status, json.teijin)
                            }
                            reserveProcess(json.reserve, s, true);
                        }, 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 responsesLen = responses ? responses.length : 0;
        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];
                var elementIdx = responsesLen - responses.length;
                lastResElem = writeMessageProcess({
                    'text': response,
                    'type': message.type,
                }, showLoading, message, elementIdx);
                // show_menu
                var isCarousel = false;
                if(response && response.indexOf('##carousel##') == 0){
                	isCarousel = true;
                }
                menu_process(message, lastResElem, elementIdx, isCarousel);

                responses.shift();
                setTimeout(function(){
                	responseProcess(callback);
                }, loadingInterval);
            } else {
            	stopLoading();
            	cnt = 0;
            	responseProcess(callback);
            }
        }
    }

    function setFocusInput(status) {
        isFocusInput = status;
    }

    function writeMessageProcess(message, showLoading, jsonObj, elementIdx){
    	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, '<br />');
        }
        var isCarousel = false;
        if(message.message_type && message.message_type === 'carousel' || message.text.indexOf('##carousel##') == 0){
        	isCarousel = true;
        }

        if (message.type === 'end_user') {
            if (message.image) {
                var imageUrl = 'https://synalio.com/api/web/880e0d55cf6a4afd9b67ee06d1fe176d/get_media/img?content_type=' + message.mime_type + '&file=' + message.image;
                writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_img_tmpl).replace(/@1/g, imageUrl)), showLoading);
            }
            else {
                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);
                    if (nonce) {
                        var form = lastResElem.getElementsByTagName("form")[0];
                        form.onchange = parent.synalio.onFormChanged;
                        var btnSend = form.getElementsByClassName("btn-send")[0];
                        btnSend.onclick = function () { return parent.synalio.onSubmitForm(btnSend); }
                    }
            		chat_msg_f_names.push('input');
            	}
            } else if(isCarousel){
            	carousel_process(message.text, jsonObj, elementIdx);
            } else{
                if(message.text.indexOf("##markdown##") != -1){
                    msg = message.text.replace(/##markdown##/g, "")
                    lastResElem = writeMessage(htmlToElement(decorateMessage('l', chat_message_markdown_tmpl).replace(/@1/g, msg)), showLoading);
                }else{
                    lastResElem = writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_tmpl).replace(/@1/g, msg).replace(/@2/g, headerText).replace(/@3/g, characterImage)), showLoading);
                }
                cspHandleOnClick(lastResElem);
            }
        } 
        else if (message.type === 'admin_user') {
            if (message.image) {
                writeMessage(htmlToElement(decorateMessage('l', chat_msg_l_img_tmpl).replace(/@1/g, message.image)), showLoading);
            }
            else {
                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 setAutoReplies(arrayAutoReplies) {
        var autoReplies = arrayAutoReplies.sort(function(a,b) {
            return a.time - b.time
        })
        idInterval = setInterval(function() {
            if (autoReplies.length > 0) {
                let autoReply = autoReplies[autoReplies.length - 1];
                if (countInterval >= autoReply.time) {
                    clearInterval(idInterval);
                    countInterval = 0;
                    return;
                }
            }
            countInterval += 1
            localStorage.setItem('countInterval', countInterval)
        }, 1000)
        autoReplies.forEach(function(r){
            let t = r.time;
            if (t > countInterval) {
                t = t - countInterval;
            } else {
                return;
            }
            var timer = setTimeout(function(){
                reserveProcess(r, s, true);
            }, t * 1000);
            reservation_autoreplies.push(timer);
        });
    }

    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 responseMarkdown = json.response_markdown || [];
                var lastResElem;
                var tempLastResElem;
                var cnt = 0;
                actionGroupName = json.action_group_name;
                if (json.scenario_id > 0) {
                    scenario_id = json.scenario_id;
                }
                startHttpFakeLoading();
                // Check rtchat status
                if(json.is_rtchat){
                    if (json.refresh_log) {
                        retryCount = 1;
                    }
                    openWs();
                }
                var callback = !json.is_rtchat ? null : function(){
                	if(json.is_rtchat){
                        stopLoading();
                		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, json.teijin)
                }
                message_process(callback);
                // reserve
                if(json.reserve){
                	setAutoReplies(json.reserve)
                }

                if(json.script){
                    for(var i=0;i<json.script.length;i++){
                        var childNodes = createElementFromHTML(json.script[i].trim());
                        for(var j=0;j<childNodes.length;j++){
                            if(childNodes[j].nodeName.toLowerCase() === 'script'){
                                if(childNodes[j].hasAttribute('src')){
                                    var script = document.createElement('script');
                                    script.type = 'text/javascript';
                                    script.src = childNodes[j].src;
                                    document.body.appendChild( script );
                                } else {
                                    var script = document.createElement('script');
                                    script.type = 'text/javascript';
                                    script.innerHTML = childNodes[j].innerHTML;
                                    document.body.appendChild(script);
                                }
                            }
                            // document.body.appendChild(childNodes[j]);
                        }
                    }
                }

                function createElementFromHTML(htmlString) {
                  var div = document.createElement('div');
                  div.innerHTML = htmlString.trim();
                  return div.childNodes;
                }

                function message_process(callback){
                	var timer = isHttpLoadingStarted ? 0 : Math.random() * 600 + 1600;
                    if(cnt == 0){
                        cnt++;
                        timer = isHttpLoadingStarted ? 0 : Math.random() * 600 + 1600;
                        if(isHttpLoadingStarted){
                        	isHttpLoadingStarted = false;
                        }
                        if (responseLength == responses.length + 1){
                            tempLastResElem = lastResElem ? lastResElem : tempLastResElem;
                            // add first-element class for every responseS
                            if (tempLastResElem) {
                                tempLastResElem.classList.add('first-element');
                            }
                        }
                        if(responses.length === 0 && responseMarkdown.length === 0){
                            synalio.onCompleteWriteMessage(json);
                            toggleChatBodyScroll(0);
                            if(callback){
                            	callback();
                            }
                            return;
                        }

                        var res = responses[0] ? responses[0] : "";
                        var match = res.match(/^##form:(.+)##/);
                        var chat_msg_template = (res.indexOf('id="chat-form-submit"') != -1) ? chat_msg_f_edit_button_tmpl : chat_msg_f_tmpl;
                        var isCarouselRes = false;
                        var elementIdx = responseLength - responses.length;
                        if(match && match.length >= 2){
                        	lastResElem = writeMessage(htmlToElement(chat_msg_template.replace('@1', res.replace(match[0], '')).replace(/@2/g, match[1])), true);
                            if (nonce) {
                                var form = lastResElem.getElementsByTagName("form")[0];
                                form.onchange = parent.synalio.onFormChanged;
                                var btnSend = form.getElementsByClassName("btn-send")[0];
                                if (btnSend.parentElement.id == "chat-form-submit") {
                                    btnSend.onclick = function () {
                                        if(typeof parent.synalio !== 'undefined') {
                                            return parent.synalio.onSubmitForm(btnSend);
                                        }
                                    }
                                } else {
                                    btnSend.onclick = parent.synalio.onSubmitForm;
                                }

                            }

                            scroll(1);
                            chat_msg_f_names.push(match[1]);
                        } else if(res.indexOf('##carousel##') == 0){
                        	stopLoading();
                        	tempLastResElem = carousel_process(res, json, elementIdx);
							isCarouselRes = true;
							scroll(1);
							timer = 0;
                        } else{
                            if(res.indexOf("##markdown##") != -1){
                                res = res.replace(/##markdown##/g, "")
                                lastResElem = writeMessage(htmlToElement(decodeMail(decorateMessage('l', chat_message_markdown_tmpl).replace(/@1/g, res))), true);
                            }else{
                                lastResElem = writeMessage(htmlToElement(decodeMail(decorateMessage('l', chat_msg_l_tmpl).replace(/@1/g, res).replace(/@2/g, headerText).replace(/@3/g, characterImage))), true);
                            }
                            cspHandleOnClick(lastResElem);
                            scroll(1);
                        }

                        menu_process(json, lastResElem, elementIdx, isCarouselRes);

                        responses.shift();
                        setTimeout(function(){
                            message_process(callback);
                        }, timer);
                    } else {
                    	stopLoading();
                    	cnt = 0;
                    	message_process(callback);
                    }
                }
            } else {
            	toggleChatBodyScroll(0);
            }
            break;
        }
    }

    function handleChatElementClick(elem) {
        var dataValue = elem.getAttribute('data-val');
        if (!dataValue) { return; }
        return function() {
            parent.synalio.onPressLink(elem);
        }
    }

    function cspHandleOnClick(elem) {
        if (!nonce) { return; }
        var childElems = elem.getElementsByClassName("chat-block");
        if (childElems.length > 0) {
            childElems[0].onclick = handleChatElementClick(childElems[0]);
        } else {
            elem.onclick = handleChatElementClick(elem);
        }
    }

    function appendMenuToLastResponse(menuHtml, lastResElem){
    	if(!lastResElem){
    		var targets = synalioDocument.getElementsByClassName('chat-message-body');
        	if(targets.length <= 0) {
        		return;
        	}
        	lastResElem = targets[targets.length - 1];
    	}
        var markdownEl = lastResElem.getElementsByClassName("markdown-body");
        // no add the backToHome button on the markdown response.
        if (markdownEl.length > 0) return;

    	if(lastResElem.className.indexOf('left-talk-box') != -1){
    		var elem = htmlToElement(menuHtml, true);
    		while(elem.childNodes.length > 0){
    			var childElem = elem.childNodes[0];
                cspHandleOnClick(childElem);
    			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, elementIdx, isCarouselResponse){
    	//var menu_count = 0;
        var hasButton = false;
        var buttonLst = json.buttons ? json.buttons : [];
        var replyDecos = json.reply_deco || [];
        // only check this flag in case not log-history
        var isCarouselRes = typeof isCarouselResponse !== 'undefined' ? isCarouselResponse : true;
        // feedback info
        var is_feedback = typeof json.is_feedback !== 'undefined' ? json.is_feedback : false;
        var feedback_log_id = typeof json.feedback_log_id !== 'undefined' ? json.feedback_log_id : null;
        var state = json.switch_state ? json.switch_state : '';
        if (state == ''){
        	if (typeof json.dialogue_history !== 'undefined' && json.dialogue_history.length > 0){
        		state = json.dialogue_history[json.dialogue_history.length-1].state_name;
        	} else {
        		state = json.state;// page-stay
        	}
        }
        var actionName = json.action;
        if (typeof json.state !== 'undefined' && json.state[state] && json.state[state].response){
        	actionName = json.state[state].response;
        }
        // new logic by response from back-end case ( not case log )
        if (typeof json.result_buttons !== 'undefined'){
        	for (var idx = 0; idx < json.result_buttons.length; idx++) {
            	if (json.result_buttons[idx].length > 0){
            		hasButton = true;
            		break;
            	}
            }
        	buttonLst = json.result_buttons[elementIdx];
        	replyDecos = json.result_reply_deco[elementIdx] || [];
        	var feedbackInfo = json.result_is_feedback[elementIdx];
        	if(feedbackInfo){
                is_feedback = feedbackInfo.is_feedback;
                feedback_log_id = feedbackInfo.feedback_log_id;
                actionName = feedbackInfo.action;
            }
        }

        if(buttonLst && buttonLst.length > 0){
            var l = [];
            var j = 0;
            for (var i = 0; i < buttonLst.length; i++) {
                var decoClass = '';
                var buttonBackgroundcolor = '';
                var buttonColor = '';
                var borderColor  = '';
                var boderColorClass = '';
                if(replyDecos.length > j){
                    decoClass = replyDecos[j];
                    var decoList = replyDecos[j].split('__');
                    if (decoList.length > 0) {
                        decoClass = decoList[0];
                        buttonBackgroundcolor = decoList.length > 1 ? decoList[1]: '';
                        buttonColor = decoList.length > 2 ? decoList[2]: '';
                        if (buttonColor) {
                            borderColor = '--border-color:' + buttonColor + ';';
                            boderColorClass = 'choice-block-color';
                        }
                    }
                }
                j++;

                var val1 = buttonLst[i].img ? buttonLst[i].img : buttonLst[i].label.replace(/"/g,'&quot;');
                var tmpl = buttonLst[i].img ? chat_msg_c_img_tmpl : chat_msg_c_tmpl;
                var val2 = buttonLst[i].url ? buttonLst[i].url : buttonLst[i].msg.replace(/"/g,'&quot;');
                var val3 = buttonLst[i].url && buttonLst[i].url_target ? buttonLst[i].url_target : '';
                var img_alt = buttonLst[i].img && buttonLst[i].img_alt ? buttonLst[i].img_alt : 'null';
                l.push(decorateMessage('c', tmpl).replace(/@1/g, val1).replace(/@2/g, val2).replace(/@3/g, decoClass).replace(/@4/g, val3).replace(/@5/g, buttonBackgroundcolor).replace(/@6/g, buttonColor).replace(/@7/g, boderColorClass).replace(/@8/g, borderColor).replace(/@9/g, img_alt));
            }
            appendMenuToLastResponse(l.join(''), lastResElem);
            //menu_count = l.length;
        } else if(!json.no_button && !hasButton) {
            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 (!isCarouselRes && is_feedback && feedback_log_id && lastResElem) {
            var feedback_form = htmlToElement(chat_feedback_form_tmpl.replace(/@2/g, '<p>回答に問題がある場合、以下のどちらだったかを教えてください。回答精度向上にフィードバックを活かします。</p>').replace(/@3/g, '見当違いな回答').replace(/@4/g, '正しいが不十分な回答').replace(/@5/g, '<p>フィードバックありがとうございました。<br>回答内容改善の参考にさせて頂きます。</p>').replace(/@6/g, actionName).replace(/@7/g, state).replace(/@8/g, feedback_log_id), true);
            lastResElem.appendChild(feedback_form);
            if (nonce) {
                var formElem = lastResElem.getElementsByTagName("form")[0];
                formElem.onchange = function () { parent.synalio.onFormChanged(formElem) };
            }
            var feedbackBtns = lastResElem.getElementsByClassName('feedbackBtn-' + feedback_log_id);
            if (feedbackBtns.length > 0) {
                for (var j = 0; j < feedbackBtns.length; j++) {
                    feedbackBtns[j].style.width = feedbackBtnFixWidth;
                    if (nonce) {
                        var buttonIdx = feedbackBtns[j].innerText == '見当違いな回答' ? 1 : 2;
                        feedbackBtns[j].onclick = function () { return parent.synalio.onSubmitFeedbackForm(buttonIdx, feedback_log_id); }
                    }
                }
            }
        }

        
    }

    function isObject(obj) {
        return obj && !Array.isArray(obj) && typeof obj === 'object';
    }

    function carousel_process(res, json, elementIdx){
    	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;
    	}
    	synalio_carousel.deleteButtons();
        var carouselItems = [];
        var imageCarouselSize = (carouselData.length > 0 && carouselData[0].image_size) ? carouselData[0].image_size : '16_9';
        var imageShowingMethod = (carouselData.length > 0 && carouselData[0].image_showing_method) ? carouselData[0].image_showing_method : 'cover';
        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,'&quot;');
                //var btnVal2 = carouselData[i].buttons[j].uri ? carouselData[i].buttons[j].uri : carouselData[i].buttons[j].text.replace(/"/g,'&quot;');
                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,'&quot;');
                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 ? 'font-weight: bold;' : '' ;
                var buttonColor = carouselData[i].buttons[j].reply_color ? carouselData[i].buttons[j].reply_color : '' ;
                var buttonBgColor = carouselData[i].buttons[j].reply_bgcolor ? carouselData[i].buttons[j].reply_bgcolor : '' ;
                if (buttonColor) {
                    btnVal5 = btnVal5 + 'color:' + buttonColor + ';';
                }
                if (buttonBgColor) {
                    btnVal5 = btnVal5 + 'background-color:' + buttonBgColor + ';';
                }
                if (btnVal5) {
                    btnVal5 = 'style="' + btnVal5 + '"';
                }
                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,'&quot;');
            var itemVal2 = carouselData[i].text.replace(/"/g,'&quot;');
        	var itemVal3 = '';
            if(carouselData[i].image_url){
                itemVal3 = chat_message_carousel_item_image_tmpl.replace(/@1/g, carouselData[i].image_url).replace(/@2/g, imageShowingMethod);
                var styleCursor = '';
                var imageLink = '';
                if (carouselData[i].image_link) {
                    let img_alt = carouselData[i].image_alt ? carouselData[i].image_alt : 'null';
                    styleCursor = 'cursor: pointer';
                    imageLink = 'onclick="parent.synalio.onPressLink(this)" data-val="@url" data-val-label="@image_alt" data-val-target="_blank"'.replace(/@url/g, carouselData[i].image_link).replace(/@image_alt/g, img_alt);
                }
                itemVal3 = itemVal3.replace(/@3/g, styleCursor).replace(/@4/g, imageLink);
            }
        	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);
        if (nonce) {
            var buttonElems = lastResElem.getElementsByClassName("btn-box");
            for (let i=0; i<buttonElems.length; i++) {
                cspHandleOnClick(buttonElems[i]);
            }
            var imgElems = lastResElem.getElementsByClassName("header-block");
            for (let i=0; i<imgElems.length; i++) {
                if (imgElems[i].dataset.val) {
                    cspHandleOnClick(imgElems[i]);
                }
            }
        }
        synalio_carousel.show(carouselLastId, imageCarouselSize);
        // only write feedback-button if not log case
        if (isObject(json) && typeof json.result_is_feedback !== 'undefined'){
        	var feedbackInfo = json.result_is_feedback[elementIdx];
	        if (feedbackInfo.is_feedback && feedbackInfo.feedback_log_id && lastResElem) {
	            var state = json.switch_state ? json.switch_state : '';
	            if (state == ''){
	            	if (typeof json.dialogue_history !== 'undefined' && json.dialogue_history.length > 0){
	            		state = json.dialogue_history[json.dialogue_history.length-1].state_name;
	            	} else {
	            		state = json.state;// page-stay
	            	}
	            }
	            var actionName = feedbackInfo.action;
	            var feedback_form = htmlToElement(chat_feedback_form_tmpl.replace(/@2/g, '<p>回答に問題がある場合、以下のどちらだったかを教えてください。回答精度向上にフィードバックを活かします。</p>').replace(/@3/g, '見当違いな回答').replace(/@4/g, '正しいが不十分な回答').replace(/@5/g, '<p>フィードバックありがとうございました。<br>回答内容改善の参考にさせて頂きます。</p>').replace(/@6/g, actionName).replace(/@7/g, state).replace(/@8/g, feedbackInfo.feedback_log_id), true);
	            var wrapDiv = document.createElement("DIV");
	            wrapDiv.className = "left-talk-box";
	            wrapDiv.setAttribute('data-talkshow', 'talkshow');
	            wrapDiv.appendChild(feedback_form);
                if (nonce) {
                    var formElem = wrapDiv.getElementsByTagName("form")[0];
                    formElem.onchange = function () { parent.synalio.onFormChanged(formElem) };
                }
	            lastResElem.parentNode.appendChild(wrapDiv);
	            var feedbackBtns = wrapDiv.getElementsByClassName('feedbackBtn-' + feedbackInfo.feedback_log_id);
	            if (feedbackBtns.length > 0) {
	                for (var j = 0; j < feedbackBtns.length; j++) {
	                    feedbackBtns[j].style.width = feedbackBtnFixWidth;
                        if (nonce) {
                            var buttonIdx = feedbackBtns[j].innerText == '見当違いな回答' ? 1 : 2;
                            feedbackBtns[j].onclick = function () { return parent.synalio.onSubmitFeedbackForm(buttonIdx, feedbackInfo.feedback_log_id); }
                        }
	                }
	            }
	        }
        }
        return lastResElem;
    }

    function httpError(){
        var msg = "<li><div class='chat-message-body error'> 送信に失敗しました。<br/>ネットワーク接続をご確認いただくか、お時間おいて再度お試しください。</div></li>";
        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=" + encodeURIComponent(refererUrl));
        if(checkDemo() == 1){
            params.push("demo=1");
        }
        if(isButton){
            params.push("button=1");
        }
        if(isInitMsg){
            params.push("init=1");
        }
        if (isInitMsg && userState && msg != "finish_rtchat"){
            params.push('u_st='+userState);
        }
        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 (demo_scenario_id != ""){
            params.push("demo_scenario_id="+demo_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(){
      if (isHideChatting) {
        return;
      }
        // 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 && !isHideChatting){
        		elem.lastChild.setAttribute('data-loading', 'on');
        	}
        	elem.lastChild.setAttribute('data-talkshow', 'talkshow');
        	elem.lastChild.setAttribute('data-test', 'chat-dialogue');
        }
        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");
        var firstElements = synalioDocument.getElementsByClassName("first-element");
        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];
            if (firstElements.length > 0 && !isInRtchat()) {
                setTimeout(function () { //Set Timeout to make sure element is appended
                  target = firstElements[firstElements.length - 1];
                  smoothScr.stopShow();
                  smoothScr.anim(target, chatBody, chatHeader);
                }, 100)
            } else {
                smoothScr.stopShow();
                smoothScr.anim(target, chatBody, chatHeader);
            }
            // chat_body.scrollTop = target.offsetTop - chat_header.offsetHeight;
            //smoothScr.step =  (target.offsetTop - chatHeader.offsetHeight - chatBody.scrollTop) / 15.0;
        }
    }

    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.position = objectCss.position;
            synalioParentDocument.body.style.width = objectCss.width;
            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 iframeStyle = "";
    	// Show to calculate the offset
        if (hiddenStyle === 'display:none;') {
            var iframe = synalioParentDocument.getElementById('synalio-iframe');
            iframeStyle = iframe.getAttribute("style");
            var tempStyle = iframeStyle.replace(hiddenStyle, "");
            iframe.setAttribute("style", tempStyle);
        }

    	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);

        // Restore iframe's style
        if (iframeStyle != "") {
            iframe.setAttribute("style", iframeStyle);
        }

    	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' && no_minimize_visual){
	    	    closeImageVisual(iframe, windowBox);
	    	}else{
	    		windowBox.removeAttribute('style');
	    		getElement('main-box').removeAttribute('style');
	    		getElement('outer-talk-set-box').removeAttribute('style');
                var frameHeight = 85;
	    		if(displayType != 'max-min'){
	    			iframe.style.width = '100%';
	    		} else {
	    			iframe.style.width = '24.47%';
                    if (navigator.userAgent.match(/iPad/)) {
                        frameHeight = Math.ceil(152 * window.screen.width / 834);// base on ipad 11
                    }
	    		}
	    		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;
                } else {
                    isClosedWindowChat = true;
                }
            }
	    }else{
	    	if(displayType === 'img' && no_minimize_visual){
	    	    closeImageVisual(iframe, windowBox);
	    	}else{
                windowBox.removeAttribute('style');
                getElement('main-box').removeAttribute('style');
                getElement('outer-talk-set-box').removeAttribute('style');
                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 +')';
                if (isClosedWindowChat) {
                    iframe.style.height = heightWindowBoxCloseNew;
                    windowBox.style.height = heightWindowBoxClose;
                    positionTimeOut = setTimeout(function () {
                        iframe.style.height = heightWindowBoxClose;
                        iframe.style.bottom = position_close_box;
                    }, 1000);
                } else {
                        windowBox.style.height = heightWindowBoxClose;
                        iframe.style.height = heightWindowBoxClose;
                        isClosedWindowChat = true;
                }
            }
        }
        // hide visual-close
        let closeWindowChat = localStorage.getItem('closeWindowChat');
        let visualClose = synalioDocument.getElementById('synalio-visual-close');
        if (visualClose && closeWindowChat) {
            visualClose.style.display = 'none';
        }
	}

    function closeImageVisual(iframe, windowBox) {
        let heightWindowBoxClose =  closeImageHeight;
        if (unread_ids.length > 0) {
            heightWindowBoxClose += closeImageBadgeHeight;
        } else {
            let image_box = synalioDocument.getElementById("img-box-image");
            image_box.style.paddingTop = "0px";
        }
        iframe.style.width = closeImageWidth + 'px';
        iframe.style.height = heightWindowBoxClose + "px";
        iframe.style.bottom = position_close_box;
        windowBox.style.width = closeImageWidth + 'px';
        windowBox.style.height = heightWindowBoxClose + "px";
        windowBox.style.padding = '0px';
    }

	function toggle(e, event){ // 0: open, 1: close, event: DOM's event
		synalio.toggle(e, event);
	}

    function resizeTextArea(target){
    	var oldHeight = target.offsetHeight || parseInt(target.style.height.replace('px', ''));
    	// Resize Text Area
    	if(target.scrollHeight >= target.offsetHeight){
    		if(target.scrollHeight < textAreaHeight + 20 + 8){
                if (target.scrollHeight > 0) {
                    target.style.height = target.scrollHeight + "px";
                }
    		} else {
    			target.style.height = (textAreaHeight + 20 + 8) + "px";
    		}
        }else{
            var height;
            for (var i = 0; i <= 10; i++){
                height = Number(target.style.height.split("px")[0]);
                target.style.height = height - textAreaHeight + "px";
                if(target.scrollHeight > target.offsetHeight){
                    if(target.scrollHeight > textAreaHeight){
                        target.style.height = target.scrollHeight + "px";
                    } else {
                        target.style.height = textAreaHeight + "px";
                    }
                    break;
                }
            }
        }

        target.rows = 1;
        var savedHeight = target.style.height;
        target.style.height = 'auto';
        var autoCalcHeight = target.scrollHeight;
        if (autoCalcHeight < parseInt(savedHeight.replace('px', ''))) {
            savedHeight = Math.max(autoCalcHeight, textAreaHeight) + "px" ;
        }
        target.style.height = savedHeight;

    	if(!initFooterHeight){
    		initFooterHeight = footer.offsetHeight || parseInt(footer.style.height.replace('px', ''))
    	}
    	footer.style.height = (parseInt(target.style.height.replace('px', '')) + 1) + 'px';
    	var newHeight = target.offsetHeight || parseInt(target.style.height.replace('px', ''));
    	if(newHeight != oldHeight){
    		addMultiLine();
    	}
    }

    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 host = "https://synalio.com";
        if(startsWith(host, "http")){
            socket = new WebSocket("https://synalio.com/chat/enduser/".replace(/http/g, "ws") + appid + "/" + s );
        } else {
            var prtcl = "https:" == synalioParentDocument.location.protocol ? "wss" : "ws";
            socket = new WebSocket(prtcl + ":https://synalio.com/chat/enduser/" + appid + "/" + s );
        }
        socket.onmessage = onWsMessage;
        socket.onopen = onWsOpen;
        socket.onclose = onWsClose;

    }
    function closeWs() {
        if(socket && socket.readyState == WebSocket.OPEN){
            socket.onclose = undefined;
            socket.close();
            socket = undefined;
        }
    }
    // using on rtchat
    function onWsMessage(e){
        var msg = JSON.parse(e.data);
        if(msg.disconnect){
        	sendRtchatSurveyFlagRequest();
            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 + 500 : 0);
            }else{
                menu_process({buttons:[{'label':'メニューへ戻る', 'msg':'メニューに戻る'}]});
                scroll(1);
            }
        } else {
            is_sent_init = true;

            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, '<br />')).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, msg.sender_image);
        }
        // Cancel reservation message
        if (idInterval) {
            clearInterval(idInterval);
            countInterval = 0;
            localStorage.removeItem('countInterval')
        }
        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 updateTextCustomValidity(form) {
        var el = null;
        for (var i = 0; i < form.elements.length; i = i + 1) {
            if (form.elements[i].name === "") {
                continue;
            }
            var nodeName = form.elements[i].nodeName;
            var type = form.elements[i].getAttribute('type');
            var required = form.elements[i].required;
            if (required) {
              var arrayType = ['text', 'number', 'email'];
              if ((nodeName === 'INPUT' && arrayType.indexOf(type) !== -1) || nodeName === 'TEXTAREA') {
                var value = form.elements[i].value;
                value = value.trim();
                if (value.length === 0) {
                  el = form.elements[i];
                  break;
                } else {
                  form.elements[i].setCustomValidity('');
                  form.elements[i].removeEventListener(
                    'keypress',
                    function() {},
                    false
                  );
                }
              }
            }

        }
        var result = true;
        if (el) {
          el.setCustomValidity(errorCheckboxMessage);
          el.addEventListener(
            'keypress',
            function() { el.setCustomValidity('') },
            false
          );
          result = false;
        }
        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');
        		// adjust height
        		let iframe = synalioParentDocument.getElementById('synalio-iframe');
        		let windowBox = synalioDocument.getElementsByClassName('window-box')[0];
        		let image_box = synalioDocument.getElementById("img-box-image");
        		iframe.style.height = closeImageHeight + closeImageBadgeHeight + 'px';
        		windowBox.style.height = closeImageHeight + closeImageBadgeHeight + 'px';
        		image_box.style.paddingTop = closeImageBadgeHeight + "px";
        	} else {
        		badge = synalioDocument.getElementById('synalio-chat-window-notice-badge');
        	}
        	if(badge){
        		badge.innerHTML = unread_ids.length;
                badge.parentElement.style.display = 'block';
        	}
        }
    }

    function toggleRtchatStatus(isRtchat, operatorIcon = undefined) {
    	var chat_window = synalioDocument.getElementsByClassName("window-box")[0];
    	var homeLink = synalioDocument.getElementById("home-link");
        if (isRtchat) {
    	    isCancelling = false
        	chat_window.setAttribute("data-operation", "on");
            synalioDocument.getElementsByClassName("def-icon")[0].style.display = 'none'
            var refresh_button = synalioDocument.getElementById("refresh-link");
            if (refresh_button) {
                refresh_button.style.opacity = '1.0'
            }

            if (hide_input) {
                chat_window.setAttribute("data-footer", "on");
                updateChatBoxMobile();
            }
            if (homeLink) {
            	homeLink.style.display = 'none';
            }

            if (operatorIcon) {
                localStorage.setItem("operatorIcon", operatorIcon);
            }

            if (localStorage.getItem("operatorIcon")) {
                synalioDocument.getElementById('operator_icon').src = localStorage.getItem("operatorIcon");
            }
        } 
        else {
        	chat_window.setAttribute("data-operation", "");
            synalioDocument.getElementsByClassName("def-icon")[0].style.display = ''

        	if (hide_input) {
                chat_window.setAttribute("data-footer", "");
            }
            if (homeLink) {
            	homeLink.style.cursor = 'pointer';
            	homeLink.style.display = '';
            }
            if (sessionStorage.getItem("alwayshide") === 'true') {
                chat_window.setAttribute("data-footer", "");
            }

            localStorage.removeItem("operatorIcon");
        }
        // 
        // CHANGED
        // synalio.resize(windowElement.offsetHeight);
        // 

    }

    function overrideHideInputSetting(input_show_status, teijin) {
        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 (hide_input) {
            if (input_show_status === 1){
                chat_window.setAttribute("data-footer", "on");

            } else {
                chat_window.setAttribute("data-footer", "");
            }
        } else {
            if (input_show_status === 2){
                // synalio-chat-footer-container
                if (footMain) {
                    //footMain.style.display = "none";
                    chat_window.setAttribute("data-footer", "");
                    sessionStorage.setItem("alwayshide", "true");
                }
                //chat_window.setAttribute("data-footer", "");

            } else {
                if (localStorage.getItem("alwayshide") === 'true') {
                    if (input_show_status === 1) {
                        chat_window.setAttribute("data-footer", "on");
                        sessionStorage.removeItem("alwayshide");
                    }
                } else {
                    chat_window.setAttribute("data-footer", "on");
                    sessionStorage.removeItem("alwayshide");
                }
            }
        }

        if (teijin) {
            chat_window.setAttribute("data-footer", "on");
        }

        synalio.resize(windowElement.offsetHeight);

        updateChatBoxMobile();

    }

    function updateChatBoxMobile() {
        if (isMobile && getCookie('r_window') === 'on') {
            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' && no_minimize_visual){
					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' && no_minimize_visual){
					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;
			}
            // In custom use case: call this function directly without toggle.
            isOpenedChat = true;
            toggleStatus = 0;
            hideCloseButton();

            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) continue;
				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) {
				        self.initImageVisualClose(iframe, windowBox);
                    }

				}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) {
					    self.initImageVisualClose(iframe, windowBox);
                    }
				}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');
					}

				}
			}
            
		},
        initImageVisualClose: function(iframe, windowBox){
            windowBox.style.width = closeImageWidth + 'px';
            windowBox.style.padding = '0px';
            if(iframe.style.visibility != 'hidden'){
                windowBox.setAttribute('data-show', 'show');
            }
            iframe.style.width = closeImageWidth + 'px';

            let image_box = synalioDocument.getElementById("img-box-image");
            let ajustHeight = 0;
            if (unread_ids.length > 0) {
                ajustHeight = closeImageBadgeHeight;
            } else if (!no_minimize_visual) {
                ajustHeight = closeImageMinimizeHeight;
            }
            if (ajustHeight > 0) {
                iframe.style.height = closeImageHeight + ajustHeight + 'px';
                windowBox.style.height = closeImageHeight + ajustHeight + 'px';
                image_box.style.paddingTop = ajustHeight + "px";
            } else {
                iframe.style.height = closeImageHeight + 'px';
                windowBox.style.height = closeImageHeight + 'px';
                image_box.style.paddingTop = "0px";
            }
        },
		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', app_unique_id: appid, scenario_id: scenario_id > 0 ? scenario_id : 0});
                }
            }
        },
		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 = {};
                hideActionSuggestion();
                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');
    	    if (outerBoxSetBox) {
                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;
            // If not modal or already closed
            var cookie_modal_val = getCookie(cookie_modal_key);
            if (!display_as_modal || (cookie_modal_val === "0" && !isDemo)) {
                iframe.style.height = 'calc(' + iframe.offsetHeight + 'px + ' +  position_close_box + ')';
            }
            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;
                    };
    	        	windowBox.removeEventListener(animationEndEvent, f, false);
    	        	windowBox.setAttribute('data-first', true);
    	        	scroll(1);
    	        	if(isFullScreen){
    	        		toggle(0);
    	        	}

    	        }
    	      }
    	    })(1),false);
            this.initEvents(iframe, windowBox);
            // modal, allway display as modal if demo-mode
            if (display_as_modal && (cookie_modal_val !== "0" || isDemo)) {
                var modalStyle = getFrameStyleRelatedModal(iframe, true);
                var currentPosition = getFramePosition(iframe);
                setCookie(synalioParentDocument, cookie_modal_key, currentPosition, 1800);
                iframe.setAttribute("style", modalStyle);
            }
    	},
     };

     function createChatWindowIframe() {
        var iframe = document.createElement("iframe");
        iframe.setAttribute("id", 'synalio-iframe');
        iframe.setAttribute("data-test", 'synalio-iframe');
        iframe.setAttribute("scrolling", "no");
        iframe.setAttribute("style", "border: 0px;background: none;display:none;");
        getOrCreateUserId();
        var url = "https://synalio.com/api/chatwindow";
        var request = new XMLHttpRequest();

        var chatwindowData = {
            's': s,
            'appid': "880e0d55cf6a4afd9b67ee06d1fe176d",
            'url': refererUrl,
            'is_demo': isDemo,
            'scenario_id': scenario_id,
        };
        if (nonce) {
            chatwindowData['nonce'] = nonce;
        }
        if (isDemo && demo_scenario_id) {
            chatwindowData['demo_scenario_id'] = demo_scenario_id;
        }
        chatwindowData['nanalytics'] = nanalyticsParams;
        if (Object.keys(ext).length > 0) {
            chatwindowData['ext'] = ext;
        }

        if(isFullScreen){
            chatwindowData['fs'] = 1;
        }
        request.open('POST', url);
        request.setRequestHeader('Content-Type', 'application/json');
        request.setRequestHeader('SecCHUAPlatformVersion', secCHUAPlatformVersion);
        request.send(JSON.stringify(chatwindowData));
        request.responseType = "document";

        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                displayIframeWindow(iframe, request.response);
            }
        };
        var chat_window = document.createElement("div");
        chat_window.appendChild(iframe);
        synalioParentDocument.body.appendChild(chat_window);
    }

    function setIframeContentWindow(iframe, response) {
        var cookie_modal_val = getCookie(cookie_modal_key);

        iframe.setAttribute("style", "border: 0px;background: none;" + hiddenStyle);

        if(window.navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
            iframe.contentWindow.document.open('text/html', 'replace');
        } else {
            iframe.contentWindow.document.open();
        }
        var iframeHtml = '<!DOCTYPE html><html>' + response.getElementsByTagName('html')[0].innerHTML + '</html>';
        iframe.contentWindow.document.write(iframeHtml);
        iframe.contentWindow.document.close();
        if (display_as_modal && (cookie_modal_val !== "0" || isDemo)) {
            var modalStyle = "position: fixed;left: 0;top: 0;width: 100%;height: 100%;background-color: rgba(0, 0, 0, 0.5);";
            modalStyle += "opacity: 1;visibility: visible;transform: scale(1.0); z-index: 999999999;";
            modalStyle += "transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;";
            iframe.parentNode.setAttribute("style", modalStyle);
        }

        if (synalioWindow.Nanalytics) {
            var visualId = response.getElementById('synalio-chat-visual-id');
            visualId = visualId ? visualId.value : '';
            var visualCreativeId = 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, app_unique_id: appid,
                    scenario_id: scenario_id > 0 ? scenario_id : 0 });
        }
    }

    function gambitGalleryIsInView(el) {
        if (el) {
            var scroll = window.scrollY || window.pageYOffset
            var boundsTop = el.getBoundingClientRect().top + scroll
            var viewport = {
                top: scroll,
                bottom: scroll + window.innerHeight,
            };

            var 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
        }
    };

    function displayIframeWindow(iframe, response) {
        if (!response) {
            return;
        }
        var scenarioIdEle = response.getElementById("synalio-chat-window-scenario-id");
        if (scenarioIdEle && scenarioIdEle.value) {
            scenario_id = parseInt(scenarioIdEle.value);
        }
        var displayNow = false;
        let modal_display_flg = response.getElementById('synalio-chat-visual-display_as_modal');
        // With chatvisual company => check hide_input flag from chatvisual's settings
        let chatbox_hide_input = response.getElementById('synalio-chat-visual-chatbox_hide_input');
        if (chatbox_hide_input && chatbox_hide_input.value > '') {
            hide_input = chatbox_hide_input.value === '1';
        }
        let no_minimize_visual_elm = response.getElementById('synalio-chat-visual-no_minimize_visual');
        no_minimize_visual = no_minimize_visual_elm && no_minimize_visual_elm.value == '1';
        let cookie_modal_val = getCookie(cookie_modal_key);
        if (modal_display_flg && modal_display_flg.value == '1') { display_as_modal = true; } else { display_as_modal = false; }
        if (display_as_modal && (cookie_modal_val !== "0" || isDemo)) {
            displayNow = true;
        }

        userState = response.getElementById("synalio-chat-window-scenario").value;
        var prevState = localStorage.getItem('synalioState');
        if (userState && prevState != userState) {
            setCookie(synalioParentDocument, 'r_window', 'off', 1800);
            localStorage.setItem('synalioState', userState);
            resetCloseWindowChat();
        }

        if (displayNow) {
            setIframeContentWindow(iframe, response);
            return;
        }
        hiddenStyle = "display:none;";
        var displaySetting = JSON.parse(response.getElementById("synalio-chat-window-display-setting").value);
        autoOpenTime = displaySetting.auto_open_time;
        position_close_box = displaySetting.position_close_box;
        if (displaySetting.appear_type == 2) {
            if (getCookie('r_window') === 'on') {
                setIframeContentWindow(iframe, response);
            } else {
                var element = document.querySelector('#'+displaySetting.appear_value);
                if (element) {
                    hiddenStyle = "";
                    if (gambitGalleryIsInView(element)) {
                        setIframeContentWindow(iframe, response);
                    } else {
                        window.addEventListener('scroll', function handleWindowScroll() {
                            if (gambitGalleryIsInView(element)) {
                                window.removeEventListener('scroll', handleWindowScroll, true);
                                setIframeContentWindow(iframe, response);
                            }
                        }, true);
                    }
                }
            }
        } else if (displaySetting.appear_type == 3) {
            isAutoDisplayBanner = true;
            setIframeContentWindow(iframe, response);
        } else {
            if (displaySetting.appear_type == 1) {
                isAutoDisplayBanner = true;
            }
            hiddenStyle = "";
            if (getCookie('r_window') === 'on') {
                setIframeContentWindow(iframe, response);
            } else {
                var displayTime = parseInt(displaySetting.appear_value);
                setTimeout(function () {
                    setIframeContentWindow(iframe, response);
                }, displayTime * 1000);
            }
        }
    }

    function createWindowAction() {
        if (createWindowAction.wasCalled) {
            return;
        }
        createWindowAction.wasCalled = true;

        isHideChatBox = !(isDemo === 1 || isPublish === 1);
        if (isHideChatBox) {
            return;
        }
        createChatWindowIframe();
    }

    function resetCloseWindowChat() {
        localStorage.removeItem('closeWindowChat');
        naCloseChatOpened = true;
        isClosedWindowChat = false;
    }

    function getFramePosition(currIframe) {
        var positionDict = {
            "top": "undefined",
            "bottom": "undefined",
            "left": "undefined",
            "right": "undefined"
        }
        var currTop = currIframe.style.top;
        if (typeof currTop !== undefined && currTop > "") {
            currTop = currTop.toString();
            positionDict["top"] = currTop;
        }
        var currBottom = currIframe.style.bottom;
        if (typeof currBottom !== undefined && currBottom > "") {
            currBottom = currBottom.toString();
            positionDict["bottom"] = currBottom;
        }
        var currLeft = currIframe.style.left;
        if (typeof currLeft!== undefined && currLeft > "") {
            currLeft = currLeft.toString();
            positionDict["left"] = currLeft;
        }
        var currRight = currIframe.style.right;
        if (typeof currRight!== undefined && currRight > "") {
            currRight = currRight.toString();
            positionDict["right"] = currRight;
        }
        return JSON.stringify(positionDict);
    }

    function getFrameStyleRelatedModal(currIframe, isModal) {
        var frameStyle = "z-index:" + chatbox_zindex + ";";
        if (isModal) {
            // has z-index bigger than campaign-modal
            frameStyle = "z-index: 999999999;top: 50%; left: 50%;transform: translate(-50%, -50%);";
        } else {
            // get from cookie. To do check case expired
            var cookiePos = getCookie(cookie_modal_key);
            if (!cookiePos || cookiePos === "0") {
                cookiePos = getCookie(cookie_modal_key_bk);
            }
            if (cookiePos !== null && cookiePos.indexOf("top") > -1) {
                jsonPos = JSON.parse(cookiePos);
                frameStyle += jsonPos.top !== "undefined" ? "top: " + jsonPos.top + ";" : "";
                frameStyle += jsonPos.bottom !== "undefined" ? "bottom: " + jsonPos.bottom + ";" : "";
                frameStyle += jsonPos.left !== "undefined" ? "left: " + jsonPos.left + ";" : "";
                frameStyle += jsonPos.right !== "undefined" ? "right: " + jsonPos.right + ";" : "";
            }
        }
        // get current other style, except top/bottom/left/right
        var currPosition = currIframe.style.position;
        if (typeof currPosition !== undefined && currPosition > "") {
            currPosition = currPosition.toString();
            frameStyle += "position: " + currPosition + ";";
        }
        var currBorder = currIframe.style.border;
        if (typeof currBorder !== undefined && currBorder > "") {
            currBorder = currBorder.toString();
            frameStyle += "border: " + currBorder + ";";
        }
        var currBackground = currIframe.style.background;
        if (typeof currBackground !== undefined && currBackground > "") {
            currBackground = currBackground.toString();
            frameStyle += "background: " + currBackground + ";";
        }
        var currWidth = currIframe.style.width;
        if (typeof currWidth !== undefined && currWidth > "") {
            currWidth = currWidth.toString();
            frameStyle += "width: " + currWidth + ";";
        }
        var currHeight = currIframe.style.height;
        if (typeof currHeight !== undefined && currHeight > "") {
            currHeight = currHeight.toString();
            frameStyle += "height: " + currHeight + ";";
        }
        var currDisplay = currIframe.style.display;
        if (typeof currDisplay !== undefined && currDisplay > "") {
            currDisplay = currDisplay.toString();
            frameStyle += "display: " + currDisplay + ";";
        }
        var currVisibility = currIframe.style.visibility;
        if (typeof currVisibility !== undefined && currVisibility > "") {
            currVisibility = currVisibility.toString();
            frameStyle += "visibility: " + currVisibility + ";";
        }
        return frameStyle;
    }

    function closeChatWindowModal() {
        // only process if chat-window setting as modal & already not yet closed
        let cookie_display_curr_val = getCookie(cookie_modal_key);
        // for case open link
        if (!cookie_display_curr_val || cookie_display_curr_val === "0") {
            cookie_display_curr_val = getCookie(cookie_modal_key_bk);
        }
        let modal_not_closed = cookie_display_curr_val !== null && cookie_display_curr_val !== "0";
        if (display_as_modal && modal_not_closed) {
            var iframe = synalioParentDocument.getElementById('synalio-iframe');
            iframe.parentNode.style = "";
            var frameNewStyle = getFrameStyleRelatedModal(iframe, false);
            iframe.setAttribute("style", frameNewStyle);
            setCookie(synalioParentDocument, cookie_modal_key, "0", 1800);
        }
    }

    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,'&quot;') : '';
            var btnVal2 = richMenu.buttons[i].type == 'url' ? richMenu.buttons[i].value : richMenu.buttons[i].value.replace(/"/g,'&quot;');
            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));
        }
        var buttonElems = buttonsContainer.getElementsByClassName("select-btn");
        for (var i = 0; i < buttonElems.length; i++) {
            cspHandleOnClick(buttonElems[i]);
        }
    }

    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 **/
    synalio_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, imageCarouselSize){
			 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);
                 optionobjParent.style.top = imageCarouselSize == '1_1' ? '100px': '40px';
				 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';
                     if (imageCarouselSize == '1_1') {
                        this.data[id].carlist[i].firstElementChild.style.height = Math.round(listwidth) + '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');
    	synalio_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;
    	}

        synalio_carousel.data[id].startX = event.pageX - tx;
        synalio_carousel.data[id].startPageX = event.pageX;
    	synalio_carousel.data[id].moveX = event.pageX - tx;
    	synalio_carousel.data[id].scrollX = synalio_carousel.data[id].scrollY = 0;
    	synalio_carousel.data[id].scrollX = event.pageX;
    	synalio_carousel.data[id].scrollY = event.pageY;
    	synalio_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 - synalio_carousel.data[id].scrollX));
    	var absy = Math.round(Math.abs(tempy - synalio_carousel.data[id].scrollY));
    	if(absx > absy){
    		drag.style.transform = 'translate3d(' + (event.pageX - synalio_carousel.data[id].moveX + 'px') + ',0,0)';
    		var carbase = synalioDocument.getElementById('custom-box-' + id);
    	}
    }

    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 - synalio_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 = synalio_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(-' + (synalio_carousel.data[id].maxlistw - (synalio_carousel.data[id].listw + parseInt(carul.style.marginLeft.replace('px', '')))) + 'px,0,0)';
    		setArrObj(carbase, 'right');
    	}else{//other
    		carul.style.transform = 'translate3d(-' + ((synalio_carousel.data[id].listw + synalio_carousel.data[id].carpad) * carbase.getAttribute('data-active')) + 'px,0,0)';
    		setArrObj(carbase, '');
    	}
    	synalio_carousel.data[id].rmoveflg = false;
    	synalio_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(synalio_carousel.data[id].startPageX < _nowX){// Left Card
            if((synalio_carousel.data[id].startPageX + _margin) < _nowX){
                now_active += -1;
            }
        }else{//Right Crad
            if((synalio_carousel.data[id].startPageX - _margin) > _nowX){
                now_active += 1;
            }
        }
        if(now_active < 0){
            now_active = 0;
        }
        if(now_active >= synalio_carousel.data[id].carnum){
            now_active = synalio_carousel.data[id].carnum - 1;
        }
        aindex = now_active;

    	if(aindex !== undefined){
    		carbase.setAttribute('data-active', aindex);
    	}
    }
    /** carousel end **/

    function hideActionSuggestion(){
        isShowSuggestion = false;
        var actionSuggestionBox = synalioDocument.getElementById("synalio-chat-suggestion");
        actionSuggestionBox.innerHTML = "";
        actionSuggestionBox.style.display="none";
        suggestionLength = 0;
        currentSuggestionLine = -1;
    }

    function focusSuggestionBox(){
        if(currentSuggestionLine > -1){
            var actionSuggestionBox = synalioDocument.getElementById("synalio-chat-suggestion");
            var focusLine = actionSuggestionBox.querySelector('.focus');
            if(focusLine){
                focusLine.classList.remove("focus");
            }
            actionSuggestionBox.focus();
            var focusLine = actionSuggestionBox.childNodes[currentSuggestionLine];
            focusLine.classList.add("focus");
            var chat_input = synalioDocument.getElementById("synalio-chat-text-input");
            var focusLineValue = focusLine.getAttribute("data-text");
            chat_input.value = decodeSystemMarks(focusLineValue);
            resizeTextArea(chat_input);
        }
    }

    function receiveActionSuggestion(){
        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);
                    var actionSuggestionBox = synalioDocument.getElementById("synalio-chat-suggestion")
                    actionSuggestionBox.innerHTML = "";
                    suggestionLength = json.result.length;
                    json.result.forEach(function(hit){
                        var action_text = hit._source.action_text;
                        var query_text = hit.query_text;
                        var escape_query_text = hit.escape_query_text;
                        let highlight_text = hit.process_highlight || null;
                        if(!highlight_text){
                            var decode_action_text = decodeSystemMarks(action_text);

                            highlight_text = decode_action_text.replace(new RegExp(escape_query_text, 'g'), "<span class='suggestion-highlight'>" + query_text + "</span>");
                        } else {
                            highlight_text = decodeSystemMarks(highlight_text);
                        }
                        var feedback_form = htmlToElement(chat_suggestion_line_tmpl.replace(/@1/g, highlight_text)
                                                                                   .replace(/@2/g, "'" + action_text + "'")
                                                                                   .replace(/@3/g, action_text));
                        actionSuggestionBox.appendChild(feedback_form);
                        if (nonce) {
                            var lastElem = actionSuggestionBox.lastChild;
                            lastElem.onclick = function () { parent.synalio.onSuggestionLineSelect(action_text); }
                            lastElem.onmouseover = function (event) { parent.synalio.onSuggestionLineHover(event.target); }
                        }
                    });

                    if(suggestionLength > 0){
                        actionSuggestionBox.style.display="block";
                    }else{
                        hideActionSuggestion();
                    }
                }
                break;
        }
    }

    function receiveRtchatSurveyFlag(){
        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);
                    show_rtchat_survey = json.is_satisfaction_survey_enabled == "1";
                }
                break;
        }
    }

    function getComputedStyle(element, styleName){
        return element.currentStyle ? element.currentStyle[styleName] : window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(styleName) : null;
    }

    function hideCloseButton() {
        let visualClose = synalioDocument.getElementById('synalio-visual-close');
        if (visualClose) {
            visualClose.style.display = 'none';
        }
    }

    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;
                    }
                    // Cypress handler: parent window is in aut-iframe.
                    if(cypressIframes && cypressIframes.length > 0){
                      synalioParentWindow = cypressIframes[0].contentWindow;
                      synalioParentDocument = cypressIframes[0].contentDocument;
                    }
                    
                    getOrCreateUserId();
                    

                    if (synalioWindow.Nanalytics) {
                        synalioWindow.Nanalytics('get',function(params) {
                            updateNanalyticsParams(params);
                            createWindowAction();
                        });
                        setTimeout(function () {
                            createWindowAction();
                        }, 500);
                    } else {
                        createWindowAction();
                    }
        },
        reloadEvent: function(){
            var ele = document.getElementById("synalio-iframe");
            if (ele) {
                ele.remove();
            }
            createWindowAction.wasCalled = false;
            refererUrl = location.href;
            scenario_id = 0;
            toggleStatus = -1;
            naCloseChatOpened = false;
            isOpenedChat = false;
            is_toggled = false;
            is_sent_init = false;
            richMenuInit = false;
            closeWs();

            synalio.onLoadEvent();
        },
        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");
            ta.addEventListener("input", function(e){ resizeTextArea(e.target) } );
            ta.innerHTML = '';
            synalioParentWindow.addEventListener('resize', function(e){
                resizeFitBrowser(e.target);
            });
            
        },
        onAfterIframeLoad: function(){
             windowElement = synalioDocument.getElementsByClassName("window-box")[0];
             var verticalAlign = getComputedStyle(windowElement, "vertical-align");
             if (verticalAlign != "top") {
                 var msg = "Failed to load resource: synalio.css";
                 console.warn(msg);
                 windowElement.style.visibility = "hidden";
                 return;
             }
             getLogs(s, sessionId);
             synalio.onCompleteLoad();
             synalio.onCheckClosedWindowChat();
        },
        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();
                            }
                        } else if (mode == 1) {
                            var chat_input = synalioDocument.getElementById("synalio-chat-text-input");
                            var start = chat_input.selectionStart, end = chat_input.selectionEnd;
                            chat_input.value = chat_input.value.substring(0, start)+ "\n" + chat_input.value.substring(end);
                            chat_input.selectionEnd = chat_input.selectionStart = start+1;
                            resizeTextArea(e.target);
                        }

                        if(isRtchat() == false){
                            if ((e.keyCode == 38 || e.keyCode == 40)){
                                var chat_input = synalioDocument.getElementById("synalio-chat-text-input");
                                if(chat_input.value == lastInputText && isShowSuggestion){
                                    if (e.keyCode == 38) {//arrowUp
                                        currentSuggestionLine = suggestionLength - 1;
                                    } else if (e.keyCode == 40){//arrowDown
                                        currentSuggestionLine = 0;
                                    }
                                    focusSuggestionBox();
                                    resizeTextArea(e.target);
                                }
                            } else if(e.keyCode == 27){
                                hideActionSuggestion();
                            }
                        }
                    },
        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){
                            // Set before and after openlink because of Chrome issues on cookies
                            if (!display_as_modal) {
                                setCookie(synalioParentDocument, 'r_window', 'off', 1800);
                            }
                            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,
                                    'scenario_id': scenario_id,
                                }
                            };
                            sendAnalyticsData(postData);
                            openLink(dataValue, dataValueTarget);
                            // clear modal cookie
                            if (display_as_modal) {
                                var cookie_modal_val = getCookie(cookie_modal_key);
                                setCookie(synalioParentDocument, cookie_modal_key_bk, cookie_modal_val, 1800);
                                setCookie(synalioParentDocument, cookie_modal_key, '', null, 'Thu, 01 Jan 1970 00:00:00 UTC');
                            }

                            return;
                        }
                        sendMessage(dataValue, false, true);
                    	deleteReplyOptions();
                        
                        deleteSubmitForms();
                        
                        synalio_carousel.deleteButtons();
        },
        onPressMessageLink: function(e){
            var urlRegex = /((http|https|file):\/\/[^\s]+)/g;
            var htmlContent = e.innerHTML;
            var index = htmlContent.search(urlRegex);
            if (index != -1) {
                setCookie(synalioParentDocument, 'r_window', 'off', 1800);
                return;
            }
        },
        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;
            }
        },
        onCloseBrowserOrReload: function(){
            if (!isCancelling) {
                isCancelling = true;
                 var msg = {'type':'close_window'};
                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);
            hideCloseButton();
            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 = '';
                        // hide first then re-show after chatwindow opened
                        var imgBoxs = synalioDocument.getElementsByClassName("img-box");
                        var imgBox = imgBoxs && imgBoxs.length > 0 ? imgBoxs[0] : null;
                        if (imgBox) {
                            imgBox.style.display = "none";
                        }
                        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);

                        
                        if (imgBox) {
                            setTimeout(function() {
                                imgBox.style.display = '';
                            }, 1000);
                        }
                    
                } else {
                    toggleChatWindow.onOpenClick(event);
                    naCloseChatOpened = false;
                    if (synalioWindow.Nanalytics) {
                        synalioWindow.Nanalytics('send','event',
                            {category:'chatbot', action:'click', label:'click_chatbot'},
                            {click_chatbot: '1', app_unique_id: appid,
                                scenario_id: scenario_id > 0 ? scenario_id : 0});
                    }
                }
                

                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();
            // return original style
            if (toggleStatus == 1) { closeChatWindowModal(); }
            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();
                        synalio_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 = '<img src="'+imagePath+'" style="border-radius: 0!important;width: 100%;height:auto;"/>';
                    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();
                 synalio_carousel.deleteButtons();
            }
        },
        onCloseImageLoad: function(e){
            if (synalio.onCloseImageLoad.wasCalled) {
                return;
            }
            synalio.onCloseImageLoad.wasCalled = true;
        	let closeWindowChat = localStorage.getItem('closeWindowChat');
            let windowChatIsClosing = false;
            if (closeWindowChat) {
                let now = Date.now();
                let diffTime = now - closeWindowChat;
                windowChatIsClosing = diffTime <= threeHourTimestamp;
            }
            let visualImgIsMinimize = design_close_type === 'img' && !sessionIdChanged && windowChatIsClosing && !no_minimize_visual;
            if(design_close_type != 'img' || visualImgIsMinimize){
        		closeImageLoaded = true;
                return 0;
        	}
        	var img = new Image();
        	img.onload = function() {
                newWidth = this.width / 2;
            	newHeight = this.height / 2;
                if (newWidth > window.innerWidth) {
                    scale_ratio = window.innerWidth / newWidth;
                    newWidth = window.innerWidth;
                    newHeight = newHeight * scale_ratio;
                }
            	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 > threeHourTimestamp) || sessionIdChanged) {
                    resetCloseWindowChat();
                } else {
                    if (displayType !== 'img' || !no_minimize_visual) {
                        
                        isClosedWindowChat = true;
                        customCloseSize('max-min');
                        
                    }
                }
            } else {
                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{
                        form.elements[i].setCustomValidity('');
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                    }
                }
                else if(form.elements[i].nodeName == 'TEXTAREA'){
                    form.elements[i].setCustomValidity('');
                    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() || !updateTextCustomValidity(form)){
                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);
                }
            }
            var formContainer = writeMessage(htmlToElement(chat_cs_form_tmpl), true);
            if (nonce) {
                var formElem = formContainer.getElementsByTagName("form")[0];
                formElem.onchange = parent.synalio.onFormChanged;
                var btnSend = formElem.getElementsByClassName("btn-send")[0];
                btnSend.onclick = parent.synalio.onSubmitCSForm;
            }
            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;
        },
        onBlur:function(){
            var chatInput = synalioDocument.getElementById("synalio-chat-text-input");
            var actionSuggestionBox = synalioDocument.getElementById("synalio-chat-suggestion");
            setTimeout(function(){
                if(synalioDocument.activeElement != chatInput &&
                        synalioDocument.activeElement != actionSuggestionBox){
                            hideActionSuggestion();
                }
            }, 100)
        },
        onInput: function(e){
            if(isRtchat() == false){
                var chat_input = synalioDocument.getElementById("synalio-chat-text-input");
                var text = chat_input.value.trim();
                if(text != ""){
                    lastInputText = text;
                    sendActionSuggestionRequest(text);
                }else{
                    hideActionSuggestion();
                }
            }
        },
        onSuggestionLineSelect: function(value){
            value = decodeSystemMarks(value);
            var chat_input = synalioDocument.getElementById("synalio-chat-text-input");
            chat_input.value = "";
            // chat_input.focus();
            sendMessage(value);
            hideActionSuggestion();
        },
        onSuggestionLineHover: function(event){
            var actionSuggestionBox = synalioDocument.getElementById("synalio-chat-suggestion");
            var suggestionLines = Array.prototype.slice.call(actionSuggestionBox.children);
            currentSuggestionLine = suggestionLines.indexOf(event.target);
        },
        onSuggestionLinePressed: function(e){
            if (e.keyCode == 38) {//arrowUp
                if(currentSuggestionLine != 0){
                    currentSuggestionLine -= 1;
                }else{
                    currentSuggestionLine = suggestionLength - 1;
                }
            }else if(e.keyCode == 40){//arrowDown
                if(currentSuggestionLine != suggestionLength - 1){
                    currentSuggestionLine += 1;
                }else{
                    currentSuggestionLine = 0;
                }
            }else if(e.keyCode == 13){ //enter key => select text
                var actionSuggestionBox = synalioDocument.getElementById("synalio-chat-suggestion");
                var focusLine = actionSuggestionBox.querySelector('.focus');
                focusLine.click();
                e.preventDefault();
            }else if(e.keyCode == 27){ //escape => hide suggestBox
                var chat_input = synalioDocument.getElementById("synalio-chat-text-input");
                chat_input.focus();
                hideActionSuggestion();
                e.preventDefault();
            }

            focusSuggestionBox();
        },
        addExtVal: function(key, val){
            ext[key] = val;
        },
        hideChat: function() {
        },
        sendSessionCloseChat: function() {
            sendMessage("close-session", true, true, null, null, null, {'session_closed': 1});
        },
        clearCloseChat: function() {
            if (display_as_modal && isDemo) {
                resetCloseWindowChat();
            }
        },
        reConnect: function() {
            if (isTabLetOrMobile) {
                if (socket) {
                    socket = undefined;
                }
                setTimeout(() => {
                    retryCount = 1;
                    openWs();
                }, 5000)
            }
            isOffline = false
        }
    };

})();

var synalioWindow = window.parent ? window.parent : window;

// Load Chat window
if(document.readyState === 'complete'){
  synalio.onLoadEvent();
} else {
  // We need to re-assign synalioWindow variable to correct window inside aut-iframe.
  if (cypressIframes && cypressIframes.length > 0) {
    synalioWindow = cypressIframes[0].contentWindow;
  }
  synalioWindow.addEventListener('load', synalio.onLoadEvent, true);
}
var terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
synalioWindow.addEventListener(terminationEvent, function (e) {
    synalio.onCloseBrowserOrReload()
});
synalioWindow.addEventListener('offline', e => {
   setTimeout(() => {
    synalio.isOffline = true;
   }, 1500)
})
synalioWindow.addEventListener('online', e => {
  if (synalio.isOffline) {
    synalio.reConnect();
  }
})

