function initCMSbutton()
{
    var cmsBtnDiv = document.getElementById('cmsButton');
    map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(cmsBtnDiv)
    cmsBtnDiv.title = 'Click to toggle cms view';
    // Setup the click event listeners to toggle icon display
    cmsBtnDiv.addEventListener('click', function()
    {
        cms_showing = !cms_showing;
        // Determine which button image to show
        if (cms_showing)
        {
            pic = "images/btnDepressed_CMS.png"
            // It's nice when icons become visible that the messages have been refreshed.
            loadAllcmsMessages();
        }
        else
        {
            pic = "images/btnReady_CMS.png"
        }
        document.getElementById('cmsBtnImg').src = pic;
        // reveal or hide all the icons
        cmsLayer.forEach(function(feature)
        {
            cmsLayer.overrideStyle(feature,
            {
                visible: cms_showing
            });
        });
    });
}
function loadCMSlayer()
{
    cmsLayer = new google.maps.Data();
    cmsLayer.setMap(map);
    cmsLayer.loadGeoJson(kCMSfile);
    // Define the clickable area on a CMS icon (the default is too big)
    var clickRegion = {coords: [0,0,18,15], type: "rect"}
    cmsLayer.setStyle(function(feature)
        {
            // return the StyleOptions
            return {
                icon: iconCMSidle,
                shape: clickRegion,
                title: feature.getId()+ " " +feature.getProperty("location")+ " " 
                        + feature.getProperty("street"),
                visible: false
            };
        });
    
    cmsLayer.addListener('click', function(event)
    {
        var dialog = document.getElementById('cms-dialog');
        // Note: If the dialog is already being displayed when someone else
        // updates the message, it won't be reflected in the dialog, until
        // you close and reopen it.
        dialog.style.display = 'block';
        cmsID = event.feature.getId();
        // Assign to the hidden field
        document.getElementById('cmsID').value = cmsID;
        showMessage(cmsID); // note: this is async
        document.getElementById('cms-info-label').innerHTML = "CMS ID: " +
            cmsID + "&nbsp;&nbsp;&nbsp;LOCATION: " + event.feature.getProperty("location")
            + "&nbsp;&nbsp;" + event.feature.getProperty("street");
        // clear input fields
        document.getElementById('msgcontent1').value = "";
        document.getElementById('msgcontent2').value = "";
        document.getElementById('msgcontent3').value = "";
        document.getElementById('msgcontent4').value = "";
        document.getElementById('msgcontent5').value = "";
        document.getElementById('msgcontent6').value = "";
        document.getElementById('msgcontent1').focus();
        var span = document.getElementById("cms-close");
            // When the user clicks on <span> (x), close the modal
        span.onclick = function()
        {
            handleDialogClose('cms-dialog');
        }
    });
}

    // Center justify message text in a 16 column field
    function justifyCMStext(message)
    {
        // don't bother justifying a blank message
        if (message.length == 0) return message;    
        // determine how much padding is needed
        var kBlanks = "                ";
        var padLen = (16 - message.length) / 2;
        // apply the padding
        var padding = kBlanks.substring(0, padLen);
        return padding + message;
    }

    function handleCMSsubmit()
    {
        // recover the user's response
        var response1 = justifyCMStext(document.getElementById('msgcontent1').value.trim());
        var response2 = justifyCMStext(document.getElementById('msgcontent2').value.trim());
        var response3 = justifyCMStext(document.getElementById('msgcontent3').value.trim());
        var response4 = justifyCMStext(document.getElementById('msgcontent4').value.trim());
        var response5 = justifyCMStext(document.getElementById('msgcontent5').value.trim());
        var response6 = justifyCMStext(document.getElementById('msgcontent6').value.trim());
        var newMsg = response1 + response2 + response3 + response4 + response5 + response6;
        if (newMsg.length == 0)
        {
            alert("Nothing to Send ... input fields are empty.");
        }
        else
        {
            document.getElementById('msgdisplay1').value = response1;
            document.getElementById('msgdisplay2').value = response2;
            document.getElementById('msgdisplay3').value = response3;
            document.getElementById('msgdisplay4').value = response4;
            document.getElementById('msgdisplay5').value = response5;
            document.getElementById('msgdisplay6').value = response6;
            saveCMSMessage(response1 + "|" + response2 + "|" + response3 + "|" +
                        response4 + "|" + response5 + "|" + response6);
        }
    }

    function handleCMSclear()
    {
        document.getElementById('msgdisplay1').value = "";
        document.getElementById('msgdisplay2').value = "";
        document.getElementById('msgdisplay3').value = "";
        document.getElementById('msgdisplay4').value = "";
        document.getElementById('msgdisplay5').value = "";
        document.getElementById('msgdisplay6').value = "";
        saveCMSMessage("|||||");
    }

    // Save an updated cms message to the file
    function saveCMSMessage(outMessage)
    {
        // Fetch cmsID from hidden field where it was put when dialog opened.
        var cmsID = document.getElementById('cmsID').value;
        //console.log("Saving " + outMessage + " for cmsID " + cmsID)
        msgParts = outMessage.split("|");
        messageDict[cmsID].cms.message.phase1.Line1 = msgParts[0];
        messageDict[cmsID].cms.message.phase1.Line2 = msgParts[1];
        messageDict[cmsID].cms.message.phase1.Line3 = msgParts[2];
        messageDict[cmsID].cms.message.phase2.Line1 = msgParts[3];
        messageDict[cmsID].cms.message.phase2.Line2 = msgParts[4];
        messageDict[cmsID].cms.message.phase2.Line3 = msgParts[5];
        // Check if there was any messages to save and
        // Set icon to reflect message state
        if (outMessage == "|||||")
        {
            currentIcon = {icon: iconCMSidle};
        }
        else
        {
            currentIcon = {icon: iconCMSactive};
        }
        cmsLayer.overrideStyle(cmsLayer.getFeatureById(cmsID), currentIcon)
        // break the json string into lines for readability
        jsonstring = JSON.stringify(Object.values(messageDict)); //Can't use these in GET parameter  ,null,4);
        outString = "{\"data\":" + jsonstring + "}";
        console.log("outString = " + outString);
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "cgi-bin/saveCMSmessage.py?msg=" + outString, true);
        xhttp.send();
        // Using POST might be a better idea ... haven't tried this yet
        //      var xhr = new XMLHttpRequest();
        //      xhr.open("POST", "/cgi-bin/saveCMSmessage.py?", true);
        //      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        // send the collected data as JSON
        //      xhr.send(JSON.stringify(messageList));
    }

    // retrieve the current cms message file
    function showMessage(cmsID)
    {
        loadAllcmsMessages();  // because someone else may have made a recent update
        // lookup the message for this cms ID
        var message = messageDict[cmsID].cms.message;
        // show the message in the display
        document.getElementById('msgdisplay1').value = message.phase1.Line1;
        document.getElementById('msgdisplay2').value = message.phase1.Line2;
        document.getElementById('msgdisplay3').value = message.phase1.Line3;
        document.getElementById('msgdisplay4').value = message.phase2.Line1;
        document.getElementById('msgdisplay5').value = message.phase2.Line2;
        document.getElementById('msgdisplay6').value = message.phase2.Line3;
    }
    function loadAllcmsMessages()
    {
        loadJSON("cms_messages.json", function(response)
        {
            // Parse JSON string into object
            messagejson = JSON.parse(response);
            // Add each message to a lookup dictionary 
            for (var i = 0; i < messagejson.data.length; i++)
            {
                var item = messagejson.data[i];
                messageDict[item.cms.index] = item;
                // Set the appropriate icon on the cms icon
                // set a yellow flag if there's currently no message
                if (item.cms.message.phase1.Line1 + 
                    item.cms.message.phase1.Line2 +
                    item.cms.message.phase1.Line3 +
                    item.cms.message.phase2.Line1 + 
                    item.cms.message.phase2.Line2 +
                    item.cms.message.phase2.Line3 == "")
                {
                    cmsLayer.overrideStyle(cmsLayer.getFeatureById(item.cms.index), {icon: iconCMSidle})
                }
                else
                {
                    cmsLayer.overrideStyle(cmsLayer.getFeatureById(item.cms.index), {icon: iconCMSactive})
                }
            }
        });
    }


