var jq_appdbrt = jQuery.noConflict();
var ajax_url = '';
var chat_icon = '';
var chatBox = '';
var is_paid = 0;
let files = [];
let adopt_questions = JSON.parse(sessionStorage.getItem('adopt_questions')) || [];
let chatBox_appdbrt = document.querySelector("#messageHistory_appdbrt");
let posting_message='I am now creating a profile for the national lost and found pets database.';
let adopt_option_message='Would you like me to tell you about the adoption process or help you find the perfect match?';
let location_message = {
  found: "Sorry, without a photo I cannot create a found pet profile on Petco Love Lost but I can search by your address instead. <br>Please provide the complete address including city and state where you found the animal.",
  lost: "Sorry, without a photo I cannot proceed with creating a pet profile on Petco Love Lost. <br> However I can search for found pets near to you to see if there's a match. <br>Please provide the complete address where your pet was lost including city and state."
};
let adopt_pet_message="Hold tight, we're looking for your perfect match.";
function saveChat(message, sender) {
    let chatHistory = JSON.parse(sessionStorage.getItem('chatHistory')) || [];
    chatHistory.push({ message, sender });
    sessionStorage.setItem('chatHistory', JSON.stringify(chatHistory));
}
function loadChat() {
    var chatBox = jq_appdbrt("#message_div");
     chat_icon = jq_appdbrt('#chat_icon').val();
    const chatHistory = JSON.parse(sessionStorage.getItem('chatHistory')) || [];
    chatHistory.forEach(({ message, sender }) => {
        if(sender=='bot'){
            var htmlstr=chatMessage(chat_icon,message);            
        }
        else{
            var htmlstr=userMessage(message,true);
        }
        jq_appdbrt(".messageHistory").append(htmlstr);
        type=sessionStorage.getItem('type');
        flag=sessionStorage.getItem('flag');
        var petcolove_location=sessionStorage.getItem('petcolove_location');
        if((flag=='MESSAGE_2') && (type=='lost' || type=='found') && petcolove_location =='') {
            jq_appdbrt('.file-upload_appdbrt').css('visibility', 'visible');
        }
        jq_appdbrt('#chat-tooltip_appdbrt').css('display', 'none');
        setTimeout(function () {auto_scroll_messages();}, 500); 
        jq_appdbrt('#chat-box').addClass('show_chat');
    });
    var qid=sessionStorage.getItem('qid')||'';
    if(qid>=0 && adopt_questions.length>0 && typeof adopt_questions[qid]!='undefined'){
        var chatMessagetext= `${adopt_questions[qid].text}<br><input type="hidden" value="loadallquestion" id="response_question">
         <input type="hidden" value="0" id="response_adopt_appdbrt">${buildSelectChoice(qid,adopt_questions[qid].type)}`;    
        html_to_show =`<div name="loadallquestion" class="loadallquestion" id="loadallquestion">${chatMessage(chat_icon,chatMessagetext,'response_msg'+qid)}</div>`;
        jq_appdbrt(".messageHistory").append(html_to_show);
    }
    auto_scroll_messages();
}
loadChat();
function load_languages_flages() {
    jq_appdbrt.ajax({
        url: ajax_url,
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'doobert_load_all_languages_flages',
            security: obj.security,
        },
        success: function (response) {
            jq_appdbrt('.langauge_selection_div').html(response.html);
            is_paid = response.status
        }
    });

}
function auto_scroll_messages() {
    setTimeout(function () {
      const messageDiv = document.getElementById("message_div");
      const lastChild = messageDiv?.lastElementChild;
      if (lastChild) {
        lastChild.scrollIntoView({ behavior: 'smooth' });
        document.getElementById("message-input")?.focus();
      }
    }, 1000);
}
document.addEventListener('click', function unlockAudioOnce() {
    var audio_url=jq_appdbrt('#audio_beep').val();
    var beep = new Audio(audio_url);
    beep.load();
    document.removeEventListener('click', unlockAudioOnce);
    if (sessionStorage.getItem('audio_appdbrt')!=1) {
        sessionStorage.setItem("audio_appdbrt", 1);
        beep.play().catch(console.warn);
    }
});
function displayImage(imageUrl) {
    chatBox = document.querySelector(".messageHistory");
    var user_img = jq_appdbrt('#avatar_user').val();
    chatBox.innerHTML +=`<div class="columns user_msg">
            <div class="column is-one-third"></div>
            <div class="column user_column">
            <div class="notification is-success" style="background: none;">
            <div class="msg notification_part"><img style="border-radius: 5px;width:50%;float: right;margin-right: -16px;margin-top: -11px;margin-bottom: -11px;" src="${imageUrl}"></div>
            </div>
            <div class="user_avatar_outer"><img class="user_avatar" src="` + user_img + `" /></div>
            </div>
            </div>`;
}
function isValueExists(searchValue,selectArray) {
        searchValue = searchValue.toLowerCase();
        return selectArray.some(function (item) {
            return item.toLowerCase() === searchValue;
        });
}
function getSelectArray(selectId){
     return selectArray = jq_appdbrt('[data-id="' + selectId + '"] option').map(function () {
      
        return jq_appdbrt(this).val();
    }).get();
}

