function ChatBot() {

    var container = document.createElement("div");
    var open = "true";
    var leadTypeId = "<#leadRef>";

    ///var newStyles = "<style type=\"text/css\" > https://app-beacon-webchat.azurewebsites.net/css/site.css </style>";
    var head = document.head || document.getElementsByTagName('head')[0];
    // var style = document.createElement('style');
    //head.appendChild(style);
    var linkRef = document.createElement('link');
    linkRef.rel = "stylesheet";
    linkRef.href = "https://app-beacon-webchat.azurewebsites.net/css/site.css";
    head.appendChild(linkRef);

    //if (style.styleSheet) {
    //    // This is required for IE8 and below.
    //    style.styleSheet.cssText = newStyles;
    //} else {
    //    style.appendChild(document.createTextNode(newStyles));
    //}

  


    var shouldRender = true;    // If the config sets this false, we will instead redirect

    console.log("Looking for lead id:");
    var leadid = URLParam("leadid");
    console.log(leadid);

    var five9options_ExistingCustomers = {
        "rootUrl": "https://app.five9.eu/consoles/",
        "type": "chat",
        "title": "Debt Advice",
        "tenant": "Babble01",
        "profiles": "CF - Customer Service WC",
        "showProfiles": false,
        "autostart": true,
        "profileLabel": "Live Chat Team from Creditfix",
        "theme": "default.css",
        "logo": "https://www.creditfix.co.uk/wp-content/themes/credit-fix/dist/img/Official%20Creditfix%20Logo%20dark.svg",

        "surveyOptions": {
            "showComment": true,
            "requireComment": false
        },

        "fields": {
            "name": {
                "value": "",
                "show": true,
                "label": "Name"
            }
        },
        "playSoundOnMessage": true,
        "allowCustomerToControlSoundPlay": false,
        "showEmailButton": true,
        "hideDuringAfterHours": true,
        "useBusinessHours": true,
        "showPrintButton": true,
        "allowUsabilityMenu": true,
        "enableCallback": false,
        "callbackList": "",
        "allowRequestLiveAgent": false,
        "ga": "87361258-1"
    };
    var five9options_DebtAdvice = {
        "rootUrl": "https://app.five9.eu/consoles/",
        "type": "chat",
        "title": "Debt Advice",
        "tenant": "Creditfix-OSP",
        "profiles": "TEST WEBCHAT",
        "showProfiles": false,
        "autostart": true,
        "profileLabel": "Live Chat Team from Creditfix",
        "theme": "default.css",
        "logo": "https://www.creditfix.co.uk/wp-content/themes/credit-fix/dist/img/Official%20Creditfix%20Logo%20dark.svg",

        "surveyOptions": {
            "showComment": true,
            "requireComment": false
        },

        "fields": {
            "name": {
                "value": "",
                "show": true,
                "label": "Name"
            }
        },
        "playSoundOnMessage": true,
        "allowCustomerToControlSoundPlay": false,
        "showEmailButton": true,
        "hideDuringAfterHours": true,
        "useBusinessHours": true,
        "showPrintButton": true,
        "allowUsabilityMenu": true,
        "enableCallback": false,
        "callbackList": "",
        "allowRequestLiveAgent": false,
        "ga": "87361258-1"

    };

    var config = {};
    if (open === "false") {
        config = {
            pages: {
                "Intro": {
                    text: "Sorry, we're currently closed but if you leave some details below, we'll contact you as soon as someone is available",
                    options: [
                        {
                            label: "I'd like to be called back",
                            page: "Collect"
                        }
                    ]
                },
                "Collect": {
                    text: "Please enter some details below",
                    fields: [
                        {
                            label: "First Name",
                            required: true,
                            field: "Forename"
                        },
                        {
                            label: "Surname",
                            required: true,
                            field: "Surname"
                        },
                        {
                            label: "Email Address",
                            required: true,
                            field: "Email"
                        },
                        {
                            label: "Contact Number",
                            required: true,
                            field: "PhoneNumber"
                        }
                    ],
                    options: [
                        {
                            label: "Back",
                            page: "Intro"
                        },
                        {
                            label: "Submit",
                            action: function () {
                                var xmlHttp = new XMLHttpRequest();
                                xmlHttp.onreadystatechange = function () {
                                    showpage("Complete");
                                    /*
                                    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                                        //alert(xmlHttp.responseText);
                                        showpage("Complete");
                                    }
                                    */
                                }
                                var url = "https://func-trident-lead-import.azurewebsites.net/api/create?code=01KNo-ROf4crsnej7tGLaBUBwIUdz_QYskzdL0P6PhD0AzFuBMt6Ig==";
                               
                                var postObject = {
                                    "url": (window.location.origin),
                                    "emailOptIn": false,
                                    "smsOptIn": false,
                                    "phoneOptIn": false,
                                    "diallerOOHOptIn": false,
                                    "leadType": "Webchat",
                                    "firstname" : (document.getElementById("babbleInput_Forename").value),
                                    "surname" : (document.getElementById("babbleInput_Surname").value),
                                    "email" : (document.getElementById("babbleInput_Email").value),
                                    "mobile" : (document.getElementById("babbleInput_PhoneNumber").value)
                                };                       

                                console.log("URL: " + url);
                                console.log("postObject: " + JSON.stringify(postObject));

                                xmlHttp.open("POST", url);
                                xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                                xmlHttp.send(JSON.stringify(postObject));
                            },
                            page: "Submitting",
                            validate: true
                        }
                    ]
                },
                "Submitting": {
                    text: "Please wait while we send your request."
                },
                "Complete": {
                    text: "Thank you for your enquiry. Someone will be in touch as soon as possible.",
                    fields: [],
                    options: []
                }
            },
            startPage: "Intro"
        };
    }
    else if (leadid == null) {
        config = {
            pages: {
                "Intro": {
                    text: "Welcome! What can I help you with today?",
                    options: [
                        {
                            label: "I need help with debt",
                            page: "New",
                            action: function () {
                                setCookie("chatbranch", "debtadvice", 1);
                                ShowFive9(five9options_DebtAdvice);
                                try {
                                    window.adalyserTracker("trackEvent", "lce2", { a2: "Live Chat" }, true);
                                }
                                catch (err) {
                                    console.log("Adalyser not initialised");
                                }
                            }
                        },
                        {
                            label: "I'm an existing customer",
                            page: "Existing",
                            action: function () {
                                setCookie("chatbranch", "existing", 1);
                                ShowFive9(five9options_ExistingCustomers);
                            }
                        },
                        {
                            label: "Just browsing",
                            page: "Browsing"
                        }
                    ]
                },
                "New": {
                    text: "Please wait while we connect you to debt advice",
                },
                "Existing": {
                    text: "Please wait while we connect you to customer support"
                },
                "Browsing": {
                    text: "No problem! Have a look around and let us know if you have any questions.",
                    options: [
                        {
                            label: "Back",
                            page: "Intro"
                        }
                    ]
                }
            },
            startPage: "Intro"
        };
    }
    else {
        // Open, with lead id
        shouldRender = false;   // We don't want to show in this case.

        config = {
            pages: {
                "Intro": {
                    text: "We're open and you're an existing customer! This will trigger the redirect",
                    options: [
                    ]
                }
            },
            startPage: "Intro"
        };

        // Append the lead id as a hidden field to the chat
        five9options_DebtAdvice.fields["Solutions.LeadReference"] = {
            value: leadid,
            show: false,
            label: "LeadId",
            required: false
        };        
        ShowFive9(five9options_DebtAdvice);
        

    }

    function validate(pagename) {
        console.log("Validating for page " + pagename);
        var page = config.pages[pagename];

        var valid = true;
        if (page.fields) {
            for (let x in page.fields) {
                let field = page.fields[x].field;
                console.log("Validating " + field);

                let value = document.getElementById("babbleInput_" + field).value;
                console.log(field + ": " + value);

                document.getElementById("babbleTooltip_" + field).innerText = "";

                if (!value && page.fields[x].required) {
                    document.getElementById("babbleTooltip_" + field).innerText = "This field is required";
                    valid = false;
                }
            }
        }

        return valid;
    }

    function render() {
        if (!shouldRender) return;
        container.className = "babble chatcontainer";
        var html = "<div id=\"divBabbleHeader\" class=\"header\" >";
        html += "close";
        html += "</div>";

        html += "<div id=\"divBabblePage\" class=\"pagecontent\" >";
        html += "Question content";
        html += "</div>";
        //html += "<link rel=\"stylesheet\" href=\"https://babblechatbot.azurewebsites.net/Styles/CommonStyles.css\"/>";

        container.id = "divBabbleContainer";
        container.innerHTML = html;
        document.body.appendChild(container);

        var offer = document.createElement("div");
        offer.id = "babbleOfferChatButton";
        offer.className = "babble offerContainer";
        offer.innerText = "Chat to an advisor";

        offer.onclick = function () {
            container.style.display = "block";
            offer.style.display = "none";
            //try {
            //    window.adalyserTracker("trackEvent", "lce2", { a2: "Live Chat" }, true);
            //} 
            //catch (err) {
            //    console.log("Adalyser not initialised");
            //}
        }

        document.body.appendChild(offer);

        document.getElementById("divBabbleHeader").onclick = function () {
            container.style.display = "none";
            offer.style.display = "block";
        }

        showpage(config.startPage);
    }



    function showpage(pagename) {

        var page = config.pages[pagename];

        var babblePage = document.getElementById("divBabblePage");
        if (babblePage !== null) babblePage.remove();

        var div = document.createElement("div");
        div.id = "divBabblePage";
        div.className = "pagecontent";
        div.innerText = page.text;

        if (page.fields) {
            for (let x in page.fields) {
                let d = document.createElement("div");
                d.className = "control";
                let label = document.createElement("div");
                label.className = "label";
                label.innerText = page.fields[x].label;
                if (page.fields[x].required) {
                    label.innerText += "*";
                }

                let input = document.createElement("input");
                input.id = "babbleInput_" + page.fields[x].field;

                let tooltip = document.createElement("div");
                tooltip.className = "tooltip";
                tooltip.id = "babbleTooltip_" + page.fields[x].field;

                d.appendChild(label);
                d.appendChild(input);
                d.appendChild(tooltip);

                div.appendChild(d);
            }
        }

        for (let x in page.options) {
            let d = document.createElement("div");
            d.className = "buttonContainer";
            let b = document.createElement("button");
            b.innerText = page.options[x].label;

            b.onclick = function () {
                if (page.options[x].validate && validate(pagename) || !page.options[x].validate) {
                    if (page.options[x].action) {
                        page.options[x].action();
                    }

                    showpage(page.options[x].page);
                }
            }

            d.appendChild(b);
            div.appendChild(d);
        }

        container.appendChild(div);

    }

    function ShowFive9(options) {
        Five9SocialWidget.data["state"] = "maximized";
        Five9SocialWidget.addWidget(options);
        container.remove();
    }

    function URLParam(name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href.toLowerCase())
       
        if (results == null) {
            return null;
        }
        else {
            return results[1] || 0;
        }
    }

    console.log("Attempting to check state:");
    Five9SocialWidget.Persist = Five9Modules.Persist;
    var data = Five9SocialWidget.Persist.loadData(Five9SocialWidget.PersistKey);

    console.log(data);
    if (data === undefined) {
        //console.log("Enter the chatbot");
        render();
    }
    else {
        //console.log("Restore Chat");

        // Check cookie for which chat we were in...
        var branch = getCookie("chatbranch");
        if (branch === "existing") {
            Five9SocialWidget.addWidget(five9options_ExistingCustomers);
        }
        else {
            Five9SocialWidget.addWidget(five9options_DebtAdvice);
        }
    }


} ChatBot();