    ////console.log("checking Through Promise==")
    //////////////console.log(CALLCID_CW_html);
    var start_time =  Date.now();

    const navigatorBrowser_CW_CALLCID =  "";

    //console.log(navigatorBrowser_CW_CALLCID);

    var CALLCID_CW_update_made = "0";
    var CALLCID_CW_ToDiv = "0"; 
    var  CALLCID_CW_loadFloatingwidget =   '0';  
    var  CALLCID_CW_loadDivwidget =   '0';  
    var  CALLCID_CW_CWPreview =   '';  
    console.log("CALLCID_CW_CWPreview =>",CALLCID_CW_CWPreview);
    //alert("asdfasd");
    var CALLCID_CW_hasError = "0";
    var CALLCID_CW_widget = '[]';
    ////////////console.log("CALLCID_CW_widget",CALLCID_CW_widget)
    var CALLCID_CWwidgetTimezone = 'America/New_York';
    //////////////console.log("CALLCID_CWwidgetTimezone",CALLCID_CWwidgetTimezone);
    var CALLCID_CW_optData = '""';
    var CALLCID_CW_theme_color = null;

    var CALLCID_AI_CHAT_FIELDS_SETTINGS = 'TRUE';

    var CALLCID_WHATSAPP_FIELDS_SETTINGS = 'TRUE';
    var CALLCID_WHATSAPP_PHONE_NUMBER = '';

    var CALLCID_CW_enable_countries = [{"id":"44","country_name":" Sierra Leone","iso_code":"SL","country_code":"+232","local_phone_cost":"10","toll_phone_cost":"20","country_code_cost":"+232","flag_emojis":"\ud83c\uddf8\ud83c\uddf1"},{"id":"39","country_name":"Aruba","iso_code":"AB","country_code":"+297","local_phone_cost":"1","toll_phone_cost":"2","country_code_cost":"+297","flag_emojis":"\ud83c\udde6\ud83c\uddfc"},{"id":"2","country_name":"Australia","iso_code":"AU","country_code":"+61","local_phone_cost":"3","toll_phone_cost":"15","country_code_cost":"+61","flag_emojis":"\ud83c\udde6\ud83c\uddfa"},{"id":"3","country_name":"Austria","iso_code":"AT","country_code":"+43","local_phone_cost":"1","toll_phone_cost":"1","country_code_cost":"+43","flag_emojis":"\ud83c\udde6\ud83c\uddf9"},{"id":"4","country_name":"Belgium","iso_code":"BE","country_code":"+32","local_phone_cost":"1","toll_phone_cost":"25","country_code_cost":"+32","flag_emojis":"\ud83c\udde7\ud83c\uddea"},{"id":"34","country_name":"Brazil","iso_code":"BR","country_code":"+55","local_phone_cost":"4","toll_phone_cost":"35","country_code_cost":"+55","flag_emojis":"\ud83c\udde7\ud83c\uddf7"},{"id":"5","country_name":"Canada","iso_code":"CA","country_code":"+1","local_phone_cost":"0.75","toll_phone_cost":"0.75","country_code_cost":"","flag_emojis":"\ud83c\udde8\ud83c\udde6"},{"id":"30","country_name":"Columbia","iso_code":"CO","country_code":"+57","local_phone_cost":"14","toll_phone_cost":"14","country_code_cost":"+57","flag_emojis":"\ud83c\udde8\ud83c\uddf4"},{"id":"37","country_name":"Costa Rica","iso_code":"CR","country_code":" +506","local_phone_cost":"1","toll_phone_cost":"2","country_code_cost":"+1","flag_emojis":"\ud83c\uddf7\ud83c\uddf4"},{"id":"42","country_name":"Croatia","iso_code":"HR","country_code":"+385","local_phone_cost":"5","toll_phone_cost":"20","country_code_cost":"+385","flag_emojis":"\ud83c\udded\ud83c\uddf7"},{"id":"6","country_name":"Czech Republic","iso_code":"CZ","country_code":"+420","local_phone_cost":"1.5","toll_phone_cost":"1.5","country_code_cost":"+420","flag_emojis":"\ud83c\udde8\ud83c\uddff"},{"id":"46","country_name":"Finland","iso_code":"FL","country_code":"+358","local_phone_cost":"5","toll_phone_cost":"10","country_code_cost":"+358","flag_emojis":" \ud83c\uddeb\ud83c\uddee"},{"id":"9","country_name":"France","iso_code":"FR","country_code":"+33","local_phone_cost":"1","toll_phone_cost":"1","country_code_cost":"+33","flag_emojis":"\ud83c\uddeb\ud83c\uddf7"},{"id":"29","country_name":"Germany","iso_code":"DE","country_code":"+49","local_phone_cost":"3","toll_phone_cost":"3","country_code_cost":"+49","flag_emojis":"\ud83c\udde9\ud83c\uddea"},{"id":"40","country_name":"Greece","iso_code":"GR","country_code":"+30","local_phone_cost":"1","toll_phone_cost":"2","country_code_cost":"+30","flag_emojis":"\ud83c\uddec\ud83c\uddf7"},{"id":"11","country_name":"Hong Kong","iso_code":"HK","country_code":"+852","local_phone_cost":"6","toll_phone_cost":"25","country_code_cost":"+852","flag_emojis":"\ud83c\udded\ud83c\uddf0"},{"id":"27","country_name":"India","iso_code":"IN","country_code":"+91","local_phone_cost":"0","toll_phone_cost":"0","country_code_cost":"+91","flag_emojis":"\ud83c\uddee\ud83c\uddf3"},{"id":"12","country_name":"Ireland","iso_code":"IE","country_code":"+353","local_phone_cost":"1.5","toll_phone_cost":"1.5","country_code_cost":"+353","flag_emojis":"\ud83c\uddee\ud83c\uddea"},{"id":"14","country_name":"Italy","iso_code":"IT","country_code":"+39","local_phone_cost":"1","toll_phone_cost":"1","country_code_cost":"+39","flag_emojis":"\ud83c\uddee\ud83c\uddf9"},{"id":"15","country_name":"Japan","iso_code":"JP","country_code":"+81","local_phone_cost":"5","toll_phone_cost":"25","country_code_cost":"+81","flag_emojis":"\ud83c\uddef\ud83c\uddf5"},{"id":"43","country_name":"Malaysia","iso_code":"MY","country_code":"+60","local_phone_cost":"0","toll_phone_cost":"0","country_code_cost":"+60","flag_emojis":"\ud83c\uddec\ud83c\uddf7"},{"id":"28","country_name":"Mexico","iso_code":"MX","country_code":"+52","local_phone_cost":"3","toll_phone_cost":"3","country_code_cost":"+52","flag_emojis":"\ud83c\uddf2\ud83c\uddfd"},{"id":"16","country_name":"Netherlands","iso_code":"NL","country_code":"+31","local_phone_cost":"3","toll_phone_cost":"3","country_code_cost":"+31","flag_emojis":"\ud83c\uddf3\ud83c\uddf1"},{"id":"17","country_name":"New Zealand","iso_code":"NZ","country_code":"+64","local_phone_cost":"3","toll_phone_cost":"3","country_code_cost":"+64","flag_emojis":"\ud83c\uddf3\ud83c\uddff"},{"id":"41","country_name":"Nigeria","iso_code":"NG","country_code":"+234","local_phone_cost":"15","toll_phone_cost":"20","country_code_cost":"+234","flag_emojis":"\ud83c\uddf3\ud83c\uddec"},{"id":"38","country_name":"Norway","iso_code":"NO","country_code":"+47","local_phone_cost":"1","toll_phone_cost":"2","country_code_cost":"+1","flag_emojis":"\ud83c\uddf3\ud83c\uddf4"},{"id":"35","country_name":"Poland","iso_code":"PL","country_code":"+48","local_phone_cost":"2","toll_phone_cost":"20","country_code_cost":"+48","flag_emojis":"\ud83c\uddf5\ud83c\uddf1"},{"id":"19","country_name":"Portugal","iso_code":"PT","country_code":"+351","local_phone_cost":"1","toll_phone_cost":"25","country_code_cost":"+351","flag_emojis":"\ud83c\uddf5\ud83c\uddf9"},{"id":"36","country_name":"Singapore","iso_code":"SG","country_code":"+65","local_phone_cost":"2","toll_phone_cost":"20","country_code_cost":"+65","flag_emojis":"\ud83c\uddf8\ud83c\uddec"},{"id":"32","country_name":"Slovakia","iso_code":"SK","country_code":"+421","local_phone_cost":"1","toll_phone_cost":"25","country_code_cost":"+421","flag_emojis":"\ud83c\uddf8\ud83c\uddf0"},{"id":"25","country_name":"South Africa","iso_code":"ZA","country_code":"+27","local_phone_cost":"1.5","toll_phone_cost":"2","country_code_cost":"+27","flag_emojis":"\ud83c\uddff\ud83c\udde6"},{"id":"21","country_name":"Spain","iso_code":"ES","country_code":"+34","local_phone_cost":"2","toll_phone_cost":"2","country_code_cost":"+34","flag_emojis":"\ud83c\uddea\ud83c\uddf8"},{"id":"22","country_name":"Sweden","iso_code":"SE","country_code":"+46","local_phone_cost":"1","toll_phone_cost":"1","country_code_cost":"+46","flag_emojis":"\ud83c\uddf8\ud83c\uddea"},{"id":"23","country_name":"Switzerland","iso_code":"CH","country_code":"+41","local_phone_cost":"1","toll_phone_cost":"1","country_code_cost":"+41","flag_emojis":"\ud83c\udde8\ud83c\udded"},{"id":"45","country_name":"United Arab Emirates","iso_code":"AE","country_code":"+971","local_phone_cost":"20","toll_phone_cost":"20","country_code_cost":"+971","flag_emojis":"\ud83c\udde6\ud83c\uddea"},{"id":"24","country_name":"United Kingdom","iso_code":"GB","country_code":"+44","local_phone_cost":"1","toll_phone_cost":"2","country_code_cost":"+44","flag_emojis":"\ud83c\uddec\ud83c\udde7"},{"id":"1","country_name":"United States","iso_code":"US","country_code":"+1","local_phone_cost":"1","toll_phone_cost":"2","country_code_cost":"+1","flag_emojis":"\ud83c\uddfa\ud83c\uddf8"},{"id":"31","country_name":"Vietnam","iso_code":"VN","country_code":"+84","local_phone_cost":"36","toll_phone_cost":"36","country_code_cost":"+84","flag_emojis":"\ud83c\uddfb\ud83c\uddf3"}];

    var  CALLCID_AI_CHAT_FIELDS_Toggle = false;
    var CALLCID_CW_json = CALLCID_CW_widget.replace("\n","\\n");
    var CALLCID_CW_json1 = CALLCID_CW_json.replace("\r","\\r");
    CALLCID_CW_json1 = CALLCID_CW_json1.replace(/\n/g, "\\n")
               .replace(/\\'/g, "\\'")
               .replace(/\\"/g, '\\"')
               .replace(/\\&/g, "\\&")
               .replace(/\r/g, "\\r")
               .replace(/\\t/g, "\\t")
               .replace(/\\b/g, "\\b")
               .replace(/\\f/g, "\\f");
    // remove non-printable and other non-valid JSON chars
    CALLCID_CW_json1 = CALLCID_CW_json1.replace(/[\u0000-\u0019]+/g,"");
    var CALLCID_CW_widgetJson = JSON.parse(CALLCID_CW_json1);
    CALLCID_CW_optDataJson = JSON.parse(CALLCID_CW_optData);
    var CALLCID_CW_widget_id = 'jv2Og2Fk58pK22YBZvGrfXbJDew7zzI2sOE8LWSGq0I=';
    var CALLCID_CW_widget_id_enc = 'jv2Og2Fk58pK22YBZvGrfXbJDew7zzI2sOE8LWSGq0I%3D';
    var CALLCID_CW_UI = '';
    ////console.log("CALLCID_CW_UI",CALLCID_CW_UI);
    var CALLCID_CW_base_url = 'https://widget.callcid.com';
    //////console.log("CALLCID_CW_base_url",CALLCID_CW_base_url);
    var CALLCID_CW_appointment_link = '';
    var CW_isMobileDevice = /Mobi/i.test(window.navigator.userAgent);
    var CALLCID_CW_platform = (CW_isMobileDevice) ? 'mobile': 'desktop';
    ////////////console.log(" CALLCID_CW_widgetJson.show_on_desktop", CALLCID_CW_widgetJson.show_on_desktop);
    var CALLCID_CW_show_on_mobile = (CALLCID_CW_widgetJson.show_on_mobile !== null && CALLCID_CW_widgetJson.show_on_mobile !== undefined) ? CALLCID_CW_widgetJson.show_on_mobile : false ;
    var CALLCID_CW_show_on_desktop = (CALLCID_CW_widgetJson.show_on_desktop !== null && CALLCID_CW_widgetJson.show_on_desktop !== undefined) ? CALLCID_CW_widgetJson.show_on_desktop : false;
    ////////////console.log("CALLCID_CW_show_on_desktop",CALLCID_CW_show_on_desktop);
    var CALLCID_CW_load_widget = false;
    var country = '';
    var is_scheduled_call = 0;
    var trigger_update = 0; // THIS WILL LOAD FRESH HTML EVEN THERE IS NO UPDATE FROM PANEL
    var userCountryData = '{}' ;
    var CW_countyData = JSON.parse(userCountryData);
    var CW_W_prefix = "CALLCID_CW_";
    var CALLCID_CW_Ai_Chat_Widget_Cls_Msg = '';
    var CALLCID_CW_Ai_Chat_Widget_Thx_Msg = '';
    var CALLCID_CW_outout ="";
    var CALLCID_CW_TOKEN_GENERATE = "";
    var CALLCID_CW_LoadPromise ={};
    var CALLCID_RejectLoadPromise,CALLCID_CW_ResolveLoadPromise;
    var CALLCID_CW_DateHelper = {
        addDays : function(aDate, numberOfDays) {
            aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
            return aDate;                                  // Return the date
        },
        format : function format(date) {
            return [
               ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
               ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
               date.getFullYear()                          // Get full year
            ].join('/');                                   // Glue the pieces together
        }
    }
    //Create the element using the createElement method.
//    window.onload = function() {
        // PROMISE SECTION
        //////console.log("Load 1");
        var CALLCID_CW_myDiv = document.createElement("div");
        CALLCID_CW_LoadPromise = new Promise(function(resolve,reject){
            //`cw-${CALLCID_CW_widget_id}-hiddenTill`            
            CALLCID_CW_ResolveLoadPromise = resolve;             
            CALLCID_RejectLoadPromise = reject;
            // CHECKING IF USER HAS PUT WIDGET TO HIDDEN
           var hiddenTill = localStorage.getItem(`cw-${CALLCID_CW_widget_id}-hiddenTill`);
           //////console.log("hiddenTill => 1.1 ",hiddenTill);
           if(hiddenTill !== null && hiddenTill !== undefined){
            //////console.log("hiddenTill FOUND");
               // GOT DESIRED VALUE
               var currentTime = new Date().getTime();
               if(hiddenTill > currentTime ){
                   //////console.log("under Hidden Period");
                   // STILL UNDER HIDDEN PERIOD
                   //console.log("Reject 3");
                   CALLCID_RejectLoadPromise();
                   return false;
               } else {
                   // Disable time has passed.
                   //////console.log("hiddenTill NOT FOUND");
                   localStorage.removeItem(`cw-${CALLCID_CW_widget_id}-hiddenTill`);
               }
           }
             //////console.log("Load 2");
            // CHECKING IF USER HAS PUT WIDGET TO HIDDEN
            CALLCID_CW_myDiv.id = 'mDw'+CALLCID_CW_UI;
            //Add your content to the DIV
            CALLCID_CW_myDiv.innerHTML = `<div class='contentLink_${CALLCID_CW_UI}'  i-htm='https://widget.callcid.com/callwidget/callwidget_htm_1.php?cID=jv2Og2Fk58pK22YBZvGrfXbJDew7zzI2sOE8LWSGq0I%3D&v=20260418194249&CWToDiv=${CALLCID_CW_ToDiv}&lu_enc=${CALLCID_CW_UI}'></div>`;
            //Finally, append the element to the HTML body
            //document.body.addEventListener("load", CALLCID_CW_init(), false);
            CALLCID_CW_myDiv.addEventListener("load", CALLCID_CW_init(), false);
            function CALLCID_CW_init(){
                //console.log("dasdfas 111");
                var urlEncodedWidgetId = CALLCID_CW_widget_id.replace("+","%2B").replace("=","%3D").replace("/","%2F");
                
                //var urlEncodedWidgetId = CALLCID_CW_widget_id;
                //console.log("urlEncodedWidgetId",urlEncodedWidgetId)
                var CALLCID_CW_totalScripts = document.querySelectorAll(`[src="${CALLCID_CW_base_url}/call-widget?cID=${urlEncodedWidgetId}"]`);
                
                if(CALLCID_CW_totalScripts.length > 1){
                    ////console.log("2. lands Here");
                    alert("Please Add Widget Script Once Only!");
                    return false;
                }

               // if(CALLCID_CW_loadFloatingwidget == '1'){
                    //console.log(".1 CALLCID_CW_loadFloatingwidget", CALLCID_CW_loadFloatingwidget);
                //////console.log("DIV LOADED");
                //////console.log("BODY LOADED");
                    setTimeout(function(){
                      ////////console.log("SETTIMEOUT ADDED");
                       document.body.appendChild(CALLCID_CW_myDiv);
                  
                      var link1 = document.createElement('link');
                        link1.setAttribute("rel", "stylesheet");
                        link1.setAttribute("type", "text/css");
                        link1.onload = function(){
                           //////console.log('loaded');
                            }
                     
                        // Adding Css From CDN 
                       
                        //link1.setAttribute("href", 'https://widget.callcid.com/css/callwidget.css?v=202604181942491');

                        
                        link1.setAttribute("href", 'https://d8tecr7d2qpx8.cloudfront.net/connectboss-cdn/connect-boss-min-css.css?v=202604181942491');
                        
                        document.getElementsByTagName("head")[0].appendChild(link1);

                        var link1 = document.createElement('link');
                        link1.setAttribute("rel", "stylesheet");
                        link1.setAttribute("type", "text/css");
                        link1.onload = function(){ ////////////////////console.log('loaded');
                           
                        }
                       
                        link1.setAttribute("href", 'https://widget.callcid.com/css/fonts-min.css?v=202604181942491');

                       //link1.setAttribute("href", 'https://d8tecr7d2qpx8.cloudfront.net/callwidget-ms-min.css?v=202604181942491');
                        document.getElementsByTagName("head")[0].appendChild(link1);
                        //console.log("dddd")
                        CALLCID_CW_checkStatus();
                      },100);
                //} else
    
            }
        });

        CALLCID_CW_LoadPromise.then(CALLCID_CW_postResolved,CALLCID_CW_RejectCB);
        /* RESOLVED */

        // function CALLCID_CW_ResolvCB(){

        //     CALLCID_CW_postResolved();
        // }
        /* Rejected  */

        function CALLCID_CW_RejectCB(){
            //////console.log("Rejected =>");
            localStorage.removeItem(`cw-${CALLCID_CW_widget_id}-lu`);
            localStorage.removeItem(`cw-${CALLCID_CW_widget_id}`);
        }

        function CALLCID_CW_LoadWidgetToDiv(){

            const addClassInnerDivWidget = "formDivWidget"; //   
            
            if(CALLCID_CW_loadDivwidget){
                var Targetdivs = document.getElementsByClassName(`cwTargetScript-${CALLCID_CW_UI}`);
                ////console.log("Targetdivs.length",Targetdivs.length);
                for (i = 0; i < Targetdivs.length; i++) {
                   //= Targetdivs[i];
                   Targetdivs[i].innerHTML = ``;
                   Targetdivs[i].classList.add(addClassInnerDivWidget);

                }

            }
        }




//var resText = localStorage.getItem(`cw-${CALLCID_CW_widget_id}`);

function CALLCID_CW_checkStatus(){
    //console.log("DDD");
    var CALLCID_CW_lu = localStorage.getItem(`cw-${CALLCID_CW_widget_id}-lu`); // LAST UPDATE DATE
    var saveObj = {
        wi:CALLCID_CW_widget_id,
        lu:CALLCID_CW_lu
    };
    //////console.log("Checking Status");
    var saveObj = new FormData();
    saveObj.append('wi', CALLCID_CW_widget_id);
    saveObj.append('lu', CALLCID_CW_lu);
   CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=c-s", saveObj)
  .then(result => {
        if(result.status == 1){
            // IF REQUEST IS FINE
            // WIDGET IS VALID
            //console.log("HJKS");
            if(result.lu_status == 1){
            
                // IF WAS LAST UPDATED
                // MAKING FRESH CALL TO LOAD HTML
                CALLCID_CW_includeHTML_NEW();
            } else {
                // IF NO UPDATE WAS MADE SINCE LAST LOADED
                // LODING FROM LS
                ////console.log("CALLCID_CW_update_made",CALLCID_CW_update_made);
                if(CALLCID_CW_update_made == 1){
                    //////console.log("**MANUALLY TRIGGERED UPDATE MADE TO LOAD LATEST INFO**")
                    // TRIGGERING UPDATE FROM CODE
                    CALLCID_CW_includeHTML_NEW();
                    
                } else {
                    ////console.log("ELSE");
                    var resText = localStorage.getItem(`cw-${CALLCID_CW_widget_id}`);
                    //resText = null;
                    if (resText === null || resText == '') {
                        //////console.log("**UPDATE ARE NOT MADE & DID **NOT** FOUND VALUE IN LS**")
                        // IF UPDATE IS NOT MADE
                        // AND ALSO THERE IS NO DATA IN LOCAL STORAGE
                        CALLCID_CW_includeHTML();
                    } else {
                        //////////console.log("**UPDATE ARE NOT MADE & FOUND VALUE IN LS**")
                        if(resText.search("ERRORCode") == -1){
                            //////console.log("LS LOADED CONTENT");
                            CALLCID_CW_myDiv.innerHTML = resText;
                            CALLCID_CW_ResolveLoadPromise();
                            CALLCID_CW_LoadWidgetToDiv();
                        } else {
                            CALLCID_CW_includeHTML();
                        }

                    }

                }

                //CALLCID_CW_includeHTML();
            }
        } else {
            // IF WIDGET IS NOT VALID
            //////console.log("Rejected 1");
            CALLCID_CW_RejectCB();
            CALLCID_CW_myDiv.innerHTML = result.message;
            ////////////console.log(result.message);
            localStorage.removeItem(`cw-${CALLCID_CW_widget_id}-lu`);
            localStorage.removeItem(`cw-${CALLCID_CW_widget_id}`);
        }
  });
}

let widgetVMHostRes;
let widgetVMHostResClear;
function checkHostRespond(reqId,parentNode){
    if(reqId != ''){
        var saveObj = new FormData();
        saveObj.append('request_id', reqId);
        saveObj.append('wi', CALLCID_CW_widget_id);

        CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-h-r", saveObj)
        .then(result => {
            if(result.status == 1 && result.host_respond == 1){
                clearInterval(widgetVMHostRes);
                clearTimeout(widgetVMHostResClear);
                
                setTimeout(function(){
                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                    var cw_create_url = `${CALLCID_CW_base_url}/video_meeting?topic=${result.topic}&token=${result.user_token}&reqId=${result.request_id}&w_req=1&username=${result.username}`;
                    window.location.href = cw_create_url;
                    
                    parentNode.querySelector("#video_meeting_form").style.display = "block";
                    parentNode.querySelector("#sbmt-video-rq").style.display = "block";
                    parentNode.querySelector("#video_meeting_loader").style.display = "none"; 

                    CALLCID_CW_clearmsg();
                },3000);

                
            }else if(result.status == 1 && result.host_respond == 2){
                clearInterval(widgetVMHostRes);
                clearTimeout(widgetVMHostResClear);

                parentNode.querySelector("#video_meeting_form").style.display = "block";
                parentNode.querySelector("#sbmt-video-rq").style.display = "block";
                parentNode.querySelector("#video_meeting_loader").style.display = "none"; 

                var items = document.getElementsByClassName('alert_message');
                for (var i=0; i < items.length; i++) {
                    items[i].innerHTML = '';
                }

                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>${result.message}</div>`,parentNode);
                setTimeout(function(){
                    CALLCID_CW_clearmsg();
                },3000);
            }
        });
    }
}

function CW_Join_VM(button){
    var url = button.getAttribute("data-url");
    
    // Open the URL in a new tab
    if (url) {
        window.location.href = url;
    } else {
        console.error("Data URL not found");
    }
}

  //  } // WHEN WINDOW IS LOADED

    function CALLCID_CW_includeHTML_NEW() {
        var elmnt = document.getElementById(`mDw${CALLCID_CW_UI}`);
        if(CALLCID_CW_update_made){
            var CALLCID_CW_html = ``;
            ////////////console.log("CALLCID_CW_html",CALLCID_CW_html);
            if(CALLCID_CW_html ==  null || CALLCID_CW_html == ''){
                //////////console.log("IF");
                CALLCID_CW_includeHTML();
            } else {
                //////console.log("ELSE");
                if(CALLCID_CW_platform == 'mobile' && CALLCID_CW_show_on_mobile == '1'){
                    CALLCID_CW_load_widget = true;
                } else if(CALLCID_CW_platform == 'desktop' && CALLCID_CW_show_on_desktop == '1'){
                    CALLCID_CW_load_widget = true;
                }
                console.log("CALLCID_CW_CWPreview",CALLCID_CW_CWPreview);
                if(CALLCID_CW_load_widget){
                    if(CALLCID_CW_loadFloatingwidget == '1' && !CALLCID_CW_CWPreview){
                        elmnt.innerHTML = CALLCID_CW_html;
                    }
                    CALLCID_CW_ResolveLoadPromise();
                    if(CALLCID_CW_loadDivwidget == '1'){
                        CALLCID_CW_LoadWidgetToDiv();
                    }
                    
                } 

                if(CALLCID_CW_hasError == "0"){
                    localStorage.setItem(`cw-${CALLCID_CW_widget_id}`, CALLCID_CW_html);
                    localStorage.setItem(`cw-${CALLCID_CW_widget_id}-lu`, CALLCID_CW_widgetJson.dateUpdated);
                } else {
                //////console.log("Rejected 2");
                    CALLCID_CW_RejectCB();
                    localStorage.removeItem(`cw-${CALLCID_CW_widget_id}-lu`);
                    localStorage.removeItem(`cw-${CALLCID_CW_widget_id}`);
                }
            }
            ////////////console.log("CALLCID_CW_html",CALLCID_CW_html);

        } else {
            // IF NO UPDATES TRIGGERED
            var resText = localStorage.getItem(`cw-${CALLCID_CW_widget_id}`);
            //resText = null;
            if (resText === null || resText == '') {
                ////////////console.log("NEITHER UPDATE MADE NORE FOUND IN LS");
                CALLCID_CW_includeHTML();
            } else {
                if(resText.search("ERRORCode") == -1){
                    if(CALLCID_CW_platform == 'mobile' && CALLCID_CW_show_on_mobile == '1'){
                        CALLCID_CW_load_widget = true;
                    } else if(CALLCID_CW_platform == 'desktop' && CALLCID_CW_show_on_desktop == '1'){
                        CALLCID_CW_load_widget = true;
                    }
                    
                    if(CALLCID_CW_load_widget){
                        if(CALLCID_CW_loadFloatingwidget == '1' && !CALLCID_CW_CWPreview){
                            elmnt.innerHTML = CALLCID_CW_html;
                        }
                        CALLCID_CW_ResolveLoadPromise();
                        if(CALLCID_CW_loadDivwidget == '1'){
                            CALLCID_CW_LoadWidgetToDiv();
                        }
                        
                    } 
                } else {
                    CALLCID_CW_includeHTML();
                }
            }
        }

    }

    


	function CALLCID_CW_includeHTML() {
        ////////console.log("CALLCID_CW_includeHTML_NEW CALLED");
      //////console.log("CALLCID_CW_includeHTML IS BEING CALLED SOME HOW")
	  var z, i, elmnt, file, xhttp;
      //z = document.getElementsByTagName("*");
      z = document.getElementsByClassName(`contentLink_${CALLCID_CW_UI}`);
      //////console.log("z.length",z.length);
	  for (i = 0; i < z.length; i++) {
	    elmnt = z[i];
	    /*search for elements with a certain atrribute:*/
	    file = elmnt.getAttribute("i-htm");
	    if (file) {

            if(CALLCID_CW_platform == 'mobile' && CALLCID_CW_show_on_mobile == '1'){
                CALLCID_CW_load_widget = true;
            } else if(CALLCID_CW_platform == 'desktop' && CALLCID_CW_show_on_desktop == '1'){
                CALLCID_CW_load_widget = true;
            }


	      /* Make an HTTP request using the attribute value as the file name: */
          ////////////////////console.log(CALLCID_CW_load_widget); 
          if(CALLCID_CW_load_widget){
            // IF SETTING IS THERE FOR LOADING WIDGET
             xhttp = new XMLHttpRequest();
              xhttp.onreadystatechange = function() {
                if (this.readyState == 4) {
                   // //////////////////console.log(this.responseText);
                  if (this.status == 200) {
                      //////////////console.log("THIS CONDITION")
                    //elmnt.innerHTML = this.responseText;
                    if(CALLCID_CW_platform == 'mobile' && CALLCID_CW_show_on_mobile == '1'){
                        CALLCID_CW_load_widget = true;
                    } else if(CALLCID_CW_platform == 'desktop' && CALLCID_CW_show_on_desktop == '1'){
                        CALLCID_CW_load_widget = true;
                    }
                    
                    if(CALLCID_CW_load_widget){
                        if(CALLCID_CW_loadFloatingwidget == '1' && !CALLCID_CW_CWPreview){
                            elmnt.innerHTML = this.responseText;
                        }
                        CALLCID_CW_ResolveLoadPromise();
                        if(CALLCID_CW_loadDivwidget == '1'){
                            CALLCID_CW_LoadWidgetToDiv();
                        }
                        
                    } 
                    //elmnt.innerHTML = CALLCID_CW_html;
                    //setCookie(`cw-${CALLCID_CW_widget_id}`, this.responseText, 30);
                    localStorage.setItem(`cw-${CALLCID_CW_widget_id}`, this.responseText);
                    localStorage.setItem(`cw-${CALLCID_CW_widget_id}-lu`, CALLCID_CW_widgetJson.dateUpdated);

                   }
                  if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
                  /* Remove the attribute, and call this function once more: */
                  elmnt.removeAttribute("i-htm");
                  CALLCID_CW_includeHTML();
                  CALLCID_CW_ResolveLoadPromise();
                }
              }
              xhttp.open("GET", file, true);
              xhttp.send();
          } else {
            //////////////////console.log("NOT ENABLED FOR CURRENT CALLCID_CW_platform");
          }

	      /* Exit the function: */
	      return;
	    }
	  }
	}

	window.addEventListener('load', (event) => {

    //     var link1 = document.createElement('link');
    //     link1.setAttribute("rel", "stylesheet");
    //     link1.setAttribute("type", "text/css");
    //     link1.onload = function(){
    //        // //////////////////console.log('loaded');
    //          }
    //     link1.setAttribute("href", 'https://widget.callcid.com/css/callwidget.css?v=202604181942491');
    //     document.getElementsByTagName("head")[0].appendChild(link1);


    //     var link1 = document.createElement('link');
    //     link1.setAttribute("rel", "stylesheet");
    //     link1.setAttribute("type", "text/css");
    //     link1.onload = function(){ ////////////////////console.log('loaded');
    // }
    //     link1.setAttribute("href", 'https://widget.callcid.com/css/callwidget_ms.css?v=202604181942491');
    //     document.getElementsByTagName("head")[0].appendChild(link1);
    //         var parentEl = document.querySelector('#mDw');
  			

    }); // window loaded
    
    /* 
    * RESOLVED
    */
   function  CALLCID_CW_postResolved() {
    var callEl = document.getElementsByClassName("call_schedule_wrapper");
    var CALLCID_CW_wrappers = document.getElementsByClassName(`wrapper_${CALLCID_CW_UI}`);    
    
    //////console.log("CALLCID_CW_postResolved => Called")
  if (CALLCID_CW_wrappers.length > 0 ) {
    var end_time =  Date.now();
    for (i = 0; i < CALLCID_CW_wrappers.length; i++) {
        
        CALLCID_CW_wrappers[i].style.display = "block";
        var CALLCID_CW_currentWrapper = CALLCID_CW_wrappers[i];
        /* WIDGET TEXT INFORMATION */
        CALLCID_CW_currentWrapper.querySelector("#cvt").addEventListener("click", function(){
            var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
            currentNodeParent.querySelector("#main_opt").style.display = "none";
            currentNodeParent.querySelector("#vtOpt").style.display = "block";
        });
        /* WIDGET CALL  */
        CALLCID_CW_wrappers[i].querySelector("#cvp").addEventListener("click", function(){
            var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
            currentNodeParent.querySelector("#main_opt").style.display = "none";
            currentNodeParent.querySelector("#vpOpt").style.display = "block";
        });
        /* Voice Message  */
        CALLCID_CW_wrappers[i].querySelector("#cvlvm").addEventListener("click", function(){

            if(navigatorBrowser_CW_CALLCID == "Safari"){
                alert("The Safari browser does not support voice recording. Please try using Chrome instead.")
                return false;
            }
            
            var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
            currentNodeParent.querySelector("#main_opt").style.display = "none";
            currentNodeParent.querySelector("#vvmOpt").style.display = "block";
        });

        /* WIDGET AI CHAT  */
            CALLCID_CW_wrappers[i].querySelector("#cvaic").addEventListener("click", function(){

              var settingsObject = validateAiChatSettings();
              var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
             if(settingsObject === 'TRUE') { // default settings and all values are required
                currentNodeParent.querySelector("#main_opt").style.display = "none";
                currentNodeParent.querySelector("#vaicOpt").style.display = "block";
               }else{

                var allFieldsAreDisabled  = Object.values(JSON.parse(CALLCID_AI_CHAT_FIELDS_SETTINGS)).every(value => value == 0);

                console.log("All fields are Required",allFieldsAreDisabled);

                if(allFieldsAreDisabled){
                    aiChatSubmitWithoutFormAllFieldsDisabled(currentNodeParent);
                      console.log("Disabled Asked For Chat"); 
                      return false;
                }

                 validateAiChatHTMLFieldsHideShow(JSON.parse(CALLCID_AI_CHAT_FIELDS_SETTINGS),currentNodeParent);
                     // we have settings
               }
            });

        /* VIDEO WIDGET  */
        CALLCID_CW_wrappers[i].querySelector("#cvvm").addEventListener("click", function(){
            var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
            currentNodeParent.querySelector("#main_opt").style.display = "none";
            currentNodeParent.querySelector("#vvideoOpt").style.display = "block";
        });

        /* WHATSAPP WIDGET */
            CALLCID_CW_wrappers[i].querySelector("#cvwa").addEventListener("click", function(){
                var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
                var settingsObject = CALLCID_WHATSAPP_FIELDS_SETTINGS !== 'TRUE' ? JSON.parse(CALLCID_WHATSAPP_FIELDS_SETTINGS || '{}') : {};
                var {"whatsapp-name-show": whatsAppNameShow,"whatsapp-email-show": whatsAppEmailShow,  "whatsapp-phone-show": whatsAppPhoneShow } = settingsObject;
                if((CALLCID_WHATSAPP_FIELDS_SETTINGS != 'TRUE' && (whatsAppNameShow == 1 || whatsAppEmailShow == 1 || whatsAppPhoneShow == 1 )) ) { 
                    currentNodeParent.querySelector("#main_opt").style.display = "none";
                    currentNodeParent.querySelector("#vwaOpt").style.display = "block";
                }else{ 
                    openWhatsAppLink();
                }
            });

          // CALL WIDGET EMAIL BUTTON CW_CALLSING_cve
       if(CALLCID_CW_wrappers[i].querySelector("#CW_CALLSING_cve") !== null){
            CALLCID_CW_wrappers[i].querySelector("#CW_CALLSING_cve").addEventListener("click", function(){
                var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
                currentNodeParent.querySelector("#main_opt").style.display = "none";
                currentNodeParent.querySelector("#veOpt").style.display = "block";
            });
        }

        if(CALLCID_CW_wrappers[i].querySelector("#CW_CALLSING_cvBooking") !== null){
            CALLCID_CW_wrappers[i].querySelector("#CW_CALLSING_cvBooking").addEventListener("click", function(){
                window.open(CALLCID_CW_appointment_link, '_blank').focus();
            });
        }

        /* COUNTRY CODE SELECTION */

        var CALLCID_CW_loc = ((localStorage.getItem(`cw-client-loc`)) ); 
        var CALLCID_CW_tz = localStorage.getItem(`cw-${CALLCID_CW_widget_id}-tz`);
        var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);   
       
     if(CALLCID_CW_loc == null 
         || CALLCID_CW_LocRes == null
         || CALLCID_CW_tz == null
         ){
                 //////////console.log("level 1");
             CALLCID_CW_getGeoData(CALLCID_CW_currentWrapper)                       
         } else {
         //////////////console.log(loc);
             clientcountry = CALLCID_CW_loc;
              CALLCID_CW_countries.filter(function(c){
                     if(c.code == clientcountry){
                         ////console.log("CALLCID_CW_currentWrapper =>",CALLCID_CW_currentWrapper);
                         var iso_code =  c.code.toLowerCase()
                         //document.getElementById("text_country_id").value = c.dial_code;
                         if(CALLCID_CW_widgetJson.is_text_enabled && CALLCID_CW_currentWrapper.querySelector("#CW_T_C_DD_SEL") !== null){   
                            CALLCID_CW_currentWrapper.querySelector("#CW_T_C_DD_SEL").innerHTML = CALLCID_CW_currentWrapper.querySelector(`#CW_T_C_DD_LI_${iso_code}`).innerHTML;
                            CALLCID_CW_currentWrapper.querySelector('#CW_text_country_id').value = c.dial_code;
                         }
  
                         if(CALLCID_CW_currentWrapper.querySelector("#CW_P_C_DD_SEL") && CALLCID_CW_widgetJson.is_phone_enabled){
                             CALLCID_CW_currentWrapper.querySelector("#CW_P_C_DD_SEL").innerHTML = CALLCID_CW_currentWrapper.querySelector(`#CW_P_C_DD_LI_${iso_code}`).innerHTML;
                             CALLCID_CW_currentWrapper.querySelector("#cw-country_id").value = c.dial_code;
                         }

                         if(CALLCID_CW_currentWrapper.querySelector("#CW_VM_C_DD_SEL") && CALLCID_CW_widgetJson.is_voice_message_enabled){
                             CALLCID_CW_currentWrapper.querySelector("#CW_VM_C_DD_SEL").innerHTML = CALLCID_CW_currentWrapper.querySelector(`#CW_VM_C_DD_LI_${iso_code}`).innerHTML;
                             CALLCID_CW_currentWrapper.querySelector("#CW_voice_country_id").value = c.dial_code;
                         }
  
                         if(CALLCID_CW_currentWrapper.querySelector("#CW_E_C_DD_SEL") && CALLCID_CW_widgetJson.is_email_enabled){
                             CALLCID_CW_currentWrapper.querySelector("#CW_E_C_DD_SEL").innerHTML = CALLCID_CW_currentWrapper.querySelector(`#CW_E_C_DD_LI_${iso_code}`).innerHTML;
                             CALLCID_CW_currentWrapper.querySelector("#CW_EMAIL_country_id").value = c.dial_code;
                         }
                         if(CALLCID_CW_currentWrapper.querySelector("#CW_AIC_C_DD_SEL") && CALLCID_CW_widgetJson.is_chat_enabled){
                             CALLCID_CW_currentWrapper.querySelector("#CW_AIC_C_DD_SEL").innerHTML = CALLCID_CW_currentWrapper.querySelector(`#CW_AIC_C_DD_LI_${iso_code}`).innerHTML;
                             CALLCID_CW_currentWrapper.querySelector("#CW_chat_country_id").value = c.dial_code;
                         }
                         if(CALLCID_CW_currentWrapper.querySelector("#CW_VIDEO_C_DD_SEL") && CALLCID_CW_widgetJson.is_video_enabled){
                             CALLCID_CW_currentWrapper.querySelector("#CW_VIDEO_C_DD_SEL").innerHTML = CALLCID_CW_currentWrapper.querySelector(`#CW_VIDEO_C_DD_LI_${iso_code}`).innerHTML;
                             CALLCID_CW_currentWrapper.querySelector("#CW_video_country_id").value = c.dial_code;
                         }
                         if(CALLCID_CW_currentWrapper.querySelector("#CW_WHATSAPP_C_DD_SEL") && CALLCID_CW_widgetJson.is_whatsapp_enabled){
                             CALLCID_CW_currentWrapper.querySelector("#CW_WHATSAPP_C_DD_SEL").innerHTML = CALLCID_CW_currentWrapper.querySelector(`#CW_WHATSAPP_C_DD_LI_${iso_code}`).innerHTML;
                             CALLCID_CW_currentWrapper.querySelector("#CW_whatsapp_country_id").value = c.dial_code;
                         }
  
                     }
                     return c.code == clientcountry
                  });
                  // GETTING APPOINTMENT DROPDOWNS AS PER NEW TZ
                  var CallScheduleHtm = CALLCID_CW_getCallScheduleHtm(CALLCID_CW_tz,CALLCID_CWwidgetTimezone,CALLCID_CW_currentWrapper);
                  ////////////console.log("CallScheduleHtm",CallScheduleHtm);
        }


        // HIDING DROPDOWN WHEN CLICKED OUTSIDE OF DD
        document.addEventListener('click', function (e) {
            // var container = document.getElementById('CW_T_COUNTRIES');
                var container1 = CALLCID_CW_currentWrapper.querySelector('#CW_P_C_DD_WRAP');
                var container2 = CALLCID_CW_currentWrapper.querySelector('#CW_T_C_DD_WRAP');
                var container3 = CALLCID_CW_currentWrapper.querySelector('#CW_E_C_DD_WRAP');
                var container4 = CALLCID_CW_currentWrapper.querySelector('#CW_VM_C_DD_WRAP');
                var container5 = CALLCID_CW_currentWrapper.querySelector('#CW_AIC_C_DD_WRAP');
                var container6 = CALLCID_CW_currentWrapper.querySelector('#CW_VIDEO_C_DD_WRAP');
                var container7 = CALLCID_CW_currentWrapper.querySelector('#CW_WHATSAPP_C_DD_WRAP');
                var containers = CALLCID_CW_currentWrapper.getElementsByClassName("chat-country-list");
            for (var i = 0; i < containers.length; i++) {
            if (!containers[i].contains(e.target) && (container1 !== null && !container1.contains(e.target)) && (container2 !== null && !container2.contains(e.target)) && (container3 !== null && !container3.contains(e.target)) && (container4 !== null && !container4.contains(e.target)) && (container5 !== null && !container5.contains(e.target)) && (container6 !== null && !container6.contains(e.target)) && (container7 !== null && !container7.contains(e.target)) ) {
                    containers[i].style.display = 'none';
                }
                //containers[i].style.display="none";
            }
        }.bind(this));

        
        intializeTextSubmission(CALLCID_CW_currentWrapper);
        intializeEmailSubmission(CALLCID_CW_currentWrapper);
        intializePhoneSubmission(CALLCID_CW_currentWrapper);
        intializeChatSubmission(CALLCID_CW_currentWrapper);
        intializeVideoSubmission(CALLCID_CW_currentWrapper);
        intializeWASubmission(CALLCID_CW_currentWrapper);

     } //Iterating all the widget Instances


     function validatePopupEnterButton(){    

        var divElementChatWrapper = document.getElementById("aiChatWrapper");
        var divElementVaicOpt     = document.getElementById("vaicOpt");
        if (divElementChatWrapper && divElementVaicOpt) {
            var computedStyle        = window.getComputedStyle(divElementChatWrapper);
            var computedStyleVaicOpt = window.getComputedStyle(divElementVaicOpt);
            if (computedStyle.display === "block" &&  computedStyleVaicOpt.display === "block") {
                    return true;
                } else {
                return false;
                }
        }else{
            console.log("not working");
            return false;
        }
     }

     function validateAiChatSettings(){ // Validate AI Settings

        //console.log("ALL Settings",CALLCID_AI_CHAT_FIELDS_SETTINGS);

        if(CALLCID_AI_CHAT_FIELDS_SETTINGS  == 'TRUE'){ // means all fields are required and no action need to required
            return 'TRUE';
        }else {
            var allFieldsAreEnabled  = Object.values(JSON.parse(CALLCID_AI_CHAT_FIELDS_SETTINGS)).every(value => value == 1);
           // console.log("All Values are 1 in validateAiChatSettings ",allFieldsAreEnabled);
            if(allFieldsAreEnabled)
                return 'TRUE'

            return JSON.parse(CALLCID_AI_CHAT_FIELDS_SETTINGS);         
        }
     }

    
     function validateAiChatHTMLFieldsHideShow(settingsObject,parentNode) {

          var { "ai-name-show": aiChatNameShow,  "ai-email-show":aiEmailShow,"ai-phone-show": aiChatPhoneShow } = settingsObject;

          var { "ai-name-show": aiChatNameShow,  "ai-email-show":aiEmailShow,"ai-phone-show": aiChatPhoneShow } = settingsObject;

          var { "ai-name-required": aiChatNameRequired,"ai-email-required": aiChatEmailRequired,  "ai-phone-required": aiChatPhoneRequired } = settingsObject; // Placeholder


          if(aiChatNameRequired == 0){ 
            const nameInput = parentNode.querySelector("#chat_name");
             nameInput.placeholder = "Enter Your Name (Optional)";
           }

           if(aiChatEmailRequired == 0){ 
            const emailInput = parentNode.querySelector("#chat_email");
            emailInput.placeholder = "Enter Your Email (Optional)";
           }

           if(aiChatPhoneRequired == 0){ 
            const phoneInput = parentNode.querySelector("#chat_phone");
             phoneInput.placeholder = "Enter Mobile Number (Optional)";
           }

          var allfieldsHide = true;
          if( aiChatNameShow == 0 && aiEmailShow == 0 && aiChatPhoneShow == 0){
             allfieldsHide = false;
          }
    
          if(aiChatNameShow == 0){
            const chatNameTextBox = parentNode.querySelector("#chat_name"); 
            chatNameTextBox.value = 'Default-ai-name-assistant';
            chatNameTextBox.style.display = "none";
        
          }

          if(aiEmailShow == 0){
            const chatEmailTextBox = parentNode.querySelector("#chat_email"); 
            chatEmailTextBox.value = "default-ai@connectboss.com";
            chatEmailTextBox.style.display = "none";
           
          }

          if(aiChatPhoneShow == 0){

            const chatPhoneTextBox = parentNode.querySelector("#chat_phone"); 
            chatPhoneTextBox.value = "11111111111";
            chatPhoneTextBox.style.display = "none";
            const chatPhoneCountryBox = parentNode.querySelector("#CW_AIC_C_DD_SEL"); 
            chatPhoneCountryBox.style.display = "none";
            const chatPhoneCountryList = parentNode.querySelector("#CW_AIC_C_DD_WRAP"); 
            chatPhoneCountryList.style.display = "none";
          }

          if(allfieldsHide === false) { 
             aiChatSubmitWithoutFormAllFieldsDisabled(parentNode); // submit without form
          }else{
          
            parentNode.querySelector("#main_opt").style.display = "none";
            parentNode.querySelector("#vaicOpt").style.display = "block";
          }
             
         
       }

     function aiChatSubmitWithoutFormAllFieldsDisabled(parentNode){

                  
                 if(CALLCID_AI_CHAT_FIELDS_Toggle) {
                    parentNode.querySelector("#main_opt").style.display = "none";
                    parentNode.querySelector("#vaicOpt").style.display = "block"; 
                    return;
                  }

                    var name  = "default-ai-name-assistant";
                    var email = "default-ai@connectboss.com";
                    var phone = "+111111111111";
                    var country_id = "+1";
                    var saveObj = new FormData();
                        saveObj.append('name', name);
                        saveObj.append('phone', phone);
                        saveObj.append('email', email);
                        saveObj.append('country_id', country_id);
                        saveObj.append('wi', CALLCID_CW_widget_id);
                        var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
                        var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
                        if(CALLCID_CW_LocRes !== null){
                            var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
                            if(CALLCID_CW_LocResParsed){
                                // IF JSON IS VALID
                                CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
                                CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
                                CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
                                CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
                            }
                        }
                        saveObj.append('ip_address', CALLCID_CW_ip_address);
                        saveObj.append('city', CALLCID_CW_city);
                        saveObj.append('region', CALLCID_CW_region);
                        saveObj.append('country_name', CALLCID_CW_country_name);
                        saveObj.append('token', CALLCID_CW_TOKEN_GENERATE);

                       // var parentNode = document.getElementById('cvaic'); // change parent nod

                        var old_button_text = parentNode.querySelector("#sbmt-chat-rq").innerText;
                        parentNode.querySelector("#sbmt-chat-rq").setAttribute('disabled','disabled');
                        parentNode.querySelector("#sbmt-chat-rq").innerText = 'Starting...';
        
                        CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-ac", saveObj)
                        .then(result => {
                            parentNode.querySelector("#sbmt-chat-rq").removeAttribute('disabled');
                            parentNode.querySelector("#sbmt-chat-rq").innerText = old_button_text;
                            if(result.status == 1){
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                                CALLCID_CW_clearmsg();
                               // CALLCID_CW_resetForm(parentNode);
                               //
                                parentNode.querySelector("#main_opt").style.display = "none";

                                parentNode.querySelector("#vaicOpt .chat_actionButton").classList.add('aiChatScreen');                                
                                parentNode.querySelector("#aiChatFormWrapper").style.display = "none";
                                parentNode.querySelector("#sbmt-chat-rq").style.display = "none";
                                parentNode.querySelector("#sbmt-ques-rq").style.display = "block";                                
                                parentNode.querySelector("#aiChatWrapper").style.display = "block"; 
                                parentNode.querySelector("#ques-btn").style.display = "block";
                                parentNode.querySelector("#user_thread_id").value = result.call_widget_id; 
                                parentNode.querySelector("#aiChatWrapper .chat-area-box").innerHTML = "";
                                var responseLoader = createLoadingEle();
                                var chatAreaBox = parentNode.querySelector("#aiChatWrapper .chat-area-box");
                                var tempDiv = document.createElement('div');
                                tempDiv.innerHTML = responseLoader;

                                // Append the first child of the temporary div to the chat area
                                chatAreaBox.appendChild(tempDiv.firstChild);

                                //disable the ai chat form submit button
                                var buttonToDisable = document.querySelector("#aiChatWrapper #sbmt-chat-rq");
                                if (buttonToDisable) {
                                    buttonToDisable.disabled = true;
                                }

                                CALLCID_CW_Ai_Chat_Widget_Cls_Msg = result.closing;
                                CALLCID_CW_Ai_Chat_Widget_Thx_Msg = result.thankyou_msg;
                                parentNode.querySelector("#vaicOpt").style.display = "block"; ;
                                
                                CALLCID_AI_CHAT_FIELDS_Toggle  =true;
                                
                                setTimeout(function(){
                                    parentNode.querySelector("#aiChatWrapper .chat-area-box .received-message.loading-animation").remove();
                                    var userRecMsg = "Hi! I'm an AI chatbot. How can I help you?";
                                    if(result.opening != "" && result.opening != null){
                                        userRecMsg = result.opening;
                                    }
                                    var userRecCon = createMsgEle('received-message',userRecMsg);
                                    chatAreaBox.appendChild(userRecCon);
                                },3000);
                                

                            } else {
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
                                CALLCID_CW_clearmsg();
                            }

                        });
     }


    //wrapper_${CALLCID_CW_UI}
    ////////////console.log(`Execution time: ${end_time - start_time} ms`);
    // setTimeout(function(){
    //     document.getElementById("widget_wrapper").style.display = "block";
    // },200);
     // CALL WIDGET TEXT BUTTON
      

     
       // CALL WIDGET PHONE BUTTON
       
       // CHECKING IF BOOKING OPTION IS THERE
      
       //

     //clearInterval(checkExist);
      //var requestUrl = 'http://ip-api.com/json';

     




      /*Text Area Counter*/
      var w_ta = document.getElementsByClassName("w-ta");
       for (var i = 0; i < w_ta.length; i++) {
            $this = w_ta[i];
            let  limit = $this.getAttribute('data-limit');
           $this.addEventListener("keyup",function(){

                 var words = this.value.length;
                   if (words > parseInt(limit)) {
                     var trimmed = this.value.substring(0, parseInt(limit));
                     // Add a space at the end to make sure more typing creates new words
                     this.value = trimmed;
                   } else {
                       var item =  this.closest(".field-wrapper");
                       item.getElementsByClassName('w-counter')[0].innerHTML = words;
                   }
           });
          //Distribute(slides.item(i));
       }

    //    var chooseEl = document.getElementsByClassName("choose-time")[0];
    //    //////////////console.log("chooseEl",chooseEl);
    //     if(chooseEl !==  null && chooseEl !== undefined){
            
    //         for (var i = 0; i < chooseEl.length; i++) {
    //                 chooseEl[i].addEventListener("click",function(event){
    //                     event.preventDefault();
    //                     var callEl = document.getElementsByClassName("call_schedule_wrapper");
    //                     if(callEl[0].style.display == 'block'){
    //                         is_scheduled_call = 0
    //                         callEl[0].style.display = "none";
    //                     } else {
    //                         is_scheduled_call = 1;
    //                         callEl[0].style.display = "block";
    //                     }
    //                     });
    //         }
    //     }
        var clInEl = document.getElementsByClassName("clean-phone");
        var cleanTime =0;
        for (var i = 0; i < clInEl.length; i++) {
           clInEl[i].addEventListener("keyup",function(event){
           //clInEl[i].addEventListener("propertychange change click keyup input paste",function(event){
               var elm = this;
                   if(cleanTime) {
                         clearTimeout(cleanTime);
                   }
                   cleanTime = setTimeout(function(){
                          cleanInput(elm);
                   }, 1000);
           })
        }
        /*SUBMIT PHONE REQUEST*/
        //////////////console.log('document.getElementById("sbmt-ph-rq")',document.getElementById("sbmt-ph-rq"));
        function intializePhoneSubmission(parentNode){


            if(parentNode.querySelector("#sbmt-ph-rq")){
                parentNode.querySelector("#sbmt-ph-rq").addEventListener("click",function(){

                 const isAiChatOpen = validatePopupEnterButton();
                  if(isAiChatOpen === true) {
                        sendUserQuestion('vaicOpt')
                        return;
                   }
                    
                    var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
                    var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
                    if(CALLCID_CW_LocRes !== null){
                        var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
                        if(CALLCID_CW_LocResParsed){
                            // IF JSON IS VALID
                            CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
                            CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
                            CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
                            CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
                        }
                    }
                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Please wait, initializing call...</div>`,parentNode);
                    cleanInput(parentNode.querySelector("#call_phone"));
                    var name = parentNode.querySelector("#call_name").value;
                    var phone = parentNode.querySelector("#call_phone").value;
                    //////////console.log("EMAIL PHON",phone); return false;
                    var country_id = parentNode.querySelector("#cw-country_id").value;
                    if(name == '' || name == undefined || name == null ){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Error! Name is required</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    }
     
                    if(phone == '' || phone == undefined || phone == null ){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Error! Phone is required</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    }
     
                    if(country_id == '' || country_id == undefined || country_id == null ){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Error! Country is required</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    }
                    var call_date ='';
                    var call_time ='';
                    if(CALLCID_CW_widgetJson.enable_call_scheduling == '1' && is_scheduled_call == 1) {
                        // IF CALL SCHEDULING IS ENABLED
                         call_date = parentNode.querySelector("#call_date").value;
                         call_time = parentNode.querySelector(`#call_time_${call_date}`).value;
                        if(call_date == '' || call_date == undefined || call_date == null ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Error! Please Select Date</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
                        if(call_time == '' || call_time == undefined || call_time == null ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Error! Please Select Time</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
                    }
     
                    //////////////////console.log("CALLCID_CW_widgetJson.enable_disclaimer_phone",CALLCID_CW_widgetJson.enable_disclaimer_phone);
                    if(CALLCID_CW_widgetJson.enable_disclaimer_phone == '1'){
                        // IF DISCLAIMER IS ENABLED
                        if(CALLCID_CW_widgetJson.phone_accept_disclaimer_required ==  true && parentNode.querySelector("#enable_disclaimer_phone") !== null && parentNode.querySelector("#enable_disclaimer_phone") !== undefined){
                            var is_disclaimer_checked = parentNode.querySelector("#enable_disclaimer_phone").checked;
                            if(!is_disclaimer_checked){
                                CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Please accept disclaimer by clicking checkbox.</div>",parentNode);
                                CALLCID_CW_clearmsg();
                                return false;
                            }
                        }
     
                    }
                    var cust_time_zone = localStorage.getItem(`cw-${CALLCID_CW_widget_id}-tz`);
                    if(cust_time_zone == null){
                        cust_time_zone = 'America/New_York';
                    }
                    // //////////////////console.log("WORKING!!!!");
                    // return false;
                    var old_button_text = parentNode.querySelector("#sbmt-ph-rq").innerText;
                    parentNode.querySelector("#sbmt-ph-rq").setAttribute('disabled','disabled');
                    parentNode.querySelector("#sbmt-ph-rq").innerText = "Initializing call...";
                    // var saveObj = {
                    //     name : name,
                    //     phone: phone,
                    //     country_id:country_id,
                    //     is_scheduled_call:is_scheduled_call,
                    //     call_date: call_date,
                    //     call_time : call_time,
                    //     wi:CALLCID_CW_widget_id,
                    //     cust_time_zone:cust_time_zone
                    // };
     
                var saveObj = new FormData();
                saveObj.append('name', name);
                saveObj.append('phone', phone);
                saveObj.append('country_id', country_id);
                saveObj.append('is_scheduled_call', is_scheduled_call);
                saveObj.append('call_date', call_date);
                saveObj.append('call_time', call_time);
                saveObj.append('wi', CALLCID_CW_widget_id);
                saveObj.append('cust_time_zone', cust_time_zone);
     
                saveObj.append('ip_address', CALLCID_CW_ip_address);
                saveObj.append('city', CALLCID_CW_city);
                saveObj.append('region', CALLCID_CW_region);
                saveObj.append('country_name', CALLCID_CW_country_name);
              
                saveObj.append('token', CALLCID_CW_TOKEN_GENERATE);
     
     
                CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-c", saveObj)
                          .then(result => {
                               parentNode.querySelector("#sbmt-ph-rq").removeAttribute('disabled');
                                parentNode.querySelector("#sbmt-ph-rq").innerText = old_button_text;
                                if(result.status == 1){
                                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                                    CALLCID_CW_clearmsg();
                                    CALLCID_CW_resetForm(parentNode);
                                } else {
                                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
                                    CALLCID_CW_clearmsg();
                                }
                          });
                 });
             }
        }
       

        /*SUBMIT PHONE REQUEST*/

        function intializeTextSubmission(parentNode) {
            if(parentNode.querySelector("#sbmt-txt-rq") !== null){
                /*SUBMIT TEXT REQUEST*/
                parentNode.querySelector("#sbmt-txt-rq").addEventListener("click",function(){
                    // CLEANING PHONE NUMBER
                   
                    const isAiChatOpen =  validatePopupEnterButton();
                      //  console.log("Chat Methode",isAiChatOpen);
                    if(isAiChatOpen === true) {
                            sendUserQuestion('vaicOpt')
                            return;
                    }
                    
                   cleanInput(parentNode.querySelector("#text_phone"));
                   var name = parentNode.querySelector("#text_name").value;
                   var phone = parentNode.querySelector("#text_phone").value;
                   var country_id = parentNode.querySelector("#CW_text_country_id").value;
                   var text_messge = parentNode.querySelector("#text_messge").value;
                   ////console.log("name",name,"phone",phone)
                   if(name == '' || name == undefined || name == null ){
                       CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Name is required</div>",parentNode);
                       CALLCID_CW_clearmsg();
                       return false;
                   }
                   //CALLCID_CW_resetForm(parentNode); return false;
                   if(phone == '' || phone == undefined || phone == null ){
                       CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Phone is required</div>",parentNode);
                       CALLCID_CW_clearmsg();
                       return false;
                   }
                   
                   //phone = cleanInput(parentNode.querySelector("#text_phone"));
                   //alert(phone); return false;
                   if(country_id == '' || country_id == undefined || country_id == null ){
                       CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Country is required</div>",parentNode);
                       CALLCID_CW_clearmsg();
                       return false;
                   }
    
    
                   if(text_messge == '' || text_messge == undefined || text_messge == null ){
                       CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Text Message is required</div>",parentNode);
                       //document.getElementsByClassName("alert_message").html("<div class='alert alert-danger'> Country is required</div>");
                       CALLCID_CW_clearmsg();
                       return false;
                   }
                   if(CALLCID_CW_widgetJson.enable_disclaimer_text == '1'){
                       // IF DISCLAIMER IS ENABLED
                       if(CALLCID_CW_widgetJson.text_accept_disclaimer_required == true){
                           var enable_disclaimer_text = parentNode.querySelector("#enable_disclaimer_text").checked;
                           ////////////console.log("CALLCID_CW_widgetJson.text_accept_disclaimer_required",CALLCID_CW_widgetJson.text_accept_disclaimer_required);
                           if(enable_disclaimer_text == false){
                               CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Please accept disclaimer by clicking checkbox.</div>",parentNode);
                               CALLCID_CW_clearmsg();
                               return false;
                           }
                       }
    
                   }
    
                   // //////////////////console.log("WORKING==");
                //return false;
    
                   CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Sending Text Message...</div>`,parentNode);
    
                   var saveObj = new FormData();
                   saveObj.append('name', name);
                   saveObj.append('phone', phone);
                   saveObj.append('country_id', country_id);
                   saveObj.append('text_messge', text_messge);
                   saveObj.append('wi', CALLCID_CW_widget_id);
    
                   var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
                   var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
                   if(CALLCID_CW_LocRes !== null){
                       var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
                       if(CALLCID_CW_LocResParsed){
                           // IF JSON IS VALID
                           CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
                           CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
                           CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
                           CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
                       }
                   }
                   saveObj.append('ip_address', CALLCID_CW_ip_address);
                   saveObj.append('city', CALLCID_CW_city);
                   saveObj.append('region', CALLCID_CW_region);
                   saveObj.append('country_name', CALLCID_CW_country_name);
                   saveObj.append('token', CALLCID_CW_TOKEN_GENERATE);
    
    
    
                   //var old_button_text = $("#sbmt-txt-rq").text();
                   var old_button_text = parentNode.querySelector("#sbmt-txt-rq").innerText;
                    parentNode.querySelector("#sbmt-txt-rq").setAttribute('disabled','disabled');
                    parentNode.querySelector("#sbmt-txt-rq").innerText = 'Sending Text Message...';
                   //////////////////console.log(CALLCID_CW_base_url);
    
                   CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-t", saveObj)
                         .then(result => {
                             parentNode.querySelector("#sbmt-txt-rq").removeAttribute('disabled');
                               parentNode.querySelector("#sbmt-txt-rq").innerText = old_button_text;
                               if(result.status == 1){
                                   CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                                   CALLCID_CW_clearmsg();
                                   CALLCID_CW_resetForm(parentNode);
                               } else {
                                   CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
                                   CALLCID_CW_clearmsg();
                               }
                         });
                });
               // SUBMIT TEXT REQUEST
          }


        }
            // Processing Text REQUEST

             /*SUBMIT EMAIL REQUEST*/
        function intializeEmailSubmission(parentNode) {
            ////console.log(`parentNode.querySelector("#sbmt-em-rq")`,parentNode.querySelector("#sbmt-em-rq"));
            if(parentNode.querySelector("#sbmt-em-rq")){
                parentNode.querySelector("#sbmt-em-rq").addEventListener("click",function(){

                    
                    const isAiChatOpen =  validatePopupEnterButton();
                      //  console.log("Chat Methode",isAiChatOpen);
                        if(isAiChatOpen === true) {
                            sendUserQuestion('vaicOpt')
                            return;
                        }

                    cleanInput(parentNode.querySelector('#'+CW_W_prefix+"email_phone"));                                                                
                    var name = parentNode.querySelector('#'+CW_W_prefix+"email_name").value;
                    var email = parentNode.querySelector('#'+CW_W_prefix+"email_email").value;
                    var subject = parentNode.querySelector('#'+CW_W_prefix+"email_subject").value;
                    var phone = parentNode.querySelector('#'+CW_W_prefix+"email_phone").value;
                    var attachment = parentNode.querySelector('#'+CW_W_prefix+"email_attachment");
                    
                    var country_id = parentNode.querySelector("#CW_EMAIL_country_id").value;
                    var text_messge = parentNode.querySelector('#'+CW_W_prefix+"email_messge").value;
                    if(name == '' || name == undefined || name == null ){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Name is required</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    }
 
                    //validateEmail(email)
 
                    //////////console.log("CALLCID_CW_widgetJson.email_form_require_phone",CALLCID_CW_widgetJson.email_form_require_phone);
                    //////////console.log("CALLCID_CW_widgetJson.email_widget_type",CALLCID_CW_widgetJson.email_widget_type);
                    //////////console.log("phone",phone);
                    if(CALLCID_CW_widgetJson.email_widget_type == '1'){
                        
                    }
                    if((phone == '' || phone == undefined || phone == null) ){
                        ////////////console.log("==== phone ====",phone);
                        
                        var is_phone_required = false;
                        if(CALLCID_CW_widgetJson.email_widget_type == '1' && CALLCID_CW_widgetJson.email_form_require_phone == '1'){
                            is_phone_required = true;
                        } else if(CALLCID_CW_widgetJson.email_widget_type == '0'){ 
                            is_phone_required = true;
                        }
 
                        if(is_phone_required){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Phone is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
                        
                    }
 
                    if(email == '' || email == undefined || email == null){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Email is required</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    } else if(!validateEmail(email)){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Enter valid email.</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    }

                    if(subject == '' || subject == undefined || subject == null ){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Subject is required</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    }
 
                    if(country_id == '' || country_id == undefined || country_id == null ){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Country is required</div>",parentNode);
                        CALLCID_CW_clearmsg();
                        return false;
                    }
 
 
                    if(text_messge == '' || text_messge == undefined || text_messge == null ){
                        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Text Message is required</div>",parentNode);
                        //document.getElementsByClassName("alert_message").html("<div class='alert alert-danger'> Country is required</div>");
                        CALLCID_CW_clearmsg();
                        return false;
                    }
                    if(CALLCID_CW_widgetJson.enable_disclaimer_email == '1'){
                        // IF DISCLAIMER IS ENABLED
                        if(CALLCID_CW_widgetJson.email_accept_disclaimer_required == true){
                            var enable_disclaimer_email = parentNode.querySelector("#enable_disclaimer_email").checked;
                            ////////////console.log("CALLCID_CW_widgetJson.text_accept_disclaimer_required",CALLCID_CW_widgetJson.email_accept_disclaimer_required);
                            if(enable_disclaimer_email == false){
                                CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'>Please accept disclaimer by clicking checkbox.</div>",parentNode);
                                CALLCID_CW_clearmsg();
                                return false;
                            }
                        }
 
                    }
 
                    // //////////////////console.log("WORKING==");
                 //return false;
 
                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Please wait, sending Email...</div>`,parentNode);
 
                    var saveObj = new FormData();
                    saveObj.append('name', name);
                    saveObj.append('email', email);
                    saveObj.append('subject', subject);
                    saveObj.append('phone', phone);
                    saveObj.append('country_id', country_id);
                    saveObj.append('text_messge', text_messge);

                    // if attachment is coming with email
                    if(attachment && attachment.value != '' && attachment.files.length > 0){
                        saveObj.append('attachment', attachment.files[0]);
                    }

                    saveObj.append('wi', CALLCID_CW_widget_id);
                    var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
                    var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
                    if(CALLCID_CW_LocRes !== null){
                        var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
                        if(CALLCID_CW_LocResParsed){
                            // IF JSON IS VALID
                            CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
                            CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
                            CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
                            CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
                        }
                    }
                    saveObj.append('ip_address', CALLCID_CW_ip_address);
                    saveObj.append('city', CALLCID_CW_city);
                    saveObj.append('region', CALLCID_CW_region);
                    saveObj.append('country_name', CALLCID_CW_country_name);
                    saveObj.append('token', CALLCID_CW_TOKEN_GENERATE);
                     var old_button_text = parentNode.querySelector("#sbmt-em-rq").innerText;
                     //parentNode.querySelector("#sbmt-em-rq").setAttribute('disabled','disabled');
                      parentNode.querySelector("#sbmt-em-rq").innerText = 'Sending mail...';
                    //////////////////console.log(CALLCID_CW_base_url);
 
                    CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-e", saveObj)
                          .then(result => {
                              parentNode.querySelector("#sbmt-em-rq").removeAttribute('disabled');
                                parentNode.querySelector("#sbmt-em-rq").innerText = old_button_text;
                                if(result.status == 1){
                                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                                    CALLCID_CW_clearmsg();
                                    CALLCID_CW_resetForm(parentNode);
                                } else {
                                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
                                    CALLCID_CW_clearmsg();
                                }
                          });
                 });
            }
        }

            /*SUBMIT AI CHAT REQUEST*/
            function intializeChatSubmission(parentNode) {


                if(parentNode.querySelector("#sbmt-chat-rq") !== null){
                    /*SUBMIT TEXT REQUEST*/
                    parentNode.querySelector("#sbmt-chat-rq").addEventListener("click",function(){
                        // CLEANING PHONE NUMBER

                        const isAiChatOpen =  validatePopupEnterButton();
                      //  console.log("Chat Methode",isAiChatOpen);
                        if(isAiChatOpen === true) {
                            sendUserQuestion('vaicOpt')
                            return;
                        }
                        

                        cleanInput(parentNode.querySelector("#chat_phone"));
                        var name = parentNode.querySelector("#chat_name").value;
                        var phone = parentNode.querySelector("#chat_phone").value;
                        var email = parentNode.querySelector("#chat_email").value;
                        var country_id = parentNode.querySelector("#CW_chat_country_id").value;
                        //console.log("name",name,"phone",phone)

                        var settingsObject = {
                        "ai-name-required": 1,
                        "ai-email-required": 1,
                        "ai-phone-required": 1
                        };

                       
                        if(CALLCID_AI_CHAT_FIELDS_SETTINGS != 'TRUE') {
                        
                          var settingsObject =  JSON.parse(CALLCID_AI_CHAT_FIELDS_SETTINGS);    
                          var { "ai-name-required": aiChatNameRequired,"ai-email-required": aiChatEmailRequired,  "ai-phone-required": aiChatPhoneRequired } = settingsObject; 

                        }else{

                            var { "ai-name-required": aiChatNameRequired,"ai-email-required": aiChatEmailRequired,  "ai-phone-required": aiChatPhoneRequired } = settingsObject; 
                        }

                       // console.log(settingsObject);
                        //console.log(CALLCID_AI_CHAT_FIELDS_SETTINGS,aiChatEmailRequired,aiChatPhoneRequired,aiChatNameRequired);
                      
                        if(aiChatNameRequired == 1 && (name == '' || name == undefined || name == null) ){
                           CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Name is required</div>",parentNode);
                           CALLCID_CW_clearmsg();
                           return false;
                        }
                        if( aiChatEmailRequired == 1 && (email == '' || email == undefined || email == null)){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Email is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        } else if(!validateEmail(email) &&  aiChatEmailRequired == 1){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Enter valid email.</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
                        //CALLCID_CW_resetForm(parentNode); return false;
                        if(aiChatPhoneRequired == 1 && phone == '' || phone == undefined || phone == null ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Phone  number is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }

                        if(aiChatPhoneRequired == 0){
                            country_id ='+1';

                            if(phone ==""){
                                phone ="11111111111"; 
                            }
                               
                        }

                        if(aiChatEmailRequired == 0 && email == ""){
                            email ="default-ai@connectboss.com";
                        }

                        if(aiChatNameRequired == 0 &&  name == ''){
                            name ='Default-ai-name-assistan';
                        }

                        if(country_id == '' || country_id == undefined || country_id == null ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Country is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
        
        
                      
        
                        CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Starting AI Chat...</div>`,parentNode);
            
                        var saveObj = new FormData();
                        saveObj.append('name', name);
                        saveObj.append('phone', phone);
                        saveObj.append('email', email);
                        saveObj.append('country_id', country_id);
                        saveObj.append('wi', CALLCID_CW_widget_id);
                        var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
                        var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
                        if(CALLCID_CW_LocRes !== null){
                            var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
                            if(CALLCID_CW_LocResParsed){
                                // IF JSON IS VALID
                                CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
                                CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
                                CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
                                CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
                            }
                        }
                        saveObj.append('ip_address', CALLCID_CW_ip_address);
                        saveObj.append('city', CALLCID_CW_city);
                        saveObj.append('region', CALLCID_CW_region);
                        saveObj.append('country_name', CALLCID_CW_country_name);
                        saveObj.append('token', CALLCID_CW_TOKEN_GENERATE);

                        var old_button_text = parentNode.querySelector("#sbmt-chat-rq").innerText;
                        parentNode.querySelector("#sbmt-chat-rq").setAttribute('disabled','disabled');
                        parentNode.querySelector("#sbmt-chat-rq").innerText = 'Starting...';
        
                        CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-ac", saveObj)
                        .then(result => {
                            parentNode.querySelector("#sbmt-chat-rq").removeAttribute('disabled');
                            parentNode.querySelector("#sbmt-chat-rq").innerText = old_button_text;
                            if(result.status == 1){
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                                CALLCID_CW_clearmsg();
                                CALLCID_CW_resetForm(parentNode);
                                var currentNodeParent =  this.closest(`.wrapper_${CALLCID_CW_UI}`);
                                parentNode.querySelector("#vaicOpt .chat_actionButton").classList.add('aiChatScreen');                                
                                parentNode.querySelector("#aiChatFormWrapper").style.display = "none";
                                parentNode.querySelector("#sbmt-chat-rq").style.display = "none";
                                parentNode.querySelector("#sbmt-ques-rq").style.display = "block";                                
                                parentNode.querySelector("#aiChatWrapper").style.display = "block"; 
                                parentNode.querySelector("#ques-btn").style.display = "block";
                                parentNode.querySelector("#user_thread_id").value = result.call_widget_id;  
                                
                                parentNode.querySelector("#aiChatWrapper .chat-area-box").innerHTML = "";
                                
                                var responseLoader = createLoadingEle();
                                var chatAreaBox = parentNode.querySelector("#aiChatWrapper .chat-area-box");
                                var tempDiv = document.createElement('div');
                                tempDiv.innerHTML = responseLoader;

                                // Append the first child of the temporary div to the chat area
                                chatAreaBox.appendChild(tempDiv.firstChild);

                                //disable the ai chat form submit button
                                var buttonToDisable = document.querySelector("#aiChatWrapper #sbmt-chat-rq");
                                if (buttonToDisable) {
                                    buttonToDisable.disabled = true;
                                }

                                CALLCID_CW_Ai_Chat_Widget_Cls_Msg = result.closing;
                                CALLCID_CW_Ai_Chat_Widget_Thx_Msg = result.thankyou_msg;
                                
                                setTimeout(function(){
                                    parentNode.querySelector("#aiChatWrapper .chat-area-box .received-message.loading-animation").remove();
                                    var userRecMsg = "Hi! I'm an AI chatbot. How can I help you?";
                                    if(result.opening != "" && result.opening != null){
                                        userRecMsg = result.opening;
                                    }
                                    var userRecCon = createMsgEle('received-message',userRecMsg);
                                    chatAreaBox.appendChild(userRecCon);
                                },3000);
                                

                            } else {
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
                                CALLCID_CW_clearmsg();
                            }
                        });
                    });
                }
            }
            /*SUBMIT AI CHAT REQUEST*/

            /*SUBMIT VIDEO REQUEST*/
            function intializeVideoSubmission(parentNode) {
                if(parentNode.querySelector("#sbmt-video-rq") !== null){
                    /*SUBMIT VIDEO REQUEST*/
                    //console.log("clicked");
                    parentNode.querySelector("#sbmt-video-rq").addEventListener("click",function(){
                        // CLEANING PHONE NUMBER
                        cleanInput(parentNode.querySelector("#video_phone"));
                        var name = parentNode.querySelector("#video_name").value;
                        var phone = parentNode.querySelector("#video_phone").value;
                        var email = parentNode.querySelector("#video_email").value;
                        var topic = parentNode.querySelector("#video_topic").value;
                        var country_id = parentNode.querySelector("#CW_video_country_id").value;

                        
                        //console.log("name",name,"phone",phone)
                        if(name == '' || name == undefined || name == null ){
                           CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Name is required</div>",parentNode);
                           CALLCID_CW_clearmsg();
                           return false;
                        }
                        if(email == '' || email == undefined || email == null){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Email is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        } else if(!validateEmail(email)){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Enter valid email.</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
                        //CALLCID_CW_resetForm(parentNode); return false;
                        if(phone == '' || phone == undefined || phone == null ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Phone is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
                        if(country_id == '' || country_id == undefined || country_id == null ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Country is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }
                        if(topic == '' || topic == undefined || topic == null ){
                           CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Topic is required</div>",parentNode);
                           CALLCID_CW_clearmsg();
                           return false;
                        }
        
                        CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Sending Video Meeting Request...</div>`,parentNode);
            
                        var saveObj = new FormData();
                        saveObj.append('name', name);
                        saveObj.append('phone', phone);
                        saveObj.append('email', email);
                        saveObj.append('topic', topic);
                        saveObj.append('country_id', country_id);

                        saveObj.append('wi', CALLCID_CW_widget_id);
                        var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
                        var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
                        if(CALLCID_CW_LocRes !== null){
                            var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
                            if(CALLCID_CW_LocResParsed){
                                // IF JSON IS VALID
                                CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
                                CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
                                CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
                                CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
                            }
                        }
                        saveObj.append('ip_address', CALLCID_CW_ip_address);
                        saveObj.append('city', CALLCID_CW_city);
                        saveObj.append('region', CALLCID_CW_region);
                        saveObj.append('country_name', CALLCID_CW_country_name);
                        saveObj.append('token', CALLCID_CW_TOKEN_GENERATE);

                        var old_button_text = parentNode.querySelector("#sbmt-video-rq").innerText;
                        parentNode.querySelector("#sbmt-video-rq").setAttribute('disabled','disabled');
                        parentNode.querySelector("#sbmt-video-rq").innerText = 'Sending...';
        
                        CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-v-c", saveObj)
                        .then(result => {
                            parentNode.querySelector("#sbmt-video-rq").removeAttribute('disabled');
                            parentNode.querySelector("#sbmt-video-rq").innerText = old_button_text;
                            if(result.status == 1){
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                                CALLCID_CW_resetForm(parentNode);

                                parentNode.querySelector("#video_meeting_form").style.display = "none";
                                parentNode.querySelector("#sbmt-video-rq").style.display = "none";
                                parentNode.querySelector("#video_meeting_loader").style.display = "block"; 
                                
                                
                                widgetVMHostRes = setInterval(function(){
                                    checkHostRespond(result.request_id,parentNode);
                                },5000);
                                
                                widgetVMHostResClear = setTimeout(function() {
                                    clearInterval(widgetVMHostRes);

                                    parentNode.querySelector("#video_meeting_form").style.display = "block";
                                    parentNode.querySelector("#sbmt-video-rq").style.display = "block";
                                    parentNode.querySelector("#video_meeting_loader").style.display = "none"; 

                                    var items = document.getElementsByClassName('alert_message');
                                    for (var i=0; i < items.length; i++) {
                                        items[i].innerHTML = '';
                                    }

                                    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Host did not respond to your request. Please reach out again after some time.</div>`,parentNode);
                                    setTimeout(function(){
                                        CALLCID_CW_clearmsg();
                                    },3000);

                                    CW_updateVideoReqStatus(result.request_id,parentNode);

                                },300000);

                            } else {
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
                                CALLCID_CW_clearmsg();
                            }
                        });
                    });
                }
            }
            /*SUBMIT VIDEO REQUEST*/

            /*SUBMIT WHATSAPP REQUEST*/
            function intializeWASubmission(parentNode) {

                if(parentNode.querySelector("#sbmt-whatsapp-rq") !== null){
                    /*SUBMIT WHATSAPP REQUEST*/
                    parentNode.querySelector("#sbmt-whatsapp-rq").addEventListener("click",function(){

                        var name = parentNode.querySelector("#whatsapp_name")?.value || null;
                        var email = parentNode.querySelector("#whatsapp_email")?.value || null;
                        var phone = parentNode.querySelector("#whatsapp_phone")?.value || null;
                        var country_id = parentNode.querySelector("#CW_whatsapp_country_id")?.value || null;

                        console.log("name",name,"phone",phone,"email",email,"country_id",country_id)

                        var settingsObject =  JSON.parse(CALLCID_WHATSAPP_FIELDS_SETTINGS);    
                        var { "whatsapp-name-required": whatsAppNameRequired,"whatsapp-email-required": whatsAppEmailRequired,  "whatsapp-phone-required": whatsAppPhoneRequired, "whatsapp-name-show": whatsAppNameShow,"whatsapp-email-show": whatsAppEmailShow,  "whatsapp-phone-show": whatsAppPhoneShow } = settingsObject; 

                        if(whatsAppNameShow == 1 && whatsAppNameRequired == 1 && (name == '' || name == undefined || name == null) ){
                           CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Name is required</div>",parentNode);
                           CALLCID_CW_clearmsg();
                           return false;
                        }

                        if(whatsAppEmailShow == 1 && whatsAppEmailRequired == 1 && (email == '' || email == undefined || email == null)){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Email is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        } else if(!validateEmail(email) && whatsAppEmailRequired == 1 && whatsAppEmailShow == 1 ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Enter valid email.</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }

                        if(whatsAppPhoneShow == 1 && whatsAppPhoneRequired == 1 && (phone == '' || phone == undefined || phone == null) ){
                           CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Phone Number is required</div>",parentNode);
                           CALLCID_CW_clearmsg();
                           return false;
                        }

                        if(whatsAppPhoneShow == 1 && whatsAppPhoneRequired == 1 && ( country_id == '' || country_id == undefined || country_id == null) ){
                            CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Country is required</div>",parentNode);
                            CALLCID_CW_clearmsg();
                            return false;
                        }

                        var saveObj = new FormData();
                        saveObj.append('name', name);
                        saveObj.append('phone', phone);
                        saveObj.append('email', email);
                        saveObj.append('country_id', country_id);
                        saveObj.append('wi', CALLCID_CW_widget_id);
                        var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
                        var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
                        if(CALLCID_CW_LocRes !== null){
                            var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
                            if(CALLCID_CW_LocResParsed){
                                // IF JSON IS VALID
                                CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
                                CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
                                CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
                                CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
                            }
                        }
                        saveObj.append('ip_address', CALLCID_CW_ip_address);
                        saveObj.append('city', CALLCID_CW_city);
                        saveObj.append('region', CALLCID_CW_region);
                        saveObj.append('country_name', CALLCID_CW_country_name);

                        var old_button_text = parentNode.querySelector("#sbmt-whatsapp-rq").innerText;
                        parentNode.querySelector("#sbmt-whatsapp-rq").setAttribute('disabled','disabled');
                        parentNode.querySelector("#sbmt-whatsapp-rq").innerText = 'Opening WhatsApp...';

                        CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-w-a", saveObj)
                        .then(result => {
                            parentNode.querySelector("#sbmt-whatsapp-rq").removeAttribute('disabled');
                            parentNode.querySelector("#sbmt-whatsapp-rq").innerText = old_button_text;
                            if(result.status == 1){
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentNode);
                                CALLCID_CW_clearmsg();
                                CALLCID_CW_resetForm(parentNode);
                                openWhatsAppLink();
                            } else {
                                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
                                CALLCID_CW_clearmsg();
                            }
                        });

                    });
                }
            }
            /*SUBMIT WHATSAPP REQUEST*/
           
           /*
           HIDING BLUR BOX
           */
          document.onclick = function(e){
           var WIDGET_divToHide = document.getElementById("widget_wrapper");
           //////////console.log("e.target.id",e.target.id);
               if(e.target.id == 'widget-Overlay_'){
               //element clicked wasn't the div; hide the div
               //WIDGET_divToHide.style.display = 'none';
               var CALLCID_CW_loadedWidgets =  document.getElementsByClassName(`wrapper_${CALLCID_CW_UI}`);
               for(var i = 0; i < CALLCID_CW_loadedWidgets.length; i++){
                    var currentNode = CALLCID_CW_loadedWidgets[i];
                    var currentNodeParent = currentNode.closest(`.cwTargetScript-${CALLCID_CW_UI}`);
                    if(currentNodeParent == null || currentNodeParent.length ==0){
                        CALLCID_CW_closeForm(currentNode.querySelector(`#close-${CALLCID_CW_UI}`));
                    }
                   
                }
               
               }
           };

          }
          
          hideWidgetForaMonth();
       }; // check every 100ms


    /* 
    * RESOLVED
    */
    
    function CALLCID_CW_openForm(element) {
        /* 
        IN CASE OF EXTERNAL BUTTON `element` WILL BE NULL OR UNDEFINED
        TO HANDLE THIS WE WILL FIND VISIBLE "#open-button" AND SET THIS INTO `element`
        */
        if(element == null ||  element == undefined ){
            var allOpenBtns = document.querySelectorAll("#open-button");
            for(var btnIndex = 0; btnIndex < allOpenBtns.length; btnIndex++){
                if(allOpenBtns[btnIndex].offsetParent !== null){
                    element = allOpenBtns[btnIndex];
                    break;
                }
            }
        }
        var parentNode = element.closest(`.wrapper_${CALLCID_CW_UI}`);
        parentNode.querySelector('#WidgetmyForm').style.display = "block";
        parentNode.querySelector("#widget-Overlay_").style.display = "block";;
        parentNode.querySelector("#open-button").style.display = "none";
        parentNode.querySelector("#widget-Overlay_").style.display = "block";
        var CW_imgHolderDiv = parentNode.getElementsByClassName("img-holder"); //divsToHide is an array
        for(var i = 0; i < CW_imgHolderDiv.length; i++){
            CW_imgHolderDiv[i].style.display = "none"; // depending on what you're doing
        }
        var cw_cid_arrow_div = parentNode.getElementsByClassName("cw_cid_arrow_div"); //divsToHide is an array
        for(var i = 0; i < cw_cid_arrow_div.length; i++){
            cw_cid_arrow_div[i].style.display = "none"; // depending on what you're doing
        }
        
        var videoBox = null;
        if (element) {
            var ancestorVideoBox = element.closest('.CW_CALLWIDGET_video');
            if (ancestorVideoBox) {
                videoBox = ancestorVideoBox.querySelector('.widgetVideo');
            }
        }

        if (videoBox) {
            initializeVideoPlayer(videoBox)
            var parentVideoBox = videoBox.closest('.video_box.CW_CALLWIDGET_video');
            if (parentVideoBox) {
                parentVideoBox.style.display = "none";
            }
        }

    }
    function CALLCID_CW_closeForm(element) {
     var parentNode = element.closest(`.wrapper_${CALLCID_CW_UI}`);
     parentNode.querySelector("#WidgetmyForm").style.display = "none";
     parentNode.querySelector("#open-button").style.display = "block";
     parentNode.querySelector("#widget-Overlay_").style.display = "none";
      var CW_imgHolderDiv = parentNode.getElementsByClassName("img-holder"); //divsToHide is an array
        for(var i = 0; i < CW_imgHolderDiv.length; i++){
            //CW_imgHolderDiv[i].style.visibility = "hidden"; // or
            CW_imgHolderDiv[i].style.display = "block"; // depending on what you're doing
        }
        var cw_cid_arrow_div = parentNode.getElementsByClassName("cw_cid_arrow_div"); //divsToHide is an array
        for(var i = 0; i < cw_cid_arrow_div.length; i++){
            //CW_imgHolderDiv[i].style.visibility = "hidden"; // or
            cw_cid_arrow_div[i].style.display = "block"; // depending on what you're doing
        }

        var videoBox = null;
        if (element && element.closest('.chat-popup')) {
            var chatPopupAncestor = element.closest('.chat-popup');
            var previousSibling = chatPopupAncestor.previousElementSibling;
            if (previousSibling && previousSibling.classList.contains('btn-animation-wrap')) {
                videoBox = previousSibling.querySelector('.widgetVideo');
            }
        }
        if (videoBox) {
            if (videoBox.classList.contains('btn_video') && videoBox.classList.contains('active')) {
                videoBox.muted = false;
            }
            var parentVideoBox = videoBox.closest('.video_box.CW_CALLWIDGET_video');
            if (parentVideoBox) {
                parentVideoBox.style.display = "block";
            }
            if(videoBox.classList.contains('closed')){
                parentNode.querySelector("#open-button").style.display = "none";
            }
        }
    }

    function CALLCID_CW_go_back(element){
    var parentNode = element.closest(`.wrapper_${CALLCID_CW_UI}`);
	(parentNode.querySelector("#vpOpt") !== null) ? parentNode.querySelector("#vpOpt").style.display = "none" : '';
	(parentNode.querySelector("#vtOpt")) ? parentNode.querySelector("#vtOpt").style.display = "none" : '';
	(parentNode.querySelector("#veOpt")) ? parentNode.querySelector("#veOpt").style.display = "none" : '';
    (parentNode.querySelector("#vaicOpt")) ? parentNode.querySelector("#vaicOpt").style.display = "none" : '';
	(parentNode.querySelector("#vvmOpt")) ? parentNode.querySelector("#vvmOpt").style.display = "none" : '';
	(parentNode.querySelector("#vvideoOpt")) ? parentNode.querySelector("#vvideoOpt").style.display = "none" : '';
	(parentNode.querySelector("#vwaOpt")) ? parentNode.querySelector("#vwaOpt").style.display = "none" : '';
	parentNode.querySelector("#main_opt").style.display = "block";

        if(element.closest("#vvmOpt")){
            CW_justStopRecord(element);
        }

	}

    function CALLCID_CW_submitReq(){
		alert("Ready to fly");
	}
    function CALLCID_CW_clearmsg(){
		setTimeout(function(){
            var items = document.getElementsByClassName('alert_message');
              for (var i=0; i < items.length; i++) {
                items[i].innerHTML = '';
              }
	 	},3000);
	}

	function CALLCID_CW_resetForm(parentNode){ 
        //console.log("parentNode =>",parentNode,`parentNode.querySelector("call_name")`,parentNode.querySelector("#call_name"));
        (parentNode.querySelector("#call_name")) ? parentNode.querySelector("#call_name").value = '' : '';
        (parentNode.querySelector("#call_phone")) ? parentNode.querySelector("#call_phone").value = '' : '';
        
        (parentNode.querySelector("#voice_sender_name")) ? parentNode.querySelector("#voice_sender_name").value = '' : '';
        (parentNode.querySelector("#voice_sender_email")) ? parentNode.querySelector("#voice_sender_email").value = '' : '';
        (parentNode.querySelector("#voice_phone")) ? parentNode.querySelector("#voice_phone").value = '' : '';
        if(parentNode.querySelector("#enable_disclaimer_phone") !== null && parentNode.querySelector("#enable_disclaimer_phone") !== undefined ){
            parentNode.querySelector("#enable_disclaimer_phone").removeAttribute("checked");
        }

        if(parentNode.querySelector("#enable_disclaimer_text") !== null && parentNode.querySelector("#enable_disclaimer_text") !== undefined ){
            parentNode.querySelector("#enable_disclaimer_text").removeAttribute("checked");
        }

        if(parentNode.querySelector("#enable_disclaimer_email") !== null && parentNode.querySelector("#enable_disclaimer_email") !== undefined ){
            parentNode.querySelector("#enable_disclaimer_email").removeAttribute("checked");
        }
		is_scheduled_call = 0;
        //(document.getElementsByClassName("call_schedule_wrapper")) ? (document.getElementsByClassName("call_schedule_wrapper")[0].style.display ='none')  : '' ;

       (parentNode.querySelector("#text_name")) ? ( parentNode.querySelector("#text_name").value = '') : '';
       (parentNode.querySelector("#call_schedule_wrapper")) ? ( parentNode.querySelector("#call_schedule_wrapper").style.display ='none') : '';
        (parentNode.querySelector("#text_phone")) ? (parentNode.querySelector("#text_phone").value ='') : '';
        (parentNode.querySelector("#text_messge")) ? (parentNode.querySelector("#text_messge").value= '') : '';

        (parentNode.querySelector(`#`+CW_W_prefix+"email_name")) ? parentNode.querySelector(`#`+CW_W_prefix+"email_name").value ='': '';
        (parentNode.querySelector(`#`+CW_W_prefix+"email_email")) ? parentNode.querySelector(`#`+CW_W_prefix+"email_email").value= '' : '';
        (parentNode.querySelector(`#`+CW_W_prefix+"email_subject")) ? parentNode.querySelector(`#`+CW_W_prefix+"email_subject").value= '' : '';
        (parentNode.querySelector(`#`+CW_W_prefix+"email_phone")) ? parentNode.querySelector(`#`+CW_W_prefix+"email_phone").value = '' : '';
        (parentNode.querySelector(`#`+CW_W_prefix+"email_messge")) ? parentNode.querySelector(`#`+CW_W_prefix+"email_messge").value= '' : '';
        (parentNode.querySelector(`#`+CW_W_prefix+"email_attachment")) ? parentNode.querySelector(`#`+CW_W_prefix+"email_attachment").value= '' : '';
        
        (parentNode.querySelector("#video_name")) ? parentNode.querySelector("#video_name").value = '' : '';
        (parentNode.querySelector("#video_email")) ? parentNode.querySelector("#video_email").value = '' : '';
        (parentNode.querySelector("#video_phone")) ? parentNode.querySelector("#video_phone").value = '' : '';
        (parentNode.querySelector("#video_topic")) ? parentNode.querySelector("#video_topic").value = '' : '';

        (parentNode.querySelector("#whatsapp_name")) ? parentNode.querySelector("#whatsapp_name").value = '' : '';
        (parentNode.querySelector("#whatsapp_email")) ? parentNode.querySelector("#whatsapp_email").value = '' : '';
        (parentNode.querySelector("#whatsapp_phone")) ? parentNode.querySelector("#whatsapp_phone").value = '' : '';

        const cw_callsling_attachments = parentNode.querySelectorAll('.selected-files-email-attachment');
        

        if (cw_callsling_attachments.length > 0) {
            cw_callsling_attachments[0].innerHTML = "";
        }

        var w_ta = parentNode.getElementsByClassName("w-ta");
        for (var i = 0; i < w_ta.length; i++) {
            var item =  w_ta[i].closest(".field-wrapper");
            item.getElementsByClassName('w-counter')[0].innerHTML = 0;

        }
	}

    function cleanInput(elm){        
        var inputVal = elm.value;
        ////////console.log("inputVal",inputVal);
        inputVal = inputVal.replace(/[^0-9]/g, "");;
        elm.value = inputVal;
    }

    window.addEventListener('load', (event) => {        
        //document.getElementById("mDw").style.display = "block";
		setTimeout(function(){
             //document.getElementById("mDw").style.display = "block";
		},2000);
	});

/*VANILA TRANSFORMATION*/
async function CALLCID_CW_postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    // mode: 'cors', // no-cors, *cors, same-origin
    // cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    // credentials: 'same-origin', // include, *same-origin, omit
    // headers: {
    //   //'Content-Type': 'application/json'
    //   'Content-Type': 'application/x-www-form-urlencoded',
    // },
    // redirect: 'follow', // manual, *follow, error
    // referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: data // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}


async function CALLCID_CW_postDataHTM(url = '', data = {}) {
    // Default options are marked with *
    const response = await fetch(url, {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      // mode: 'cors', // no-cors, *cors, same-origin
      // cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      // credentials: 'same-origin', // include, *same-origin, omit
      // headers: {
      //   //'Content-Type': 'application/json'
      //   'Content-Type': 'application/x-www-form-urlencoded',
      // },
      // redirect: 'follow', // manual, *follow, error
      // referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
      body: data // body data type must match "Content-Type" header
    });
    return response.text(); // parses JSON response into native JavaScript objects
  }

function CALLCID_CW_setAlertMessage(className,message,parentNode){
    var items = parentNode.getElementsByClassName(className);
  for (var i=0; i < items.length; i++) {
    items[i].innerHTML = message;
  }
}

async function CALLCID_CW_getData(url){

    const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
// myHeaders.append('Content-Length', content.length.toString());
// myHeaders.append('X-Custom-Header', 'ProcessThisImmediately');
  const response = await fetch(url,{
    method:"GET",
    mode: 'no-cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: myHeaders
  });

  return response;
   // .then(response => response.json())
   // .then(data => //////////////console.log(data));

}

// COUNTRY CODE DROP DOWN CODE FOR TEXT
function CW_T_C_DD(__me){
    ////console.log("CW_T_C_DD");
    var currentNodeParent =  __me.closest(`.wrapper_${CALLCID_CW_UI}`);
    ////console.log("currentNodeParent => ",currentNodeParent);
    var CW_current_state = currentNodeParent.querySelector("#CW_T_COUNTRIES").style.display;
    ////console.log("CW_current_state => ",CW_current_state,`currentNodeParent.querySelector("#CW_T_COUNTRIES")`,currentNodeParent.querySelector("#CW_T_COUNTRIES"));
    if(CW_current_state == 'block'){
        currentNodeParent.querySelector("#CW_T_COUNTRIES").style.display ="none";
    } else {
        currentNodeParent.querySelector("#CW_T_COUNTRIES").style.display ="block";
    }

    //////////////console.log("CONNECTED");
}
// WHEN CLICKED ON LI OF COUNTRY CODE
function CW_T_C_DD_LI(country_code,iso_code,$this){
    var currentNodeParent =  $this.closest(`.wrapper_${CALLCID_CW_UI}`);
    ////////////console.log("country_code",country_code);
    currentNodeParent.querySelector('#CW_text_country_id').value = country_code;
    currentNodeParent.querySelector("#CW_T_C_DD_SEL").innerHTML = currentNodeParent.querySelector(`#CW_T_C_DD_LI_${iso_code}`).innerHTML;
}

// COUNTRY CODE DROP DOWN CODE FOR VOICE MESSAGE
function CW_VM_C_DD(__me){

    var currentNodeParent =  __me.closest(`.wrapper_${CALLCID_CW_UI}`);
    var CW_current_state = currentNodeParent.querySelector("#CW_VM_COUNTRIES").style.display;
   
    if(CW_current_state == 'block'){
        currentNodeParent.querySelector("#CW_VM_COUNTRIES").style.display ="none";
    } else {
        currentNodeParent.querySelector("#CW_VM_COUNTRIES").style.display ="block";
    }
}
// WHEN CLICKED ON LI OF COUNTRY CODE
function CW_VM_C_DD_LI(country_code,iso_code,$this){
    var currentNodeParent =  $this.closest(`.wrapper_${CALLCID_CW_UI}`);

    currentNodeParent.querySelector('#CW_voice_country_id').value = country_code;
    currentNodeParent.querySelector("#CW_VM_C_DD_SEL").innerHTML = currentNodeParent.querySelector(`#CW_VM_C_DD_LI_${iso_code}`).innerHTML;
}

// COUNTRY CODE DROP DOWN CODE FOR AI CHAT
function CW_AIC_C_DD(__me){
    var currentNodeParent =  __me.closest(`.wrapper_${CALLCID_CW_UI}`);
    var CW_current_state = currentNodeParent.querySelector("#CW_AIC_COUNTRIES").style.display;
    if(CW_current_state == 'block'){
        currentNodeParent.querySelector("#CW_AIC_COUNTRIES").style.display ="none";
    } else {
        currentNodeParent.querySelector("#CW_AIC_COUNTRIES").style.display ="block";
    }
}
// WHEN CLICKED ON LI OF COUNTRY CODE
function CW_AIC_C_DD_LI(country_code,iso_code,$this){
    var currentNodeParent =  $this.closest(`.wrapper_${CALLCID_CW_UI}`);
    currentNodeParent.querySelector('#CW_chat_country_id').value = country_code;
    currentNodeParent.querySelector("#CW_AIC_C_DD_SEL").innerHTML = currentNodeParent.querySelector(`#CW_AIC_C_DD_LI_${iso_code}`).innerHTML;
}

// COUNTRY CODE DROP DOWN CODE FOR VIDEO
function CW_VIDEO_C_DD(__me){
    var currentNodeParent =  __me.closest(`.wrapper_${CALLCID_CW_UI}`);
    var CW_current_state = currentNodeParent.querySelector("#CW_VIDEO_COUNTRIES").style.display;
    if(CW_current_state == 'block'){
        currentNodeParent.querySelector("#CW_VIDEO_COUNTRIES").style.display ="none";
    } else {
        currentNodeParent.querySelector("#CW_VIDEO_COUNTRIES").style.display ="block";
    }
}
// WHEN CLICKED ON LI OF COUNTRY CODE
function CW_VIDEO_C_DD_LI(country_code,iso_code,$this){
    var currentNodeParent =  $this.closest(`.wrapper_${CALLCID_CW_UI}`);
    currentNodeParent.querySelector('#CW_video_country_id').value = country_code;
    currentNodeParent.querySelector("#CW_VIDEO_C_DD_SEL").innerHTML = currentNodeParent.querySelector(`#CW_VIDEO_C_DD_LI_${iso_code}`).innerHTML;
}

// COUNTRY CODE DROP DOWN CODE FOR WHATSAPP
function CW_WHATSAPP_C_DD(__me){
    var currentNodeParent =  __me.closest(`.wrapper_${CALLCID_CW_UI}`);
    var CW_current_state = currentNodeParent.querySelector("#CW_WHATSAPP_COUNTRIES").style.display;
    if(CW_current_state == 'block'){
        currentNodeParent.querySelector("#CW_WHATSAPP_COUNTRIES").style.display ="none";
    } else {
        currentNodeParent.querySelector("#CW_WHATSAPP_COUNTRIES").style.display ="block";
    }
}
// WHEN CLICKED ON LI OF COUNTRY CODE
function CW_WHATSAPP_C_DD_LI(country_code,iso_code,$this){
    var currentNodeParent =  $this.closest(`.wrapper_${CALLCID_CW_UI}`);
    currentNodeParent.querySelector('#CW_whatsapp_country_id').value = country_code;
    currentNodeParent.querySelector("#CW_WHATSAPP_C_DD_SEL").innerHTML = currentNodeParent.querySelector(`#CW_WHATSAPP_C_DD_LI_${iso_code}`).innerHTML;
}

// COUNTRY CODE DROP DOWN CODE FOR TEXT
function CW_P_C_DD(__me){
    var currentNodeParent =  __me.closest(`.wrapper_${CALLCID_CW_UI}`);

    var CW_current_state = currentNodeParent.querySelector("#CW_P_COUNTRIES").style.display;
    ////////////console.log("CW_current_state",CW_current_state);
    if(CW_current_state == 'block'){
        currentNodeParent.querySelector("#CW_P_COUNTRIES").style.display ="none";
    } else {
        currentNodeParent.querySelector("#CW_P_COUNTRIES").style.display ="block";
    }

    //////////////console.log("CONNECTED");
}

// COUNTRY CODE DROP DOWN CODE FOR TEXT
function CW_E_C_DD(__me){
    var currentNodeParent =  __me.closest(`.wrapper_${CALLCID_CW_UI}`);

    var CW_current_state = currentNodeParent.querySelector("#CW_E_COUNTRIES").style.display;
    if(CW_current_state == 'block'){
        currentNodeParent.querySelector("#CW_E_COUNTRIES").style.display ="none";
    } else {
        currentNodeParent.querySelector("#CW_E_COUNTRIES").style.display ="block";
    }

    ////////////////console.log("CONNECTED");
}
// WHEN CLICKED ON LI OF COUNTRY CODE
function CW_E_C_DD_LI(country_code,iso_code,$this){
    //////////////console.log("country_code",country_code);
    var currentNodeParent =  $this.closest(`.wrapper_${CALLCID_CW_UI}`);
    currentNodeParent.querySelector('#CW_EMAIL_country_id').value = country_code;
    currentNodeParent.querySelector("#CW_E_C_DD_SEL").innerHTML = currentNodeParent.querySelector(`#CW_E_C_DD_LI_${iso_code}`).innerHTML;
}









// WHEN CLICKED ON LI OF COUNTRY CODE
function CW_P_C_DD_LI(country_code,iso_code,$this){
    ////////////console.log("country_code",country_code);
    var currentNodeParent =  $this.closest(`.wrapper_${CALLCID_CW_UI}`);
    currentNodeParent.querySelector('#cw-country_id').value = country_code;
    currentNodeParent.querySelector("#CW_P_C_DD_SEL").innerHTML = currentNodeParent.querySelector(`#CW_T_C_DD_LI_${iso_code}`).innerHTML;
}
var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var monArray=['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
var weekDayArray=['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
function CALLCID_CW_formatDate(convertedDate){
    var d = convertedDate.getDate();
    var m = strArray[convertedDate.getMonth()];
    var mm = monArray[convertedDate.getMonth()];
    var y = convertedDate.getFullYear();
    var wd = weekDayArray[convertedDate.getDay()];
    return `${y}-${mm}-${d}`;
}

function CALLCID_CW_getCallScheduleHtm(time_zone,CALLCID_CWwidgetTimezone,parentNode){
    //DYNAMIC SCHEDULE TIME DROPDOWN
    var saveObj = new FormData();
    saveObj.append('wi', CALLCID_CW_widget_id);
    saveObj.append('time_zone', time_zone);
    saveObj.append('CALLCID_CWwidgetTimezone', CALLCID_CWwidgetTimezone);
    CALLCID_CWwidgetTimezone
    CALLCID_CW_postDataHTM(CALLCID_CW_base_url+"/callwidget-save?f=c-s-htm", saveObj)
    .then(result => {
        //call_schedule_wrapper
        if(parentNode.querySelector('#call_schedule_wrapper')){
            ////console.log("parentNode.querySelector('#call_schedule_wrapper').length",parentNode.querySelector('#call_schedule_wrapper').length)
            parentNode.querySelector('#call_schedule_wrapper').innerHTML = result;
            setTimeout(function(){
                /* NEW CODE */
                var chooseEl = parentNode.getElementsByClassName("choose-time");
                //console.log("chooseEl",chooseEl);
                if(chooseEl !==  null && chooseEl !== undefined && chooseEl.length > 0){
                    ////console.log(chooseEl[0]);
                    for (var j = 0; j < chooseEl.length; j++) {
                            ////console.log("chooseEl[j] =>",chooseEl[j]);
                            chooseEl[j].addEventListener("click",function(event){
                                event.preventDefault();
                                var callEl = parentNode.getElementsByClassName("call_schedule_wrapper");
                                ////console.log("callEl => ",callEl[0].style.display);
                                if(callEl[0].style.display == 'block'){
                                    is_scheduled_call = 0
                                    callEl[0].style.display = "none";
                                } else {
                                    is_scheduled_call = 1;
                                    callEl[0].style.display = "block";
                                }
                                });
                    }
                }
                /* NEW CODE */
                //console.log(`parentNode.querySelector("#call_date").length`,parentNode.querySelector("#call_date").length)
                parentNode.querySelector("#call_date").addEventListener("change",function(event){
                        event.preventDefault();
                        var selected_date = this.value;
                        var ts = parentNode.querySelectorAll(".time-select");
                        for (var tIndex = 0; tIndex < ts.length; tIndex++) {
                            ts[tIndex].style.display="none";
                        }
                        parentNode.querySelector(`#call_time_${selected_date}`).style.display="block";
                });
            },500);
        }
    })
}

function CALLCID_CW_setLoc (result,parentNode){

    if(result.country_code !== undefined){
        var cw_callcid_countryFound = false;
        for (var i = 0; i < CALLCID_CW_enable_countries.length; i++) {
            if (CALLCID_CW_enable_countries[i].iso_code === result.country_code) {
                cw_callcid_countryFound = true;
                break;
            }
        }
        if(cw_callcid_countryFound){
            clientcountry = result.country_code;            
        }else{
            clientcountry = 'US';
        }
    } else {
       clientcountry = 'US';
    }

    var time_zone = 'America/New_York';
   if(result.time_zone !== undefined){
       //localStorage.setItem(`cw-${CALLCID_CW_widget_id}-tz`, result.time_zone.name);
       time_zone = result.time_zone.name;
   }
   localStorage.setItem(`cw-${CALLCID_CW_widget_id}-tz`, time_zone);
   localStorage.setItem(`cw-client-loc`, clientcountry);
   var CallScheduleHtm = CALLCID_CW_getCallScheduleHtm(time_zone,CALLCID_CWwidgetTimezone,parentNode);
   //
   localStorage.setItem(`cw-${CALLCID_CW_widget_id}-loc`, clientcountry);
   CALLCID_CW_countries.filter(function(c){
           if(c.code == clientcountry){
               var iso_code =  c.code.toLowerCase()
               if(CALLCID_CW_widgetJson.is_text_enabled && parentNode.querySelector("#CW_T_C_DD_SEL") !== null){
                   //////////////console.log("CALLCID_CW_widgetJson.is_text_enabled",CALLCID_CW_widgetJson.is_text_enabled);
                   parentNode.querySelector("#CW_T_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_T_C_DD_LI_${iso_code}`).innerHTML;
                   parentNode.querySelector('#CW_text_country_id').value = c.dial_code;
               }

               if(CALLCID_CW_widgetJson.is_voice_message_enabled && parentNode.querySelector("#CW_VM_C_DD_SEL") !== null){
                   //////////////console.log("CALLCID_CW_widgetJson.is_voice_message_enabled",CALLCID_CW_widgetJson.is_voice_message_enabled);
                   parentNode.querySelector("#CW_VM_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_VM_C_DD_LI_${iso_code}`).innerHTML;
                   parentNode.querySelector('#CW_voice_country_id').value = c.dial_code;
               }
               
               if(parentNode.querySelector("#CW_P_C_DD_SEL") && CALLCID_CW_widgetJson.is_phone_enabled){
                   parentNode.querySelector("#CW_P_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_P_C_DD_LI_${iso_code}`).innerHTML;
                   parentNode.querySelector("#cw-country_id").value = c.dial_code;
               }

               if(parentNode.querySelector("#CW_E_C_DD_SEL") && CALLCID_CW_widgetJson.is_email_enabled){
                   parentNode.querySelector("#CW_E_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_E_C_DD_LI_${iso_code}`).innerHTML;
                   parentNode.querySelector("#CW_EMAIL_country_id").value = c.dial_code;
               }
               if(parentNode.querySelector("#CW_AIC_C_DD_SEL") && CALLCID_CW_widgetJson.is_chat_enabled){
                   parentNode.querySelector("#CW_AIC_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_AIC_C_DD_LI_${iso_code}`).innerHTML;
                   parentNode.querySelector("#CW_chat_country_id").value = c.dial_code;
               }
               if(parentNode.querySelector("#CW_VIDEO_C_DD_SEL") && CALLCID_CW_widgetJson.is_video_enabled){
                   parentNode.querySelector("#CW_VIDEO_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_VIDEO_C_DD_LI_${iso_code}`).innerHTML;
                   parentNode.querySelector("#CW_video_country_id").value = c.dial_code;
               }
               if(parentNode.querySelector("#CW_WHATSAPP_C_DD_SEL") && CALLCID_CW_widgetJson.is_whatsapp_enabled){
                   parentNode.querySelector("#CW_WHATSAPP_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_WHATSAPP_C_DD_LI_${iso_code}`).innerHTML;
                   parentNode.querySelector("#CW_whatsapp_country_id").value = c.dial_code;
               }
               // parentNode.querySelector("#CW_T_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_T_C_DD_LI_${iso_code}`).innerHTML;
               // parentNode.querySelector("#CW_P_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_T_C_DD_LI_${iso_code}`).innerHTML;
               // parentNode.querySelector("#CW_E_C_DD_SEL").innerHTML = parentNode.querySelector(`#CW_E_C_DD_LI_${iso_code}`).innerHTML;
               if(parentNode.querySelector('CW_text_country_id') !== null){
                parentNode.querySelector('#CW_text_country_id').value = c.dial_code;
               }
               if(parentNode.querySelector("#cw-country_id") !== null){
                parentNode.querySelector("#cw-country_id").value = c.dial_code;
               }
               
           }
           return c.code == clientcountry
        });
    /*FOR COUNTRY CODE*/
}

function CALLCID_CW_getGeoData(parentNode){
    CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=get_geo", {"data":"get_geo"})
    .then(result => {
        //var CALLCID_CW_result =  JSON.parse(result);
		if(result.ip !== undefined && result.ip !== null ){
                localStorage.setItem(`cw-WIDGET-3P-LocRes`,JSON.stringify(result));
		}
		CALLCID_CW_setLoc(result,parentNode);

    });
}



function convertTZ(date, tzString) {
    return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}

function hideWidgetForaMonth(){
            var widget_clsebtn = document.getElementsByClassName("widget_clsebtn");
            if(widget_clsebtn !== null && widget_clsebtn !== undefined){
                for(btnIndex = 0; btnIndex < widget_clsebtn.length; btnIndex++){
                    widget_clsebtn[btnIndex].addEventListener("click",function(event){
                        event.stopImmediatePropagation();
                        var oneMonthDate =  CALLCID_CW_DateHelper.addDays(new Date(), 30).getTime();
                            if(confirm("Are you sure to hide widget for a month?")){
                                localStorage.setItem(`cw-${CALLCID_CW_widget_id}-hiddenTill`,oneMonthDate);
                                //mDw
                                document.getElementById(`mDw${CALLCID_CW_UI}`).outerHTML = "";
                                var Targetdivs = document.getElementsByClassName(`cwTargetScript-${CALLCID_CW_UI}`);
                               
                                ////console.log("Targetdivs.length",Targetdivs.length);
                                for (targetDivIndex = 0; targetDivIndex < Targetdivs.length; targetDivIndex++) {
                                    Targetdivs[targetDivIndex].outerHTML = "";
                                }
                            }
                    });
                }
                
            }
            
         
}

var pluseinoutToggle = setInterval(pluseinout, (CALLCID_CW_widgetJson.animation_interval / 2 ) *1000);
//var dt = new Date().getSeconds();

function pluseinout(){
    //open-button
    var currentTime = new Date().getSeconds();
    ////////console.log("DIFFERENT = currentTime",(currentTime - dt));
    var element =  document.getElementsByClassName("open-button");
    //isExists = element[0].classList.contains("animation-in");
    for (var i = 0; i < element.length; i++) {
        //ts[i].style.display="none";
        isExists = element[i].classList.contains("toggleAnimation");
        //////console.log("isExists => ",isExists,CALLCID_CW_widgetJson.animation_interval);
        if(isExists){
            element[i].classList.remove("toggleAnimation");
        } else {
           element[i].classList.add("toggleAnimation"); 
        }
    }
    
}


function removCls(element){
    //element.classList.add("toggleAnimation"); 
    //pluseinoutToggle = setInterval(pluseinout, CALLCID_CW_widgetJson.animation_interval*1000);
}

var previous_widget_video_width = 0;
var previous_widget_video_height = 0;

function initializeVideoPlayer(element) {
    function playVideo() {
        element.currentTime = 0;
        element.muted = !element.muted;
    }
    var video = element;
    if (element.classList.contains('closed')) {
      previous_widget_video_width = element.offsetWidth;
      previous_widget_video_height = element.offsetHeight;
      element.classList.remove('closed');
      element.classList.add('active');
      element.parentElement.querySelector('.close-widget-video-icon').style.display = 'block';
      element.style.maxHeight = '400px';
      element.style.maxWidth = '300px';
      setTimeout(function() {
        video.nextElementSibling.style.display = 'block';
      }, 150);
    } else {
      element.classList.remove('active');
      element.classList.add('closed');
      element.style.maxHeight = '130px';
      element.style.maxWidth = '185px';
      element.style.minHeight = previous_widget_video_height + 'px';
      element.style.minWidth = previous_widget_video_width + 'px';
      element.nextElementSibling.style.display = 'none';
      element.parentElement.querySelector('.close-widget-video-icon').style.display = 'none';
    }

    if(element.classList.contains('btn_video')){
        playVideo();
    }

}

function closeWidgetVideoPlayer(element){
    var targetEle = element.parentElement.querySelector('.widgetVideo');
    initializeVideoPlayer(targetEle) 
}


//Voice Message Section all events
let CW_timerId;
let mediaRecorder;
let recordedChunks = [];
let CW_startTime;
let recordedBlob;
let CW_duration;
let notResetButton = true;

//check the Media input device
function validateMediaDevice(element) {
    var parentSection = element.closest("#vvmOpt");
    if (navigator.mediaDevices && typeof navigator.mediaDevices.getUserMedia === 'function' && typeof MediaRecorder === 'function') {
        <!-- console.log('Recording API is supported in this browser.'); -->
        navigator.mediaDevices.enumerateDevices()
            .then(function (devices) {
                const audioInputDevices = devices.filter(device => device.kind === 'audioinput');
                if (audioInputDevices.length > 0) {
                    <!-- console.log('Microphone device(s) available.'); -->
                    startRecording(element);  // Access the microphone and start recording
                } else {
                    CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> No microphone device available.</div>",parentSection);
                    CALLCID_CW_clearmsg();
                }
            })
            .catch(function (error) {
                CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'> Error enumerating media devices: ${error}</div>`,parentSection);
                CALLCID_CW_clearmsg();
            });

    } else {
        CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'> Recording API is not supported in this browser.</div>`,parentSection);
        CALLCID_CW_clearmsg();
    }
}

// Access the microphone and start recording
function startRecording(element) {
    element.disabled = true;
    var parentSection = element.closest("#vvmOpt");
    navigator.mediaDevices.getUserMedia({ audio: true })
        .then(function (stream) {
            // Create a MediaRecorder object
            mediaRecorder = new MediaRecorder(stream);

            // Add event listeners for data available and stop recording
            mediaRecorder.addEventListener('dataavailable', function (event) {
                recordedChunks.push(event.data);
            });

            mediaRecorder.addEventListener('stop', function () {

                if(notResetButton){
                    // Convert the recorded chunks into a single Blob
                    recordedBlob = new Blob(recordedChunks, { type: 'audio/mpeg' });

                    // Calculate the duration of the recording
                    CW_duration = (Date.now() - CW_startTime) / 1000;
                    parentSection.querySelector("#count_seconds").value = Math.floor(CW_duration);

                    // Play the recorded audio
                    if(recordedBlob){
                        const cwAudioPlay = parentSection.querySelector("#cw_audio_file");
                        cwAudioPlay.src = URL.createObjectURL(recordedBlob);
                        cwAudioPlay.load();
                        cwAudioPlay.parentElement.style.display = 'block';
                        cwAudioPlay.play();
                    }

                }
                notResetButton = true;

                // Enable the stop button and disable the start button
                element.disabled = false;
                parentSection.querySelector("#stop_record").disabled = true;
                parentSection.querySelector("#cw_reset_record_immediate").disabled = true;


                // Clear the recorded chunks for the next recording
                recordedChunks = [];

            });

            // Start recording with a specified time slice (optional)
            mediaRecorder.start(10); // Record chunks every 10ms

            //show recording section
            parentSection.querySelector("#record-voice-wrapper").style.display = "none";
            parentSection.querySelector("#speak-now-wrapper").style.display = "block";

            // Disable the start button and enable the stop button
            element.disabled = true;
            parentSection.querySelector("#stop_record").disabled = false;
            parentSection.querySelector("#cw_reset_record_immediate").disabled = false;

            let timeElm = parentSection.querySelector('#record_time_count');
            let timer = function(x) {
                if (x === 30) {
                    return CW_Voice_StopAudio(element);
                }
                timeElm.innerHTML = x;
                CW_timerId =  setTimeout(() => {timer(++x)}, 1000);
            }
            timer(0);

            // Store the start time of the recording
            CW_startTime = Date.now();
        })
        .catch(function (error) {

            element.disabled = false;
            CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'> Error accessing the microphone: ${error}</div>`,parentSection);
            CALLCID_CW_clearmsg();
        });

}

// Play the recorded audio
function playRecording(blob) {
    const audioPlayer = document.getElementById('cw_audio_file');
    audioPlayer.src = URL.createObjectURL(blob);
    audioPlayer.parentElement.style.display = 'block';
    audioPlayer.play();
}

function CW_justStopRecord(element) {
    var parentSection = element.closest("#vvmOpt");
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        notResetButton = false;
        mediaRecorder.stop();
    }
}


//Onclick calling start recording function 
function CW_Voice_startRecord(element) {
    validateMediaDevice(element);
}

function CW_Voice_resetAudio(element){
    var parent = element.closest('.form-group');
    var parentSection = element.closest("#vvmOpt");
    parent.style.display = "none";
    
    if(element.getAttribute('id') == 'cw_reset_record_immediate'){
        if (mediaRecorder && mediaRecorder.state !== 'inactive') {
            notResetButton = false;
            mediaRecorder.stop();
        }
        parentSection.querySelector("#record-voice-wrapper").style.display = "block";
        CW_Voice_removeAudio(element);
    }else{
        parentSection.querySelector("#reset-recording-wrapper").style.display = "block";
    }
}

function CW_Voice_removeAudio(element){
    var parentSection = element.closest("#vvmOpt");
    parentSection.querySelector("#audio_display_wrapper").style.display = "none";
    var audio = parentSection.querySelector('#cw_audio_file');
        audio.pause();
        audio.setAttribute("src", "");
        clearTimeout(CW_timerId);
}

function CW_Voice_StopAudio(element) {
    var parentSection = element.closest("#vvmOpt");
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
    }
    parentSection.querySelector("#speak-now-wrapper").style.display = "none";
    parentSection.querySelector("#your-recording-wrapper").style.display = "block";
    clearTimeout(CW_timerId);
}




function CW_Voice_StopRecord(element) {
    var parentSection = element.closest("#vvmOpt");
    parentSection.querySelector("#speak-now-wrapper").style.display = "none";
    parentSection.querySelector("#your-recording-wrapper").style.display = "block";
    clearTimeout(CW_timerId);
    CW_Voice_StopAudio(element);
}


function CW_Voice_ProceedRecord(element) {  
    var parentSection = element.closest("#vvmOpt");    
    parentSection.querySelector("#your-recording-wrapper").style.display = "none";
    parentSection.querySelector("#send-data-wrapper").style.display = "block";
    var x = parentSection.querySelector("#cw_audio_file");
    x.pause();
}

function CW_Voice_ViewRecord(element) { 
    var parentSection = element.closest("#vvmOpt");
    parentSection.querySelector("#send-data-wrapper").style.display = "none";
    parentSection.querySelector("#your-recording-wrapper").style.display = "block";
}

function CW_Voice_ResetRecord(element) {    
    var parentSection = element.closest("#vvmOpt");
    parentSection.querySelector("#reset-recording-wrapper").style.display = "none";
    parentSection.querySelector("#record-voice-wrapper").style.display = "block";
    CW_Voice_removeAudio(element);
}

function CW_Voice_ResetRecordCancel(element) {
    var parentSection = element.closest("#vvmOpt");   
    parentSection.querySelector("#reset-recording-wrapper").style.display = "none";
    parentSection.querySelector("#send-data-wrapper").style.display = "block";
}

// Processing Voice Message REQUEST
async function CW_Voice_SendData(element){

    var parentSection = element.closest("#vvmOpt");
    var audioFile = parentSection.querySelector("#cw_audio_file");
    var senderName = parentSection.querySelector("#voice_sender_name");
    var senderEmail = parentSection.querySelector("#voice_sender_email");
    var phone = parentSection.querySelector("#voice_phone").value;
    var country_id = parentSection.querySelector("#CW_voice_country_id").value;
    var seconds_wrapper_cw = document.querySelector("#count_seconds").value;
    var body = senderName.closest('.box-body');
    if(audioFile.getAttribute("src") == ''){
        var alertBox = body.querySelector('.alert_message');
        alertBox.innerHTML = "<div class='alert alert-danger'>Error! Please Record Audio First</div>";
        CALLCID_CW_clearmsg();
        return false;
    }
    if(senderName.value == ''){
        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Name is required</div>",parentSection);
        CALLCID_CW_clearmsg();
        return false;
    } 
    if(senderEmail.value == ''){
        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Email is required</div>",parentSection);
        CALLCID_CW_clearmsg();
        return false;
    }
    if(!validateEmail(senderEmail.value)){
        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Enter valid email.</div>",parentSection);
        CALLCID_CW_clearmsg();
        return false;
    }
    if(phone == '' || phone == undefined || phone == null ){
        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Phone is required</div>",parentSection);
        CALLCID_CW_clearmsg();
        return false;
    }
    if(country_id == '' || country_id == undefined || country_id == null ){
        CALLCID_CW_setAlertMessage("alert_message","<div class='alert alert-danger'> Country is required</div>",parentSection);
        CALLCID_CW_clearmsg();
        return false;
    }
    
    <!-- let blob = await fetch(audioFile.src).then(r => r.blob()); -->
    
    var saveObj = new FormData();
    saveObj.append('name', senderName.value);
    saveObj.append('email', senderEmail.value);
    saveObj.append('phone', phone);
    saveObj.append('country_id', country_id);
    saveObj.append('record_duration', seconds_wrapper_cw);
    saveObj.append('audio_file', recordedBlob);
    saveObj.append('wi', CALLCID_CW_widget_id);
    var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
    var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
    if(CALLCID_CW_LocRes !== null){
        var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
        if(CALLCID_CW_LocResParsed){
            // IF JSON IS VALID
            CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
            CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
            CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
            CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
        }
    }
    saveObj.append('ip_address', CALLCID_CW_ip_address);
    saveObj.append('city', CALLCID_CW_city);
    saveObj.append('region', CALLCID_CW_region);
    saveObj.append('country_name', CALLCID_CW_country_name);
    console.log(saveObj);
    var old_button_text = parentSection.querySelector("#sbmt-vm-rq").innerText;
    parentSection.querySelector("#sbmt-vm-rq").setAttribute('disabled','disabled');
    parentSection.querySelector("#sbmt-vm-rq").innerText = 'Sending...';
    
    CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Please wait, sending voice message...</div>`,parentSection);
    CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-v-m", saveObj)
    .then(result => {
        parentSection.querySelector("#sbmt-vm-rq").removeAttribute('disabled');
        parentSection.querySelector("#sbmt-vm-rq").innerText = old_button_text;

        if(result.status == 1){
            parentSection.querySelector("#send-data-wrapper").style.display = "none";
            parentSection.querySelector("#record-voice-wrapper").style.display = "block";
            CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-success'>Success! ${result.message}</div>`,parentSection);
            CALLCID_CW_clearmsg();
            CALLCID_CW_resetForm(parentSection);
        } else {
            CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentSection);
            CALLCID_CW_clearmsg();
        }
    });

    return false;					

    
}

//Widget Email Attachment Events

function CW_EMAIL_createDeleteButton() {
    var deleteButton = document.createElement('span');
    deleteButton.textContent = 'x';
    deleteButton.classList.add('delete-email-widget-file');
    return deleteButton;
}


function CW_EMAIL_handleFileInput(element) {
    var parentSection = element.closest("#veOpt");
    var parent = element.closest('.box-body');
    var fileInput = parent.querySelectorAll('input[name=CALLCID_CW_email_attachment]')[0];
    var file = fileInput.files[0];
    var maxSize = 2097152; // 2MB
    var allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf'];
    var selectedFilesContainer = parent.querySelectorAll('.selected-files-email-attachment')[0];

    if (fileInput.files.length !== 1) {
        CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'> Please select only one file.</div>`,parentSection);
        CALLCID_CW_clearmsg();
    } else if (file.size > maxSize) {
        CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'> The file you attempted to upload is too large. Maximum size is 2MB.</div>`,parentSection);
        CALLCID_CW_clearmsg();
    } else if (!allowedExtensions.includes(file.name.split('.').pop().toLowerCase())) {
        CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'> Only .jpg, .png and .pdf files are allowed.</div>`,parentSection);
        CALLCID_CW_clearmsg();
    } else {
        var deleteButton = CW_EMAIL_createDeleteButton();
        selectedFilesContainer.innerHTML = `<span>${file.name}</span>`;
        selectedFilesContainer.appendChild(deleteButton);

        // Attach click event listener for the dynamically created delete button
        deleteButton.addEventListener('click', function(event) {
            CW_EMAIL_handleFileDeletionClick(event, parentSection);
        });
    }
}

// Event listener for the attachment field click
function CW_EMAIL_handleAttachmentFieldClick(element) {
    var parentSection = element.closest('#veOpt');
    var selectedFilesContainer = parentSection.querySelectorAll('.selected-files-email-attachment');
    selectedFilesContainer[0].innerHTML = "";
    var fileInput = parentSection.querySelectorAll('input[name=CALLCID_CW_email_attachment]');
    fileInput[0].value = '';
    fileInput[0].click();
}

// Event delegation for file deletion
function CW_EMAIL_handleFileDeletionClick(event) {
    var parentSection = event.target.closest(`#veOpt`);
    if (event.target.classList.contains("delete-email-widget-file")) {
        var selectedFilesContainer = event.target.parentElement.innerHTML = "";
        var fileInput = parentSection.querySelectorAll('input[name=CALLCID_CW_email_attachment]');
        fileInput[0].value = '';
    }
}


/*SUBMIT EMAIL REQUEST*/
function validateEmail(email) {
    const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}


// create a msg element div
function createMsgEle(conName,divVal){
    var userSentMsgContainer = document.createElement('div');
    userSentMsgContainer.className = conName;
    var userSentParagraph = document.createElement('p');
    userSentParagraph.className = 'chat-box';
    userSentParagraph.style.borderColor = CALLCID_CW_theme_color;
    //userSentParagraph.textContent = divVal;
   
    userSentParagraph.innerHTML = divVal;
    userSentMsgContainer.appendChild(userSentParagraph);
    return userSentMsgContainer;      
}

// create a msg element div
function createLoadingEle(){
    var responseEle = '<div class="received-message loading-animation">' +
                      '<div class="snippet" data-title="dot-pulse">' +
                      '<div class="stage">' +
                      '<div class="dot-pulse"></div>' +
                      '</div></div></div>';
    return responseEle;      
}

//closing statement message timeout
let CW_AI_Chat_msg;
let CW_AI_Chat_msg_Loader;
function createClosingMessage(parentNode) {
    var innerCont = createMsgEle('received-message', CALLCID_CW_Ai_Chat_Widget_Cls_Msg);
    var clsCon = document.createElement('div');
    clsCon.className = 'closing-message';
    clsCon.appendChild(innerCont);
    clsCon.insertAdjacentHTML('beforeend', '<button class="btn chatbox-btn" onclick="CW_rmClsEle(this)">Yes</button><button class="btn chatbox-btn" onclick="CW_EndAIScreenChat(this)">No</button>');

    parentNode.querySelector("#aiChatWrapper .chat-area-box").appendChild(clsCon);
}

function formatMessageChatResponse(message) {
     
     let formatted = message.replace(/\n/g, '<br>');
     formatted     = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
     return formatted;
 }


//Send User Question to AI Chatbot
function sendUserQuestion(element){
   
    if(element == 'vaicOpt'){
       var parentNode  = document.getElementById(element);
    }else{
        var parentNode = element.closest("#vaicOpt");
    }
   
    var user_thread_id = parentNode.querySelector("#user_thread_id");
    var userQuestion = parentNode.querySelector("#user_question"); 

    // remove the closing-message
    CW_rmClsEle(element);

    //clearTimeOut
    clearTimeout(CW_AI_Chat_msg_Loader);
    clearTimeout(CW_AI_Chat_msg);

    if(userQuestion.value == ""){
        var alertBox = body.querySelector('.alert_message');
        alertBox.innerHTML = "<div class='alert alert-danger'>Question is required.</div>";
        CALLCID_CW_clearmsg();
        return false;
    }
    
    var userSentMsgContainer = createMsgEle('sent-message',userQuestion.value);
    var chatAreaBox = parentNode.querySelector("#aiChatWrapper .chat-area-box");
    chatAreaBox.appendChild(userSentMsgContainer);
    CW_scrollBottom();

    // Append the first child of the temporary div to the chat area
    const loadingMessage = parentNode.querySelector("#aiChatWrapper .chat-area-box .received-message.loading-animation");
    if (loadingMessage) loadingMessage.remove();

    chatAreaBox.insertAdjacentHTML('beforeend', createLoadingEle());
    CW_scrollBottom();

    var saveObj = new FormData();
    saveObj.append('user_thread_id', user_thread_id.value);
    saveObj.append('user_question', userQuestion.value);
    saveObj.append('wi', CALLCID_CW_widget_id);

    var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
    var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
    if(CALLCID_CW_LocRes !== null){
        var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
        if(CALLCID_CW_LocResParsed){
            // IF JSON IS VALID
            CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
            CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
            CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
            CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
        }
    }
    saveObj.append('ip_address', CALLCID_CW_ip_address);
    saveObj.append('city', CALLCID_CW_city);
    saveObj.append('region', CALLCID_CW_region);
    saveObj.append('country_name', CALLCID_CW_country_name);

    userQuestion.value = "";
    autosize(userQuestion);
    CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-ai-c", saveObj)
    .then(result => {

        parentNode.querySelector("#aiChatWrapper .chat-area-box .received-message.loading-animation").remove();

        if(result.status == 1){

            var formattedMessage="";
            if(result.message !="") {
                 formattedMessage = formatMessageChatResponse(result.message);
            }
            
            var userRecMsgCon = createMsgEle('received-message',formattedMessage);
            chatAreaBox.appendChild(userRecMsgCon);                             
            CW_scrollBottom();

            CW_AI_Chat_msg_Loader = setTimeout(() => {
                // Append the first child of the temporary div to the chat area
                chatAreaBox.insertAdjacentHTML('beforeend', createLoadingEle());
                CW_scrollBottom()
            }, 118000);

            if(CALLCID_CW_Ai_Chat_Widget_Cls_Msg != ''){
                CW_AI_Chat_msg = setTimeout(() => {
                    parentNode.querySelector("#aiChatWrapper .chat-area-box .received-message.loading-animation").remove();
                    createClosingMessage(parentNode);
                    CW_scrollBottom();
                }, 120000);
            }
        } else {
            CALLCID_CW_setAlertMessage("alert_message",`<div class='alert alert-danger'>Error! ${result.message}</div>`,parentNode);
            CALLCID_CW_clearmsg();
        }
    });
}

//this function is used to scroll bottom in chat screen
function CW_scrollBottom(){
    var chkSrl = document.querySelector("#aiChatWrapper .chat-area-box");
    var lastMessage = chkSrl.lastElementChild;

    if (lastMessage) {
        lastMessage.scrollIntoView({ behavior: 'smooth', block: 'end' });
    }
}

//this function is use to end the AI screen Chat
function CW_EndAIScreenChat(element){
    var parentNode = document.getElementById('vaicOpt');
    parentNode.querySelector(".aiChatScreen #ques-btn").style.display = "none";

    CW_rmClsEle(element);

    CALLCID_AI_CHAT_FIELDS_Toggle = false; // Reset AI Chat //

    var chatAreaBox = parentNode.querySelector("#aiChatWrapper .chat-area-box");
    var userRecMsgCon = createMsgEle('received-message',CALLCID_CW_Ai_Chat_Widget_Thx_Msg);
    chatAreaBox.appendChild(userRecMsgCon);
    CW_scrollBottom(); 
}

//this function is use to continue the AI screen Chat
function CW_rmClsEle(element){
    var parentNode =  document.getElementById('vaicOpt');
    var checkExistCls = parentNode.querySelector("#aiChatWrapper .chat-area-box .closing-message");
    checkExistCls && checkExistCls.remove();
}

//update video meeting request status
function CW_updateVideoReqStatus(request_id,parentNode){

    var saveObj = new FormData();
    saveObj.append('request_id', request_id);
    saveObj.append('no_response', 1);
    saveObj.append('wi', CALLCID_CW_widget_id);

    var CALLCID_CW_LocRes = localStorage.getItem(`cw-WIDGET-3P-LocRes`);
    var CALLCID_CW_ip_address,CALLCID_CW_city,CALLCID_CW_region,CALLCID_CW_country_name;
    if(CALLCID_CW_LocRes !== null){
        var CALLCID_CW_LocResParsed = JSON.parse(CALLCID_CW_LocRes);
        if(CALLCID_CW_LocResParsed){
            // IF JSON IS VALID
            CALLCID_CW_ip_address = CALLCID_CW_LocResParsed.ip;
            CALLCID_CW_city = CALLCID_CW_LocResParsed.city;
            CALLCID_CW_region = CALLCID_CW_LocResParsed.region;
            CALLCID_CW_country_name = CALLCID_CW_LocResParsed.country_name;
        }
    }
    saveObj.append('ip_address', CALLCID_CW_ip_address);
    saveObj.append('city', CALLCID_CW_city);
    saveObj.append('region', CALLCID_CW_region);
    saveObj.append('country_name', CALLCID_CW_country_name);

    CALLCID_CW_postData(CALLCID_CW_base_url+"/callwidget-save?f=u-r-v-m-s", saveObj)
    .then(result => {});
}


function autosize(ele) { 
  var el = ele;
  setTimeout(function() {
    el.style.cssText = 'height:auto; padding:0;'; // Concatenate both styles into a single string
    el.style.cssText += 'height:' + el.scrollHeight + 'px;'; // Append the new style
  }, 0);
}

function openWhatsAppLink(){
    var wa_redirect_link = "https://wa.me/"+CALLCID_WHATSAPP_PHONE_NUMBER;
    window.open(wa_redirect_link, '_blank'); 
}

var CALLCID_CW_countries = [{"name":"Afghanistan","dial_code":"+93","code":"AF"},{"name":"Albania","dial_code":"+355","code":"AL"},{"name":"Algeria","dial_code":"+213","code":"DZ"},{"name":"AmericanSamoa","dial_code":"+1 684","code":"AS"},{"name":"Andorra","dial_code":"+376","code":"AD"},{"name":"Angola","dial_code":"+244","code":"AO"},{"name":"Anguilla","dial_code":"+1 264","code":"AI"},{"name":"Antarctica","dial_code":"+672","code":"AQ"},{"name":"Antigua and Barbuda","dial_code":"+1268","code":"AG"},{"name":"Argentina","dial_code":"+54","code":"AR"},{"name":"Armenia","dial_code":"+374","code":"AM"},{"name":"Aruba","dial_code":"+297","code":"AW"},{"name":"Australia","dial_code":"+61","code":"AU"},{"name":"Austria","dial_code":"+43","code":"AT"},{"name":"Azerbaijan","dial_code":"+994","code":"AZ"},{"name":"Bahamas","dial_code":"+1 242","code":"BS"},{"name":"Bahrain","dial_code":"+973","code":"BH"},{"name":"Bangladesh","dial_code":"+880","code":"BD"},{"name":"Barbados","dial_code":"+1 246","code":"BB"},{"name":"Belarus","dial_code":"+375","code":"BY"},{"name":"Belgium","dial_code":"+32","code":"BE"},{"name":"Belize","dial_code":"+501","code":"BZ"},{"name":"Benin","dial_code":"+229","code":"BJ"},{"name":"Bermuda","dial_code":"+1 441","code":"BM"},{"name":"Bhutan","dial_code":"+975","code":"BT"},{"name":"Bolivia, Plurinational State of","dial_code":"+591","code":"BO"},{"name":"Bosnia and Herzegovina","dial_code":"+387","code":"BA"},{"name":"Botswana","dial_code":"+267","code":"BW"},{"name":"Brazil","dial_code":"+55","code":"BR"},{"name":"British Indian Ocean Territory","dial_code":"+246","code":"IO"},{"name":"Brunei Darussalam","dial_code":"+673","code":"BN"},{"name":"Bulgaria","dial_code":"+359","code":"BG"},{"name":"Burkina Faso","dial_code":"+226","code":"BF"},{"name":"Burundi","dial_code":"+257","code":"BI"},{"name":"Cambodia","dial_code":"+855","code":"KH"},{"name":"Cameroon","dial_code":"+237","code":"CM"},{"name":"Canada","dial_code":"+1","code":"CA"},{"name":"Cape Verde","dial_code":"+238","code":"CV"},{"name":"Cayman Islands","dial_code":"+ 345","code":"KY"},{"name":"Central African Republic","dial_code":"+236","code":"CF"},{"name":"Chad","dial_code":"+235","code":"TD"},{"name":"Chile","dial_code":"+56","code":"CL"},{"name":"China","dial_code":"+86","code":"CN"},{"name":"Christmas Island","dial_code":"+61","code":"CX"},{"name":"Cocos (Keeling) Islands","dial_code":"+61","code":"CC"},{"name":"Colombia","dial_code":"+57","code":"CO"},{"name":"Comoros","dial_code":"+269","code":"KM"},{"name":"Congo","dial_code":"+242","code":"CG"},{"name":"Congo, The Democratic Republic of the","dial_code":"+243","code":"CD"},{"name":"Cook Islands","dial_code":"+682","code":"CK"},{"name":"Costa Rica","dial_code":"+506","code":"CR"},{"name":"Cote d'Ivoire","dial_code":"+225","code":"CI"},{"name":"Croatia","dial_code":"+385","code":"HR"},{"name":"Cuba","dial_code":"+53","code":"CU"},{"name":"Cyprus","dial_code":"+357","code":"CY"},{"name":"Czech Republic","dial_code":"+420","code":"CZ"},{"name":"Denmark","dial_code":"+45","code":"DK"},{"name":"Djibouti","dial_code":"+253","code":"DJ"},{"name":"Dominica","dial_code":"+1 767","code":"DM"},{"name":"Dominican Republic","dial_code":"+1 849","code":"DO"},{"name":"Ecuador","dial_code":"+593","code":"EC"},{"name":"Egypt","dial_code":"+20","code":"EG"},{"name":"El Salvador","dial_code":"+503","code":"SV"},{"name":"Equatorial Guinea","dial_code":"+240","code":"GQ"},{"name":"Eritrea","dial_code":"+291","code":"ER"},{"name":"Estonia","dial_code":"+372","code":"EE"},{"name":"Ethiopia","dial_code":"+251","code":"ET"},{"name":"Falkland Islands (Malvinas)","dial_code":"+500","code":"FK"},{"name":"Faroe Islands","dial_code":"+298","code":"FO"},{"name":"Fiji","dial_code":"+679","code":"FJ"},{"name":"Finland","dial_code":"+358","code":"FI"},{"name":"France","dial_code":"+33","code":"FR"},{"name":"French Guiana","dial_code":"+594","code":"GF"},{"name":"French Polynesia","dial_code":"+689","code":"PF"},{"name":"Gabon","dial_code":"+241","code":"GA"},{"name":"Gambia","dial_code":"+220","code":"GM"},{"name":"Georgia","dial_code":"+995","code":"GE"},{"name":"Germany","dial_code":"+49","code":"DE"},{"name":"Ghana","dial_code":"+233","code":"GH"},{"name":"Gibraltar","dial_code":"+350","code":"GI"},{"name":"Greece","dial_code":"+30","code":"GR"},{"name":"Greenland","dial_code":"+299","code":"GL"},{"name":"Grenada","dial_code":"+1 473","code":"GD"},{"name":"Guadeloupe","dial_code":"+590","code":"GP"},{"name":"Guam","dial_code":"+1 671","code":"GU"},{"name":"Guatemala","dial_code":"+502","code":"GT"},{"name":"Guernsey","dial_code":"+44","code":"GG"},{"name":"Guinea","dial_code":"+224","code":"GN"},{"name":"Guinea-Bissau","dial_code":"+245","code":"GW"},{"name":"Guyana","dial_code":"+595","code":"GY"},{"name":"Haiti","dial_code":"+509","code":"HT"},{"name":"Holy See (Vatican City State)","dial_code":"+379","code":"VA"},{"name":"Honduras","dial_code":"+504","code":"HN"},{"name":"Hong Kong","dial_code":"+852","code":"HK"},{"name":"Hungary","dial_code":"+36","code":"HU"},{"name":"Iceland","dial_code":"+354","code":"IS"},{"name":"India","dial_code":"+91","code":"IN"},{"name":"Indonesia","dial_code":"+62","code":"ID"},{"name":"Iran, Islamic Republic of","dial_code":"+98","code":"IR"},{"name":"Iraq","dial_code":"+964","code":"IQ"},{"name":"Ireland","dial_code":"+353","code":"IE"},{"name":"Isle of Man","dial_code":"+44","code":"IM"},{"name":"Israel","dial_code":"+972","code":"IL"},{"name":"Italy","dial_code":"+39","code":"IT"},{"name":"Jamaica","dial_code":"+1 876","code":"JM"},{"name":"Japan","dial_code":"+81","code":"JP"},{"name":"Jersey","dial_code":"+44","code":"JE"},{"name":"Jordan","dial_code":"+962","code":"JO"},{"name":"Kazakhstan","dial_code":"+7 7","code":"KZ"},{"name":"Kenya","dial_code":"+254","code":"KE"},{"name":"Kiribati","dial_code":"+686","code":"KI"},{"name":"Korea, Democratic People's Republic of","dial_code":"+850","code":"KP"},{"name":"Korea, Republic of","dial_code":"+82","code":"KR"},{"name":"Kuwait","dial_code":"+965","code":"KW"},{"name":"Kyrgyzstan","dial_code":"+996","code":"KG"},{"name":"Lao People's Democratic Republic","dial_code":"+856","code":"LA"},{"name":"Latvia","dial_code":"+371","code":"LV"},{"name":"Lebanon","dial_code":"+961","code":"LB"},{"name":"Lesotho","dial_code":"+266","code":"LS"},{"name":"Liberia","dial_code":"+231","code":"LR"},{"name":"Libyan Arab Jamahiriya","dial_code":"+218","code":"LY"},{"name":"Liechtenstein","dial_code":"+423","code":"LI"},{"name":"Lithuania","dial_code":"+370","code":"LT"},{"name":"Luxembourg","dial_code":"+352","code":"LU"},{"name":"Macao","dial_code":"+853","code":"MO"},{"name":"Macedonia, The Former Yugoslav Republic of","dial_code":"+389","code":"MK"},{"name":"Madagascar","dial_code":"+261","code":"MG"},{"name":"Malawi","dial_code":"+265","code":"MW"},{"name":"Malaysia","dial_code":"+60","code":"MY"},{"name":"Maldives","dial_code":"+960","code":"MV"},{"name":"Mali","dial_code":"+223","code":"ML"},{"name":"Malta","dial_code":"+356","code":"MT"},{"name":"Marshall Islands","dial_code":"+692","code":"MH"},{"name":"Martinique","dial_code":"+596","code":"MQ"},{"name":"Mauritania","dial_code":"+222","code":"MR"},{"name":"Mauritius","dial_code":"+230","code":"MU"},{"name":"Mayotte","dial_code":"+262","code":"YT"},{"name":"Mexico","dial_code":"+52","code":"MX"},{"name":"Micronesia, Federated States of","dial_code":"+691","code":"FM"},{"name":"Moldova, Republic of","dial_code":"+373","code":"MD"},{"name":"Monaco","dial_code":"+377","code":"MC"},{"name":"Mongolia","dial_code":"+976","code":"MN"},{"name":"Montenegro","dial_code":"+382","code":"ME"},{"name":"Montserrat","dial_code":"+1664","code":"MS"},{"name":"Morocco","dial_code":"+212","code":"MA"},{"name":"Mozambique","dial_code":"+258","code":"MZ"},{"name":"Myanmar","dial_code":"+95","code":"MM"},{"name":"Namibia","dial_code":"+264","code":"NA"},{"name":"Nauru","dial_code":"+674","code":"NR"},{"name":"Nepal","dial_code":"+977","code":"NP"},{"name":"Netherlands","dial_code":"+31","code":"NL"},{"name":"Netherlands Antilles","dial_code":"+599","code":"AN"},{"name":"New Caledonia","dial_code":"+687","code":"NC"},{"name":"New Zealand","dial_code":"+64","code":"NZ"},{"name":"Nicaragua","dial_code":"+505","code":"NI"},{"name":"Niger","dial_code":"+227","code":"NE"},{"name":"Nigeria","dial_code":"+234","code":"NG"},{"name":"Niue","dial_code":"+683","code":"NU"},{"name":"Norfolk Island","dial_code":"+672","code":"NF"},{"name":"Northern Mariana Islands","dial_code":"+1 670","code":"MP"},{"name":"Norway","dial_code":"+47","code":"NO"},{"name":"Oman","dial_code":"+968","code":"OM"},{"name":"Pakistan","dial_code":"+92","code":"PK"},{"name":"Palau","dial_code":"+680","code":"PW"},{"name":"Palestinian Territory, Occupied","dial_code":"+970","code":"PS"},{"name":"Panama","dial_code":"+507","code":"PA"},{"name":"Papua New Guinea","dial_code":"+675","code":"PG"},{"name":"Paraguay","dial_code":"+595","code":"PY"},{"name":"Peru","dial_code":"+51","code":"PE"},{"name":"Philippines","dial_code":"+63","code":"PH"},{"name":"Pitcairn","dial_code":"+872","code":"PN"},{"name":"Poland","dial_code":"+48","code":"PL"},{"name":"Portugal","dial_code":"+351","code":"PT"},{"name":"Puerto Rico","dial_code":"+1 939","code":"PR"},{"name":"Qatar","dial_code":"+974","code":"QA"},{"name":"Romania","dial_code":"+40","code":"RO"},{"name":"Russia","dial_code":"+7","code":"RU"},{"name":"Rwanda","dial_code":"+250","code":"RW"},{"name":"Réunion","dial_code":"+262","code":"RE"},{"name":"Saint Barthélemy","dial_code":"+590","code":"BL"},{"name":"Saint Helena, Ascension and Tristan Da Cunha","dial_code":"+290","code":"SH"},{"name":"Saint Kitts and Nevis","dial_code":"+1 869","code":"KN"},{"name":"Saint Lucia","dial_code":"+1 758","code":"LC"},{"name":"Saint Martin","dial_code":"+590","code":"MF"},{"name":"Saint Pierre and Miquelon","dial_code":"+508","code":"PM"},{"name":"Saint Vincent and the Grenadines","dial_code":"+1 784","code":"VC"},{"name":"Samoa","dial_code":"+685","code":"WS"},{"name":"San Marino","dial_code":"+378","code":"SM"},{"name":"Sao Tome and Principe","dial_code":"+239","code":"ST"},{"name":"Saudi Arabia","dial_code":"+966","code":"SA"},{"name":"Senegal","dial_code":"+221","code":"SN"},{"name":"Serbia","dial_code":"+381","code":"RS"},{"name":"Seychelles","dial_code":"+248","code":"SC"},{"name":"Sierra Leone","dial_code":"+232","code":"SL"},{"name":"Singapore","dial_code":"+65","code":"SG"},{"name":"Slovakia","dial_code":"+421","code":"SK"},{"name":"Slovenia","dial_code":"+386","code":"SI"},{"name":"Solomon Islands","dial_code":"+677","code":"SB"},{"name":"Somalia","dial_code":"+252","code":"SO"},{"name":"South Africa","dial_code":"+27","code":"ZA"},{"name":"South Georgia and the South Sandwich Islands","dial_code":"+500","code":"GS"},{"name":"Spain","dial_code":"+34","code":"ES"},{"name":"Sri Lanka","dial_code":"+94","code":"LK"},{"name":"Sudan","dial_code":"+249","code":"SD"},{"name":"Suriname","dial_code":"+597","code":"SR"},{"name":"Svalbard and Jan Mayen","dial_code":"+47","code":"SJ"},{"name":"Swaziland","dial_code":"+268","code":"SZ"},{"name":"Sweden","dial_code":"+46","code":"SE"},{"name":"Switzerland","dial_code":"+41","code":"CH"},{"name":"Syrian Arab Republic","dial_code":"+963","code":"SY"},{"name":"Taiwan","dial_code":"+886","code":"TW"},{"name":"Tajikistan","dial_code":"+992","code":"TJ"},{"name":"Tanzania, United Republic of","dial_code":"+255","code":"TZ"},{"name":"Thailand","dial_code":"+66","code":"TH"},{"name":"Timor-Leste","dial_code":"+670","code":"TL"},{"name":"Togo","dial_code":"+228","code":"TG"},{"name":"Tokelau","dial_code":"+690","code":"TK"},{"name":"Tonga","dial_code":"+676","code":"TO"},{"name":"Trinidad and Tobago","dial_code":"+1 868","code":"TT"},{"name":"Tunisia","dial_code":"+216","code":"TN"},{"name":"Turkey","dial_code":"+90","code":"TR"},{"name":"Turkmenistan","dial_code":"+993","code":"TM"},{"name":"Turks and Caicos Islands","dial_code":"+1 649","code":"TC"},{"name":"Tuvalu","dial_code":"+688","code":"TV"},{"name":"Uganda","dial_code":"+256","code":"UG"},{"name":"Ukraine","dial_code":"+380","code":"UA"},{"name":"United Arab Emirates","dial_code":"+971","code":"AE"},{"name":"United Kingdom","dial_code":"+44","code":"GB"},{"name":"United States","dial_code":"+1","code":"US"},{"name":"Uruguay","dial_code":"+598","code":"UY"},{"name":"Uzbekistan","dial_code":"+998","code":"UZ"},{"name":"Vanuatu","dial_code":"+678","code":"VU"},{"name":"Venezuela, Bolivarian Republic of","dial_code":"+58","code":"VE"},{"name":"Viet Nam","dial_code":"+84","code":"VN"},{"name":"Virgin Islands, British","dial_code":"+1 284","code":"VG"},{"name":"Virgin Islands, U.S.","dial_code":"+1 340","code":"VI"},{"name":"Wallis and Futuna","dial_code":"+681","code":"WF"},{"name":"Yemen","dial_code":"+967","code":"YE"},{"name":"Zambia","dial_code":"+260","code":"ZM"},{"name":"Zimbabwe","dial_code":"+263","code":"ZW"},{"name":"Åland Islands","dial_code":"+358","code":"AX"}]