function buildSelectChoice(qid,asType) {
   const specie=sessionStorage.getItem("specie");
    if (asType=='select') {
        const { name, option: choices} = adopt_questions[qid];
        const select = Object.assign(document.createElement('select'), {
            name,
            id:   name,
            className: 'checkboxoption_appdbrt',
          });
          select.dataset.id   = qid;   // data-id
          select.dataset.type = asType;  // data-type
          select.style.display = 'inline-block';
          if(qid==4)
          select.setAttribute('multiple', '');
        select.append(
            new Option('Select an option', '', /* defaultSelected */ true, /* selected */ true)
        );
        const frag = document.createDocumentFragment();
        const targetParentId = specie === 'cat' ? '2' : specie === 'dog' ? '1' : null;
            choices.forEach(opt => {
               if ((opt.parent_id == targetParentId) || opt.parent_id==0) {
                frag.append(new Option(opt.text, opt.text)); // value == text
              }
            });
        select.append(frag);
        return select.outerHTML;
    } else{
        const frag = document.createDocumentFragment();
        const { name, option: choices } = adopt_questions[qid];
        choices.forEach((raw, i) => {
          if((specie=='dog' && raw.parent_id=='1') || (specie=='cat' && raw.parent_id=='2') || raw.parent_id==0){
            const val = typeof raw === 'object' ? raw.text : raw;
            const txt = typeof raw === 'object' ? raw.text  : raw;
            const id = `${name}_${i}`;
            const input = Object.assign(document.createElement('input'), {
              type: asType,        // dynamic: 'checkbox' or 'radio'
              id,
              name: asType === 'radio' ? name : `${name}[]`, // checkboxes as array
              value: val
            });
            input.dataset.id = qid;
            input.dataset.field = txt;
            input.dataset.type = asType;
            const label = document.createElement('label');
            label.dataset.id   = qid;   // data-id                
            label.htmlFor = id;
            label.textContent = txt;
            label.style.marginLeft = '2px'; // Apply margin-left
            label.style.marginBottom = '0px'; // Apply margin-left
            const br = document.createElement('br');
            br.dataset.id   = qid;   
            frag.append(input, label, br);
            }
          });
      const wrapper = document.createElement('div');
      wrapper.append(frag);
      return wrapper.innerHTML;}
}
function response_question_validate(){
    if(!jq_appdbrt('#response_question').val())
    jq_appdbrt('#loadallquestion').append('<input type="hidden" value="loadallquestion" id="response_question"></input>');
}
jq_appdbrt(function () {
    document.getElementById('file-upload_appdbrt').addEventListener('click', () => {
        document.getElementById('file-input_appdbrt').click();
      });
    jq_appdbrt(document).off('change').on('change','select.checkboxoption_appdbrt', function () {
        response_question_validate();
        jq_appdbrt('#send-message').click();
      });
    jq_appdbrt(document).on('click','input[name="specie_appdbrt"], #qid4_continue_btn', function () {
        response_question_validate();
        jq_appdbrt('#send-message').click();
    });
    jq_appdbrt(document).on('change','#file-input_appdbrt', function () {
        
       files = this.files;
        if (!files || Object.keys(files)=='') return;
        const maxSize = 4 * 1024 * 1024;
        let formData = new FormData();
        jq_appdbrt.each(files, function (index, file) {
            if (file.size > maxSize) {
                alert(`"${file.name}" exceeds 4MB limit. Please select a smaller file.`);
                return;
            } else {
                formData.append('images[]', file);
            }
        jq_appdbrt('.custom-file-upload-btn').click();
        return false;
        });
    });    
    jq_appdbrt(document).on('click','.custom-file-upload-btn', function () {
        let html_to_show;
        if (!files) return;
        let formData = new FormData();
        const maxSize = 4 * 1024 * 1024;
        jq_appdbrt.each(files, function (index, file) {
            let fileURL = URL.createObjectURL(file);
            displayImage(fileURL);
            formData.append('images[]', file);
        });
        formData.append("security", obj.security);
        formData.append("type", sessionStorage.getItem('type'));
        formData.append("flag", sessionStorage.getItem('flag'));
        formData.append("response_input", jq_appdbrt('#response_input').val());
        formData.append("action", 'doobert_petcolove');
            var html_to_show1 = `<div class="columns waiting_for_response"><div class="chat-bubble">
            <img src="` + chat_icon + `"  class="chat_icon" /><img src="` + waiting_icon + `" />
            </div></div>`;
            chatBox.innerHTML += html_to_show1;
            chatBox.scrollIntoView(false);
        jq_appdbrt.ajax({
            url: ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                response = JSON.parse(response);
                jq_appdbrt('#message-input').removeAttr('disabled');
                jq_appdbrt('.chat_load').removeClass('loading');
                jq_appdbrt('.waiting_for_response').remove();
                if(response.status == 1) {
                    sessionStorage.setItem("type", response.type);
                    sessionStorage.setItem("flag", response.flag);
                     if (Array.isArray(response.images) && response.images.length > 0) {
                        response.images.forEach(image_url_app => {
                            if(image_url_app !== '') {
                                var image_tag=`<img style="margin-bottom: -5px;margin-top: -5px;float: right; width: 50%; border-radius: 5px; margin-right: -8px;" src="${image_url_app}" alt="Image Missing">`;
                                saveChat(image_tag, 'user');
                            }
                        });
                    }
                    var html_to_show ='';                  
                     if (typeof response.message != 'undefined' && response.message.trim() != '') {
                        html_to_show += chatMessage(chat_icon,response.message);
                            saveChat(response.message, 'bot');
                    }
                    if(response.data){
                        html_to_show += chatMessage(chat_icon,response.data);
                        saveChat(response.data, 'bot'); 
                    }
                    if (typeof response.last != 'undefined' && response.last.trim() != '') {
                        html_to_show += chatMessage(chat_icon,response.last);
                        saveChat(response.last, 'bot');
                    }
                    if (typeof response.photos != 'undefined' && response.photos == 1) {
                        html_to_show += `<div id="image_yes_no" class="question_avppdbrt not_found_div_main"><div class="pre_button_appdbrt not_found_div_inner" id="image_button_appdbrt" data-flag="${response.flag}" data-type="yes" >Yes</div><div id="image_button_appdbrt" class="not_found_div_inner" data-flag="${response.flag}" data-type="no" >No</div></div>`;
                        sessionStorage.setItem("has_no", 'has_no');
                        sessionStorage.setItem("adopt_yes_no",''); 
                    }
                    if(response.error == 2) {
                        jq_appdbrt('.file-upload_appdbrt').css('visibility', 'visible');
                    } else {
                        jq_appdbrt('#file-upload_appdbrt').css('visibility', 'hidden');
                    }
                    chatBox.innerHTML += html_to_show;
                }
                auto_scroll_messages();
            },
            error: function () {
                jq_appdbrt('#message-input').removeAttr('disabled');
                jq_appdbrt('.chat_load').removeClass('loading');
                jq_appdbrt('.waiting_for_response').remove();
                chatBox.innerHTML += 'Error uploading file.';
                chatBox.scrollIntoView(false);
            }
        });
        files=[];
        this.files=[];
         jq_appdbrt('#file-input_appdbrt').val('');
         jq_appdbrt('.message-input_appdbrt').removeAttr('disabled');
    });
    ajax_url = jq_appdbrt('#ajax_url').val();
    if (jq_appdbrt('.langauge_selection_div').length > 0) {
        load_languages_flages();
    }
    jq_appdbrt(document).on('click', '.chat_flage_to_show', function () {
        jq_appdbrt('.langauge_dropdown_selection').toggleClass('hide_it');
    });

    jq_appdbrt(document).on('click', '.single_language', function () {
        var inside = 0;
        if (jq_appdbrt(this).hasClass('choosen_langauge')) {

        } else {
            inside = 1;
            jq_appdbrt('.single_language').removeClass('choosen_langauge');
            jq_appdbrt(this).addClass('choosen_langauge');
            var src = jq_appdbrt(this).find('img').attr('src');
            jq_appdbrt('.chat_flage_to_show .language_flage').attr('src', src);
        }
        jq_appdbrt('.langauge_dropdown_selection').addClass('hide_it');

        var langauge_selected = jq_appdbrt(this).attr('data-language');
        if (langauge_selected) {
            jq_appdbrt.ajax({
                url: ajax_url,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'doobert_load_new_language_for_data',
                    langauge_selected: langauge_selected,
                    security: obj.security,
                },
                success: function (response) {
                    if (response.title && response.title != '') {
                        jq_appdbrt('#chat-header h4').html(response.title);
                    }

                    if (response.placeholder && response.placeholder != '') {
                        jq_appdbrt('#message-input').attr('placeholder', response.placeholder);
                    }

                    if (response.default_msg && response.default_msg != '') {
                        jq_appdbrt('.default_msgs_top').html(response.default_msg);
                    }
                    if (response.default_options && response.default_options != '') {
                        jq_appdbrt('#pre_defined_msg').html(response.default_options);
                    }
                }
            });
        }
    });
        jq_appdbrt(document).on('click', '#adopt_button_appdbrt', function () {
        var type = jq_appdbrt(this).attr('data-type');
        jq_appdbrt(this).parent().hide();
        if (type == 'yes') {
            saveChat('Yes', 'user');
            sessionStorage.setItem("qoption", 3);
            jq_appdbrt('#response_question').val('loadallquestion');
            jq_appdbrt('#message-input').val('Yes');
            jq_appdbrt('#send-message').click();
            jq_appdbrt('#loadallquestion').attr('id','loadallquestionold');
            sessionStorage.setItem("petcolove_location", '');
            return;
        } else {
            var htmlstr=userMessage('No',true);
            var adopt_yes_no=sessionStorage.getItem("adopt_yes_no");
            htmlstr += chatMessage(chat_icon,adopt_yes_no,'');
            chatBox.innerHTML += htmlstr;
            saveChat('No', 'user');
            saveChat(adopt_yes_no, 'bot');
        }
        document.querySelector("#message_div")?.lastElementChild?.scrollIntoView({ behavior: "smooth" });
        jq_appdbrt('#message-input').focus()[0].setSelectionRange(0, 0);
    });
    
     jq_appdbrt(document).on('click', '#image_button_appdbrt', function () {
        var type = jq_appdbrt(this).attr('data-type');      
        jq_appdbrt(this).closest('#image_yes_no').hide();
        if (type == 'yes') {
                jq_appdbrt('.file-upload_appdbrt').css('visibility', 'visible');
                //alert('File upload is now visible');
                userMessage('Yes');
                saveChat('Yes', 'user');
        } else {
            sessionStorage.setItem("petcolove_location", 'petcolove_location');
            if(sessionStorage.getItem("has_no")=='has_no'){
                jq_appdbrt('#message-input').val('No');
                jq_appdbrt('#send-message').click();
                return;
            } 
            var location_storage_message=location_message[sessionStorage.getItem("type")];
            var htmlstr= userMessage('No',true);
            htmlstr += chatMessage(chat_icon,location_storage_message,'');
            chatBox.innerHTML += htmlstr;
            saveChat('No', 'user');
            saveChat(location_storage_message, 'bot');
        }
        jq_appdbrt('#message-input').focus()[0].setSelectionRange(0, 0);
        chatBox.lastElementChild?.scrollIntoView({ behavior: "smooth" });
    });
    jq_appdbrt(document).on('click', '#not_found_div_inner', function () {
        var type = jq_appdbrt(this).attr('data-type');
        if (type == 'yes') {
            var flag = jq_appdbrt(this).attr('data-petclove-flag');
            if (typeof flag !== 'undefined' && flag !== '') {
                jq_appdbrt('#message-input').val('Yes');
                jq_appdbrt('#response_flag').val(flag);
                jq_appdbrt('#response_type').val('lost');
                jq_appdbrt('#send-message').click();
                return;
            }
            var doobert_yes_option = jq_appdbrt('#doobert_yes_option').val();
            if (doobert_yes_option) {
                var h = '';
                if (doobert_yes_option.indexOf('@') > 1) {
                    h = `<div class="columns response_msg response_bot">
                <div class="column actual_chat">
                <img src="` + chat_icon + `"  class="chat_icon" />
                <div class="notification is-success">
                <div class="msg notification_part"><div class="contact_here">Contact <a href="mailto:` + doobert_yes_option + `">` + doobert_yes_option + `</a> here for more information</div></div>
                </div>
                </div>
                </div>`;
                } else {
                    h = `<div class="columns response_msg response_bot">
                <div class="column actual_chat">
                <img src="` + chat_icon + `"  class="chat_icon" />
                <div class="notification is-success">
                <div class="msg notification_part"><div class="contact_here"><a href="` + doobert_yes_option + `" target="_blank">Contact here</a> for more information</div></div>
                </div>
                </div>
                </div>`;
                }
            }
        } else {
            jq_appdbrt('#response_type').val('');
            jq_appdbrt('#response_flag').val('');
            var default_msgs_top = jq_appdbrt('.default_msgs_top').html();
            h = `<div class="columns response_msg response_bot">
            <div class="column actual_chat">
            <img src="` + chat_icon + `"  class="chat_icon" />
            <div class="notification is-success">
            <div class="msg notification_part">` + default_msgs_top + `</div>
            </div>
            </div>
            </div>`;
        }
        jq_appdbrt(this).closest('.not_found_div_main').hide();
        chatBox.innerHTML += h;
        chatBox.scrollIntoView(false);
    });
    var is_quick_response = 0;
        jq_appdbrt(document).on('click', '.pre_button', function () {
        if(!jq_appdbrt(this).hasClass('file-upload_appdbrt') && jq_appdbrt(this).attr('id')!='qid4_continue_btn' && jq_appdbrt(this).attr('id')!='adopt_button_appdbrt'){
                var txt = jq_appdbrt(this).html();
                jq_appdbrt('#message-input').val(txt);                
                if(jq_appdbrt(this).parent().attr('id')=='adopt-question'){
                    jq_appdbrt('#response_question').val('loadallquestion');
                    jq_appdbrt('#loadallquestion').attr('id','loadallquestionold');
                    sessionStorage.setItem("qid",0);
                    sessionStorage.setItem("qoption",'');
                }
                else if(jq_appdbrt(this).parent().attr('id')=='adopt-question-option'){   
                                
                    jq_appdbrt('#response_question').val('loadallquestion');
                    jq_appdbrt('#loadallquestion').attr('id','loadallquestionold');
                    jq_appdbrt('#adopt-question-option').remove();
                    if(txt=='Adoption process'){
                        sessionStorage.setItem("qoption",1);
                    }
                    else
                    {
                        if( sessionStorage.getItem("specie")=='dog' || sessionStorage.getItem("specie")=='cat')
                            sessionStorage.setItem("qid",1);
                        else
                            sessionStorage.setItem("qid",0);
                            sessionStorage.setItem("qoption",2);
                    } 
                    sessionStorage.setItem("show_question",'yes');
                }
                jq_appdbrt('#response_type').val(jq_appdbrt(this).attr('data-type'));
                jq_appdbrt('#response_flag').val(jq_appdbrt(this).attr('data-flag'));
                //
                is_quick_response = 1;
                jq_appdbrt('#send-message').click();
        }
      
    });
    chat_icon = jq_appdbrt('#chat_icon').val();
    jq_appdbrt('#chat-icon-hidden').click(function () {
        jq_appdbrt('#chat-box').toggleClass('show_chat');
        jq_appdbrt('#chat-icon').toggleClass('chat_active');
        jq_appdbrt('#message-input').focus();
    });
    jq_appdbrt('#chat-icon').click(function (e) {
        const popup = document.getElementById("message_popup_appdbrt");
        if (!popup.contains(e.target)) {
            jq_appdbrt('#chat-box').toggleClass('show_chat');
            jq_appdbrt('#chat-icon').toggleClass('chat_active');
            jq_appdbrt('#message-input').focus();
            jq_appdbrt('#message_popup_appdbrt').hide();
        }
    });
    jq_appdbrt('#chat-close-button').click(function () {
        jq_appdbrt('#chat-box').toggleClass('show_chat');
        jq_appdbrt('#chat-icon').toggleClass('chat_active');
        jq_appdbrt('#message-input').focus();
    });

    jq_appdbrt('#close-chat').click(function () {
        jq_appdbrt('#chat-box').removeClass('show_chat');
    });

    jq_appdbrt('#message-input').keypress(function (e) {
        if (e.which === 13) {
            jq_appdbrt('#send-message').click();
        }
    });
