/**
 * Created by Tom Free
 * Inspired by: http://ryanmorr.com/using-mutation-observers-to-watch-for-element-availability/
 */

var listeners = [],
    doc = window.document,
    MutationObserver = window.MutationObserver || window.WebKitMutationObserver,
    observer;
var DomObserver = {
    ready: function(selector, fn) {
        // Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn
        });
        if (!observer) {
            // Watch for changes in the document
            observer = new MutationObserver(DomObserver.check);
            observer.observe(doc.documentElement, {
                childList: true,
                subtree: true
            });
        }
        // Check if the element is currently in the DOM
        DomObserver.check();
    },
    check: function() {
        // Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
            // Query for elements matching the specified selector
            elements = doc.querySelectorAll(listener.selector);
            for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                element = elements[j];
                // Make sure the callback isn't invoked with the 
                // same element more than once
                if (!element.ready) {
                    element.ready = true;
                    // Invoke the callback with the element
                    listener.fn.call(element, element);
                }
            }
        }
    }
}

DomObserver.ready('.embeddedServiceHelpButton', function() {
    checkChatButton();
});

function checkChatButton() {
    // Prod: https://care.hallmark.com/services/apexrest/CheckBusinessHoursService?businessHoursName=Care%20Business%20Hours
    // Dev: /HallmarkCare/services/apexrest/CheckBusinessHoursService?businessHoursName=Care%20Business%20Hours
    $.get('https://care.hallmark.com/services/apexrest/CheckBusinessHoursService?businessHoursName=Care%20Business%20Hours')
    .done(function(data) {
        console.log(data);

        if (!data.withinHours) {
            $('.embeddedServiceHelpButton').hide();
        }
    }).fail(function(error) {
        console.error(error);
    });
}