function isOffTopic(input) {
   const offTopicKeywords = ["who","what","when","where","why","how","which","does","do","did","is","are","was","were","can","could","would",
    "will","shall","should","may","might","details","detail","information","info","about","explain","describe","clarify","definition","meaning",
    "price","cost","charge","fee","rate","available","availability","search","show","list","provide","give","tell","tell me","looking","look",
    "need","want","require","know","photos","pictures","image","images",
    "pics","location","nearest","near me","address","map","place","shelter","rescue","center","breeds","breed","types","species","transport",
    "transportation","volunteer","services","test","example","samples"];
   input = input.toLowerCase();
   return offTopicKeywords.some(keyword => {
      const pattern = new RegExp("\\b" + keyword + "\\b", "i");
      return pattern.test(input);
   });
}
    var new_chat = 0;
    var user_img = jq_appdbrt('#avatar_user').val();
    var waiting_icon = jq_appdbrt('#waiting_icon').val();
    var plugin_version = jq_appdbrt('#doobert_chatbot_version').val();
    chatBox = document.querySelector(".messageHistory");
    jq_appdbrt('#send-message').click(function (e) {
        e.preventDefault();
        if(files.length!=0){
            jq_appdbrt('.custom-file-upload-btn').click();
            return false;
        }
        var ajax_action = 'doobert_openai_request';
        var message = jq_appdbrt('#message-input').val().trim();
         
        jq_appdbrt('.response_msgerror').remove();
         if(jq_appdbrt('#response_question').val()=='loadallquestion'){
            ajax_action='doobert_adoptpet';
            var loadallquestion = document.querySelector("#loadallquestion");
            var qid=sessionStorage.getItem("qid");
            if(qid=='' || qid==null) qid=0;
            const selectArray=getSelectArray(qid);
            const elements = jq_appdbrt('#loadallquestion [data-id="' + qid + '"]');
            const field_type= elements.attr('data-type');
            const multiselect= elements.attr('multiple');
            var names = elements.map(function() {return jq_appdbrt(this).attr('name');}).get();          
            if(message!='' && field_type!='checkbox' && field_type!='radio' && qid>0 && adopt_questions.length!=parseInt(qid)+1){           
                if(isValueExists(message,selectArray))  {
                    jq_appdbrt("#loadallquestion [data-id='" + qid + "'] option").filter(function () {
                        return jq_appdbrt(this).val().toLowerCase().trim() === message.toLowerCase().trim();
                    }).prop("selected", true);
                    jq_appdbrt('#message-input').val('');
                    jq_appdbrt('#send-message').click();
                    return true;
                }
                ajax_action='doobert_openai_request';
            }
            if (field_type=='checkbox' || field_type=='radio') {
            var anyChecked = elements.is(':checked');
            var selectedCheckboxes = elements.filter(':checked').map(function() {return jq_appdbrt(this).val();}).get();
            var user_select_value= encodeURIComponent(selectedCheckboxes.join("<br>"));
            } else {
                var anyChecked= elements.val();
                if(multiselect){
                    const selectedCheckboxes = [];
                    jq_appdbrt('#loadallquestion [data-id="' + qid + '"]').each(function () {
                        const values = jq_appdbrt(this).val(); // val() is an array or null
                        if (values) selectedCheckboxes.push(...values);
                    });
                    var user_select_value= selectedCheckboxes.join("<br>");                   
                }
                else
                {
                    var user_select_value= elements.find('option:selected').text();
                }
            }
            if(qid==4 && selectedCheckboxes.length>5){
                loadallquestion.insertAdjacentHTML('beforeend', chatMessage(chat_icon,"Please select maximum 5 color",`response_msgerror`));                          
                document.getElementById("chat-body")?.scrollTo({top: document.getElementById("chat-body").scrollHeight,behavior: "smooth"});
                return false;
            }
            if(!anyChecked && message=='' && qid!=5) {
                loadallquestion.insertAdjacentHTML('beforeend', chatMessage(chat_icon,"Please select " + names[0].split("_")[0].charAt(0).toUpperCase()+names[0].split("_")[0].slice(1) + " ",`response_msgerror`));
                document.getElementById("chat-body")?.scrollTo({top: document.getElementById("chat-body").scrollHeight,behavior: "smooth"});
               return false;
            }
            jq_appdbrt('#loadallquestion .response_msg'+qid).remove();
            if(user_select_value.toLowerCase()=='dog' || user_select_value.toLowerCase()=='cat'){
                sessionStorage.setItem("specie",user_select_value.toLowerCase());  
                adopt_questions=JSON.parse(sessionStorage.getItem(user_select_value.toLowerCase())); 
                sessionStorage.setItem("adopt_questions",  JSON.stringify(adopt_questions));                    
            }
            if(adopt_questions.length==parseInt(qid)+1){
                ajax_action='doobert_adoptpet';
                saveChat(adopt_questions[qid].text,'bot');
                loadallquestion.insertAdjacentHTML('beforeend', chatMessage(chat_icon,adopt_questions[qid].text,`response_msg${qid}`));
                if(message.trim()!=''){
                    sessionStorage.setItem("adopt_questions_selection", sessionStorage.getItem("adopt_questions_selection")+'&color_appdbrt[]='+message,",");
                    saveChat(message,'user');
                    loadallquestion.insertAdjacentHTML('beforeend', userMessage(message,true));
                }                    
                else
                {
                    sessionStorage.setItem("adopt_questions_selection", sessionStorage.getItem("adopt_questions_selection")+'&'+names[0]+"="+user_select_value.replace("<br>",","));
                    saveChat(decodeURIComponent(user_select_value),'user');
                    loadallquestion.insertAdjacentHTML('beforeend', userMessage(decodeURIComponent(user_select_value),true));
                }
                if(!isOffTopic(message)){
                    loadallquestion.insertAdjacentHTML('beforeend', chatMessage(chat_icon,adopt_pet_message));
                }
                message=sessionStorage.getItem("adopt_questions_selection")+'&start_number=1';
                jq_appdbrt('#loadallquestion #qid4_continue_btn').remove();
            }
            else if(anyChecked && message.trim()=='')
            {
                saveChat(adopt_questions[qid].text,'bot');
                saveChat(decodeURIComponent(user_select_value),'user');
                sessionStorage.setItem("adopt_questions_selection", sessionStorage.getItem("adopt_questions_selection")+'&'+names[0]+"="+user_select_value.replace("<br>",",")); 
                loadallquestion.insertAdjacentHTML('beforeend', chatMessage(chat_icon,adopt_questions[qid].text,'response_msg'+qid));
                html_to_show=userMessage(decodeURIComponent(user_select_value),true);
                qid++;
                sessionStorage.setItem("qid",qid);
                let chatMessagetext='';
                chatMessagetext= `<div class="default_msgs_top">
                                    ${adopt_questions[qid].text}
                                    <br>`;
                chatMessagetext += buildSelectChoice(qid,adopt_questions[qid].type);
                 chatMessagetext +='</div>';
                html_to_show+=chatMessage(chat_icon,chatMessagetext,'response_msg'+qid);
                loadallquestion.insertAdjacentHTML('beforeend', html_to_show);
                sessionStorage.setItem("qid",qid);
                jq_appdbrt('.waiting_for_response_appdbrt').remove();
                
                document.getElementById("chat-body")?.scrollTo({top: document.getElementById("chat-body").scrollHeight,behavior: "smooth"});
                if(user_select_value.toLowerCase()=='dog' || user_select_value.toLowerCase()=='cat'){
                    sessionStorage.setItem("show_question",'no');
                    message=sessionStorage.getItem("adopt_questions_selection")+'&start_number=1';                
                }
                else { return false; }
            }
        }
        if (message && message != '' && message.trim() != '') {
            var flag=sessionStorage.getItem('flag');
            var type=sessionStorage.getItem('type');
            var has_no=sessionStorage.getItem('has_no');
            var petcolove_location=sessionStorage.getItem('petcolove_location');
            jq_appdbrt('.chat_load').addClass('loading');
            message = message.charAt(0).toUpperCase() + message.slice(1);
            html_to_show1 = `<div class="columns user_msg">
            <div class="column is-one-third"></div>
            <div class="column user_column">
            <div class="notification is-success">
            <div class="msg notification_part">${message}</div>
            </div>
            <div class="user_avatar_outer"><img class="user_avatar" src="` + user_img + `" /></div>
            </div>
            </div>`;
            if(message.trim()=='' || message=='loadallquestion' || message.includes('start_number')){
                html_to_show1='';
                message=sessionStorage.getItem("adopt_questions_selection")+'&start_number=1';
            }
            chatBox.innerHTML += html_to_show1;
            if (flag == 'MESSAGE_5' && !isOffTopic(message)) {
                 chatBox.innerHTML += chatMessage(chat_icon,posting_message);
            }
            if (new_chat === 0) {
                new_chat = 1;
                const now = new Date();
                const timeString = `Today <span>${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}</span>`;
                jq_appdbrt('.chat_time').html(timeString);
            }
            chatBox = document.querySelector(".messageHistory");
            const adoptPetMessages = ["I adopt a pet", "adopt a pet", "adopt", "adopt the pet", "I adopt a dog", "adopt a dog", "adopt the dog", "I want to adopt a dog", "I would like to adopt a dog", "Looking to adopt a dog", "Interested in adopting a dog", "Can I adopt a dog?", "I adopt a cat", "adopt a cat", "adopt the cat", "I want to adopt a cat", "I would like to adopt a cat", "Looking to adopt a cat", "Interested in adopting a cat", "Can I adopt a cat?"];
            var adopt_result = adoptPetMessages.find(sentence => message.toLowerCase().includes(sentence.toLowerCase()) || /adopt|adopt/.test(message.toLowerCase()));
           if(html_to_show1!=''){
               saveChat(message, 'user');
            }
            
            var html_to_show1 = `<div class="columns waiting_for_response"><div class="chat-bubble">
            <img src="` + chat_icon + `"  class="chat_icon" /><img src="` + waiting_icon + `" />
            </div></div>`;
            chatBox.innerHTML += html_to_show1;
            chatBox.scrollIntoView(false);
            jq_appdbrt('#message-input').val('');
            var language_selection = 'english';
            if (jq_appdbrt('.choosen_langauge').length > 0) {
                language_selection = jq_appdbrt('.choosen_langauge').attr('data-language');
            }
            var response_input=jq_appdbrt('#response_input').val();
            var petco_love=jq_appdbrt('#petco_love').val();
            var adopt_pet=jq_appdbrt('#adopt_pet').val();
            
            if(sessionStorage.getItem('adopt_yes_no')!='' && message.toLowerCase().trim()=='yes') {
                jq_appdbrt('#adopt_button_appdbrt').parent().hide();
                message=sessionStorage.getItem('adopt_query_message');
                adopt_result=sessionStorage.getItem('adopt_query_message');
                sessionStorage.setItem("adopt_yes_no",'');
                 jq_appdbrt('#loadallquestion').attr('id','loadallquestionold');
            } else if(sessionStorage.getItem('adopt_yes_no')!='' && message.toLowerCase().trim()=='no') {
                jq_appdbrt('#adopt_button_appdbrt').parent().hide();
                var adopt_no_case_message=sessionStorage.getItem("adopt_yes_no");
                chatBox.innerHTML += chatMessage(chat_icon,adopt_no_case_message,'');
                saveChat('No', 'user');
                saveChat(adopt_no_case_message, 'bot');
                sessionStorage.setItem("adopt_yes_no",'');
                jq_appdbrt('#message-input').val('');
                jq_appdbrt('.waiting_for_response').remove();
                jq_appdbrt('.chat_load').removeClass('loading');
                document.querySelector("#message_div")?.lastElementChild?.scrollIntoView({ behavior: "smooth" });
                return;
            }
            if(flag == 'MESSAGE_2' && message.toLowerCase().trim()=='yes') {
                jq_appdbrt('.file-upload_appdbrt').css('visibility', 'visible');
                saveChat('Yes', 'user');
                sessionStorage.setItem("petcolove_location", '');
                sessionStorage.setItem("flag", 'MESSAGE_2');
                jq_appdbrt('#image_yes_no').hide();
                document.getElementById("chat-body")?.scrollTo({top: document.getElementById("chat-body").scrollHeight,behavior: "smooth"});
                jq_appdbrt('#message-input_appdbrt').val('');
                jq_appdbrt('.waiting_for_response').remove();
                jq_appdbrt('.chat_load').removeClass('loading');
                return ;
            } else if(flag == 'MESSAGE_2' && message.toLowerCase().trim()=='no'){
                var location_storage_message=location_message[sessionStorage.getItem("type")];
                chatBox.innerHTML += chatMessage(chat_icon,location_storage_message);
                saveChat('No', 'user');
                saveChat(location_storage_message, 'bot');
                sessionStorage.setItem("petcolove_location", 'petcolove_location');
                jq_appdbrt('#image_yes_no').hide();
                document.getElementById("chat-body")?.scrollTo({top: document.getElementById("chat-body").scrollHeight,behavior: "smooth"});
                jq_appdbrt('#message-input').val('');
                jq_appdbrt('.waiting_for_response').remove();
                jq_appdbrt('.chat_load').removeClass('loading');
                return ;
            } else if(flag == 'MESSAGE_5' && message.toLowerCase().trim()=='no') {
                petcolove_location ='petcolove_location';
                has_no='has_no';
            }
            const foundPetSentences = ["I found a pet","found", "I found pet","I found cat","I found dog","I found the pet", "I found pet", "Found a pet", "Found pet", "I have found a pet", "I have found the pet", "I have found pet", "I just found a pet", "I just found the pet", "I just found pet", "I happened to find a pet", "I happened to find the pet", "I happened to find pet", "I discovered a pet", "I discovered the pet", "I discovered pet", "I located a pet", "I located the pet", "I located pet", "I spotted a pet", "I spotted the pet", "I spotted pet", "I came across a pet", "I came across the pet", "I came across pet", "I saw a pet", "I saw the pet", "I saw pet", "I found a dog", "I found the dog", "I found dog", "Found a dog", "Found dog", "I have found a dog", "I have found the dog", "I have found dog", "I just found a dog", "I just found the dog", "I just found dog", "I happened to find a dog", "I happened to find the dog", "I happened to find dog", "I discovered a dog", "I discovered the dog", "I discovered dog", "I located a dog", "I located the dog", "I located dog", "I spotted a dog", "I spotted the dog", "I spotted dog", "I came across a dog", "I came across the dog", "I came across dog", "I saw a dog", "I saw the dog", "I saw dog", "I found a cat", "I found the cat", "I found cat", "Found a cat", "Found cat", "I have found a cat", "I have found the cat", "I have found cat", "I just found a cat", "I just found the cat", "I just found cat", "I happened to find a cat", "I happened to find the cat", "I happened to find cat", "I discovered a cat", "I discovered the cat", "I discovered cat", "I located a cat", "I located the cat", "I located cat", "I spotted a cat", "I spotted the cat", "I spotted cat", "I came across a cat", "I came across the cat", "I came across cat", "I saw a cat", "I saw the cat", "I saw cat"];
            const found_result = foundPetSentences.find(sentence => message.toLowerCase().includes(sentence.toLowerCase()) || /found|find/.test(message.toLowerCase()));
            if (found_result) {
                type = 'found';
                flag = 'MESSAGE_1';
                petcolove_location='';
            }
            const lostPetMessages = ["I lost pet","I lose pet","lost","I lose cat","I lose dog","I lost my cat","lost","lost pet","lost a pet","I lost my pet","I lost the pet","lost the pet","My pet is missing","I am lost my dog","Help! I lost my pet","I can't find my pet","My pet is gone","I need help finding my pet","My pet ran away","Lost pet alert!","Please help, my pet is missing","I misplaced my pet","I lost my beloved pet","My pet disappeared","Urgent! My pet is lost","Has anyone seen my pet?","Looking for my lost pet","My pet is nowhere to be found","I'm searching for my lost pet","Help me find my pet","I lost dog","lost dog","lost a dog","I lost my dog","I lost the dog","lost the dog","My dog is missing","Help! I lost my dog","I can't find my dog","My dog is gone","I need help finding my dog","My dog ran away","Lost dog alert!","Please help, my dog is missing","I misplaced my dog","I lost my beloved dog","My dog disappeared","Urgent! My dog is lost","Has anyone seen my dog?","Looking for my lost dog","My dog is nowhere to be found","I'm searching for my lost dog","Help me find my dog","I lost cat","lost cat","lost a cat","I lost my cat","I lost the cat","lost the cat","My cat is missing","Help! I lost my cat","I can't find my cat","My cat is gone","I need help finding my cat","My cat ran away","Lost cat alert!","Please help, my cat is missing","I misplaced my cat","I lost my beloved cat","My cat disappeared","Urgent! My cat is lost","Has anyone seen my cat?","Looking for my lost cat","My cat is nowhere to be found","I'm searching for my lost cat","Help me find my cat"];
            const lost_result = lostPetMessages.find(sentence => message.toLowerCase().includes(sentence.toLowerCase()) || /lost|lose/.test(message.toLowerCase()));
            if (lost_result) {
                type = 'lost';
                flag = 'MESSAGE_1';
                petcolove_location='';
                ajax_action='doobert_petcolove';
            }
            // alert(adopt_result)
            // alert(adopt_pet)
            if (adopt_result && adopt_pet == 1) {
                jq_appdbrt('#file-upload_appdbrt').css('visibility', 'hidden');
                sessionStorage.setItem('adopt_query_message',message);
                const petRegex = /\b(cat|dog)\b/;
                const match = message.match(petRegex);
               
                if(match && (match[0]=='cat' || match[0]=='dog')){
                    adopt_questions=JSON.parse(sessionStorage.getItem(match[0]));                    
                    sessionStorage.setItem("adopt_questions", JSON.stringify(adopt_questions));
                    sessionStorage.setItem("qid",1);
                    sessionStorage.setItem("show_question",'yes');
                    sessionStorage.setItem("adopt_questions_selection", sessionStorage.getItem("adopt_questions_selection")+'&specie_appdbrt='+match[0]);                    
                    if(sessionStorage.getItem("qoption")!=1 && sessionStorage.getItem("qoption") != 3){   
                         chatBox.innerHTML += chatMessage(chat_icon,adopt_option_message);   
                        saveChat(adopt_option_message, 'bot');
                        chatBox.innerHTML +=  '<div class="pre_defined_msg" id="adopt-question-option"><div id="pre_button_appdbrt" class="pre_button">Adoption process</div><div id="pre_button_appdbrt" class="pre_button">Find perfect match</div></div>';
                        jq_appdbrt('.chat_load').removeClass('loading');
                        jq_appdbrt('.waiting_for_response').remove();   
                    }
                    var qoption=sessionStorage.getItem("qoption");
                    chatBox.scrollIntoView(false); 
                    sessionStorage.setItem("specie",match[0]);
                    if(qoption != 3){
                         sessionStorage.setItem('qoption','');
                         return false;    
                    }
                } else {
                    let storedData = sessionStorage.getItem('dog');
                    let adopt_questions = [];
                    if (storedData && storedData !== "undefined") {                    
                     try {
                            adopt_questions = JSON.parse(storedData);
                        } catch (e) {
                            adopt_questions = [];
                        }
                    }
                    if(message!='Find perfect match')
                    sessionStorage.setItem("qid",0);
                    sessionStorage.setItem("specie",'');
                    sessionStorage.setItem("adopt_questions", JSON.stringify(adopt_questions));
                    sessionStorage.setItem("adopt_questions_selection", '');
                    if(sessionStorage.getItem('qoption')!='3' && sessionStorage.getItem("qoption") != 1){
                        chatBox.innerHTML += chatMessage(chat_icon,adopt_option_message);  
                        chatBox.innerHTML +=  '<div class="pre_defined_msg" id="adopt-question-option"><div id="pre_button_appdbrt" class="pre_button">Adoption process</div><div id="pre_button_appdbrt" class="pre_button">Find perfect match</div></div>';
                        jq_appdbrt('.chat_load').removeClass('loading');
                        jq_appdbrt('.waiting_for_response').remove();
                        sessionStorage.setItem('qoption','');
                        document.getElementById("chat-body")?.scrollTo({top: document.getElementById("chat-body").scrollHeight,behavior: "smooth"});
                        return false;
                    }
                }
                flag = '';
                ajax_action='doobert_adoptpet';
            }
            if(flag && typeof flag == 'string' && flag.trim() != '' && flag != 'undefined' && petco_love == 1) {
                ajax_action = 'doobert_petcolove';
            }
            if(adopt_questions && adopt_questions.length==parseInt(qid)+1){
                sessionStorage.setItem("qid",''); 
                sessionStorage.setItem("adopt_questions_selection",''); 
            }
            if(isOffTopic(message)) {
                if (message.includes("color_appdbrt")) {
                   const params = new URLSearchParams(message);
                    message = params.get("color_appdbrt[]");
                }
                flag = '';
                type = '';
                has_no = '';
                petcolove_location = '';
                ajax_action='doobert_openai_request';
            }
            else if(sessionStorage.getItem("qoption")==2){
                ajax_action='doobert_adoptpet';
                if(sessionStorage.getItem('specie')=='dog' || sessionStorage.getItem('specie')=='cat')
                message='I adopt a '+sessionStorage.getItem('specie');
            }
            else if(sessionStorage.getItem("qoption")==1){
               ajax_action='doobert_openai_request';
            }
            else if (message.includes("start_number")) {
                ajax_action='doobert_adoptpet';
                message = message.replace("null", "");
            }
            if (language_selection!='english' && ajax_action!='doobert_petcolove') {
                ajax_action='doobert_openai_request';
            }
            if(message.toLowerCase().includes("adopt") && sessionStorage.getItem("qoption")!=1 && adopt_pet == 1) {
                ajax_action='doobert_adoptpet';
            }
            sessionStorage.setItem('qoption','');
            jq_appdbrt.ajax({
                url: ajax_url,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: ajax_action,
                    payload: message,
                    language_selection: language_selection,
                    security: obj.security,
                    is_paid: is_paid,
                    plugin_version: plugin_version,
                    is_quick_response: is_quick_response,
                    flag: flag,
                    type: type,
                    has_no: has_no,
                    petcolove_location:petcolove_location,
                    response_input: response_input
                },
                success: function (response) {
                    jq_appdbrt('.chat_load').removeClass('loading');
                    jq_appdbrt('.waiting_for_response').remove();
                    sessionStorage.setItem('petcolove_location','');
                    is_quick_response = 0;
                    var html_to_show = '';
                    var flag = response?.flag ?? ''; 
                    var type = response?.type ?? '';
                    var petcolove_location = response?.petcolove_location ?? '';
                    sessionStorage.setItem("type",type);
                    sessionStorage.setItem("flag",flag);
                    sessionStorage.setItem("petcolove_location", petcolove_location);
                    sessionStorage.setItem("has_no", '');
                    sessionStorage.setItem("adopt_yes_no",'');

                    jq_appdbrt('#message-input').focus()[0].setSelectionRange(0, 0);
                    if (response.status == 1) {
                        if (response.message && response.message != null) {
                            html_to_show = chatMessage(chat_icon,response.message);
                            saveChat(response.message, 'bot');  
                            if(response.data){
                                html_to_show += chatMessage(chat_icon,response.data);
                                saveChat(response.data, 'bot');
                            }
                            if (typeof response.last != 'undefined' && response.last.trim() != '') {
                                html_to_show += chatMessage(chat_icon,response.last);
                                saveChat(response.last, 'bot');
                            }
                            if (response?.photos && response?.photos!= '') {
                                sessionStorage.setItem("has_no", 'has_no');                                
                                html_to_show += `<div id="image_yes_no" class="not_found_div_main"><div class="not_found_div_inner op_yes" id="image_button_appdbrt" data-petclove-flag="${response.flag}" data-type="yes">YES</div><div id="image_button_appdbrt" class="not_found_div_inner op_no" data-petclove-flag="${response.flag}" data-type="no">NO</div></div>`
                            }
                            if((response.flag=='MESSAGE_2') || (response.type=='lost' && response.type=='found')) {
                                html_to_show += `<div id="image_yes_no" class="not_found_div_main"><div class="not_found_div_inner op_yes" id="image_button_appdbrt" data-petclove-flag="${response.flag}" data-type="yes">YES</div><div id="image_button_appdbrt" class="not_found_div_inner op_no" data-petclove-flag="${response.flag}" data-type="no">NO</div></div>`
                            }
                           chatBox.innerHTML += html_to_show;
                           chatBox.scrollIntoView(false); 
                        } else {
                            html_to_show = `<div class="columns response_msg">
                        <div class="column actual_chat">
                        <img src="` + chat_icon + `"  class="chat_icon" />
                        <div class="notification is-success">
                        <div class="msg notification_part">Hmm, something doesn’t look right. Please review your request or question and give it another go.</div>
                        </div>
                        </div>
                        </div>`;
                            chatBox.innerHTML += html_to_show;
                            chatBox.scrollIntoView(false);
                        }
                         sessionStorage.setItem("qid",'');
                    }
                    else if (response.status == 2) {

                        html_to_show = `<div class="columns response_msg">
                    <div class="column actual_chat">
                    <img src="` + chat_icon + `"  class="chat_icon" />
                    <div class="notification is-success">
                    <div class="msg notification_part">${response.message}</div>
                    </div>
                    </div>
                    </div>
                    <div class="not_found_div_main"><div id="not_found_div_inner" class="not_found_div_inner op_yes" data-petclove-flag="${flag}" data-type="yes">YES</div><div id="not_found_div_inner" class="not_found_div_inner op_no" data-petclove-flag="" data-type="no">NO</div></div>`;

                        chatBox.innerHTML += html_to_show;
                        saveChat(response.message, 'bot');
                        chatBox.scrollIntoView(false);
                        sessionStorage.setItem("type",'');
                        sessionStorage.setItem("flag",'');
                        sessionStorage.setItem("petcolove_location", '');
                        sessionStorage.setItem("has_no", '');
                        sessionStorage.setItem("adopt_yes_no",'');
                        sessionStorage.setItem("qid",'');

                    } else if (response.status == 0) {

                        html_to_show = `<div class="columns response_msg error_msg">
                    <div class="column is-one-third"></div>
                    <div class="column actual_chat">
                    <img src="` + chat_icon + `"  class="chat_icon" />
                    <div class="notification is-success">
                    <div class="msg notification_part">Some error while response</div>
                    </div>
                    </div>
                    </div>`;
                    saveChat('Some error while response', 'bot');
                        chatBox.innerHTML += html_to_show;
                        chatBox.scrollIntoView(false);
                    sessionStorage.setItem("type",'');
                    sessionStorage.setItem("flag",'');
                    sessionStorage.setItem("petcolove_location", '');
                    sessionStorage.setItem("has_no", '');
                    sessionStorage.setItem("adopt_yes_no",'');
                    sessionStorage.setItem("qid",'');

                    } else if (response.status==3) {
                            const container = chatBox;
                            sessionStorage.setItem("adopt_yes_no",'');
                            var specie=sessionStorage.getItem("specie");
                            qid=sessionStorage.getItem("qid")>0?sessionStorage.getItem("qid"):0;  
                            qid=specie=='dog' || specie=='cat'?1:qid;                            
                            sessionStorage.setItem("cat", JSON.stringify(response.cat));
                            sessionStorage.setItem("dog", JSON.stringify(response.dog));
                            adopt_questions=(specie!=null && specie!='')?JSON.parse(sessionStorage.getItem(specie)):JSON.parse(sessionStorage.getItem("dog"));
                            sessionStorage.setItem("adopt_questions",  JSON.stringify(adopt_questions));
                            if((qid==0  && adopt_questions.length!=parseInt(qid)+1) || sessionStorage.getItem("show_question")=='yes' ){
                            let chatMessagetext='';
                            chatMessagetext= `<div class="default_msgs_top" >
                                                ${adopt_questions[qid].text}
                                                <br>`;
                            chatMessagetext += buildSelectChoice(qid,adopt_questions[qid].type);
                            chatMessagetext +='</div>';
                                html_to_show =`<div name="loadallquestion" class="loadallquestion" id="loadallquestion">
                                <div class="default_msgs_top" style="margin-top:11px;">
                                ${chatMessage(chat_icon,chatMessagetext,'response_msg'+qid)}<br><input type="hidden" value="loadallquestion" id="response_question">
                                    <input type="hidden" value="0" id="response_adopt">`;
                                sessionStorage.setItem("show_question",'no');
                                html_to_show +='</div></div>';
                            }
                            chatBox.innerHTML += html_to_show;
                            chatBox.scrollIntoView(false); 
                            sessionStorage.setItem("type",'');
                            sessionStorage.setItem("flag",'');

                    } else if (response.status==4) {
                            jq_appdbrt('#loadallquestion').attr('id','loadallquestionold');
                            if (response.message!='') {
                                chatBox.innerHTML +=`<div id="progress_appdbrt" style="margin-top:6px;"><div id="bar_appdbrt"></div></div>`;
                                var width = 1;
                                var flag_adopt = 0;
                                setTimeout(function(){                               
                                    if (flag_adopt == 0) {
                                      flag_adopt = 1;
                                      var elem = jq_appdbrt("#bar_appdbrt"); 
                                      jq_appdbrt("#progress_appdbrt").show();                                    
                                      var id = setInterval(frame, 25);
                                      function frame() {
                                        if(width >= 90) {
                                          clearInterval(id);
                                          saveChat(response.message, 'bot');
                                          chatBox.innerHTML += chatMessage(chat_icon,response.message);
                                          if(response.last!='') {
                                                chatBox.innerHTML += `<div id="image_yes_no" class="question_appdbrt not_found_div_main"><div class="pre_button" id="adopt_button_appdbrt" data-flag="${response.flag}" data-type="yes">Yes</div><div id="adopt_button_appdbrt" class="pre_button" data-flag="${response.flag}" data-type="no" >No</div></div>`;
                                                sessionStorage.setItem("adopt_yes_no",response.last);
                                            }
                                          jq_appdbrt("#progress_appdbrt").remove();
                                          setTimeout(function () {chatBox.scrollIntoView(false);}, 500); 
                                          flag_adopt = 0;
                                          width = 1;
                                        } else {
                                          width++;
                                          elem.css("width", parseInt(width) + "%");
                                        }
                                      }
                                    }
                                }, 500); // Delay execution to next tick 
                                 var specie=sessionStorage.getItem("specie");
                                if(specie=='dog' || specie=='cat')
                                    sessionStorage.setItem("qid",1);
                                else
                                    sessionStorage.setItem("qid",'');
                            }
                            sessionStorage.setItem("type",'');
                            sessionStorage.setItem("flag",'');
                        }
                        else 
                        {
                                html_to_show = `<div class="columns response_msg">
                            <div class="column actual_chat">
                            <img src="` + chat_icon + `"  class="chat_icon" />
                            <div class="notification is-success">
                            <div class="msg notification_part">Some error while response</div>
                            </div>
                            </div>
                            </div>`;
                            chatBox.innerHTML += html_to_show;
                            chatBox.scrollIntoView(false);
                            sessionStorage.setItem("type",'');
                            sessionStorage.setItem("flag",'');
                            sessionStorage.setItem("petcolove_location", '');
                            sessionStorage.setItem("has_no", '');
                            sessionStorage.setItem("adopt_yes_no",'');
                    }
                }
            });
        }
    });
});


function chatMessage(chat_icon,message,extraclass=''){

    var q_continue_btn_current=`<button id="qid4_continue_btn" class="pre_button" style="background: none;margin-top: 10px;margin-left: 25px;position: relative;font-weight: 300 !important;font-size: 16px;padding:7px 5px !important;">Continue</button>`;;
    if(extraclass!='response_msg4') 
        q_continue_btn_current='';        
    return `<div class="columns response_msg ${extraclass}">
                        <div class="column actual_chat">
                        <img src="` + chat_icon + `"  class="chat_icon" />
                        <div class="notification is-success">
                        <div class="msg notification_part">${message}</div>
                        </div>
                        </div>
                        ${q_continue_btn_current}
                        </div>
                       `;
}
function userMessage(message,ret=false){
    var user_img = jq_appdbrt('#avatar_user').val();
    var h= `<div class="columns user_msg">
    <div class="column is-one-third"></div>
    <div class="column user_column">
    <div class="notification is-success">
    <div class="msg notification_part">${message}</div>
    </div>
    <div class="user_avatar_outer"><img class="user_avatar" src="` + user_img + `" /></div>
    </div>
    </div>`;
    if(ret==true)
        return h;
        chatBox.innerHTML += h;
        chatBox.scrollIntoView(false);
}

function updateChatPosition(position) {
    const chatPopup = document.getElementById("chat-popup");
    const chatBox = document.getElementById("chat-box");
    jq_appdbrt('#notification-badge_appdbrt').addClass('notification-badge-'+position);
    // Reset styles
    chatPopup.style.left = '';
    chatPopup.style.right = '';
    chatPopup.style.bottom = '';
    chatPopup.style.top = '';
    chatBox.style.right = '';
    chatBox.style.left = '';
    chatBox.style.bottom = '';
    chatBox.style.top = '';

    // Apply specific styles based on the selected position
    switch (position) {
        case "left-bottom":
            
            chatPopup.style.bottom = "30px";
            chatPopup.style.left = "20px";
            chatPopup.style.width = "fit-content";

            // Updated style
            chatBox.style.bottom = "50px";
            chatBox.style.left = "25px"; // Changed from right: -259px to left: 25px
            break;

        case "right-bottom":
            chatPopup.style.bottom = "30px";
            chatPopup.style.right = "20px";

            chatBox.style.right = "0";
            break;

        case "left-center":
            chatPopup.style.top = "45%";
            chatPopup.style.left = "20px";
            chatPopup.style.width = "fit-content";

            // Updated style
            chatBox.style.bottom = "100px"; // Changed from top: -100% to bottom: 100px
            chatBox.style.left = "25px"; // Changed to left: 25px
            break;

        case "right-center":
            chatPopup.style.top = "45%";
            chatPopup.style.right = "20px"; // Added right: 20px

            // Updated style
            chatBox.style.top = ''; // Removed top: -100%
            break;
    }
}
jq_appdbrt(function () {
    updateChatPosition(obj.doobert_chatbot_postion);
    jq_appdbrt('#chat-popup').show();
    jq_appdbrt.post(
        jq_appdbrt('#ajax_url').val(),
        { action: 'get_petcolove_adopt'},
        function(response) {
            if (response.petco_love != 1) {
                jq_appdbrt('#petcolove-question').css('display', 'none');
            }
            if (response.adopt_pet != 1) {
                jq_appdbrt('#adopt-question').css('display', 'none');
            }
        }
    );  
});