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()
        {
            hideElementById('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;
    }
    // Remove harmful characters from the message
    // Fix defect #122.   
    function sanitize(text)
    {
        return text.replace(/[;:,"]/gi, ""); 
    }
    function handleCMSsubmit()
    {
        // recover the user's response
        var response1 = sanitize(document.getElementById('msgcontent1').value.trim());
        var response2 = sanitize(document.getElementById('msgcontent2').value.trim());
        var response3 = sanitize(document.getElementById('msgcontent3').value.trim());
        var response4 = sanitize(document.getElementById('msgcontent4').value.trim());
        var response5 = sanitize(document.getElementById('msgcontent5').value.trim());
        var response6 = sanitize(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 = justifyCMStext(response1);
            document.getElementById('msgdisplay2').value = justifyCMStext(response2);
            document.getElementById('msgdisplay3').value = justifyCMStext(response3);
            document.getElementById('msgdisplay4').value = justifyCMStext(response4);
            document.getElementById('msgdisplay5').value = justifyCMStext(response5);
            document.getElementById('msgdisplay6').value = justifyCMStext(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;
        msgParts = outMessage.split("|");
        CMSmessageDict[cmsID].cms.message.phase1.Line1 = msgParts[0];
        CMSmessageDict[cmsID].cms.message.phase1.Line2 = msgParts[1];
        CMSmessageDict[cmsID].cms.message.phase1.Line3 = msgParts[2];
        CMSmessageDict[cmsID].cms.message.phase2.Line1 = msgParts[3];
        CMSmessageDict[cmsID].cms.message.phase2.Line2 = msgParts[4];
        CMSmessageDict[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);
        // Examine each message in the dict and convert to json format
        var lineOut = "";
        for (var id in CMSmessageDict)
        {
            // convert and append to output string
            lineOut += JSON.stringify(CMSmessageDict[id]) + ',\n';
        }
        // remove trailing comma
        lineOut = lineOut.substring(0,lineOut.length-2);
        outString = "{\"data\":[\n" + lineOut + "\n]}";

        // Using POST to send the data 
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "../cgi-bin/saveCMSmessage.py", true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        // send the collected data as JSON
        xhr.send("msg="+outString);
    }

    // 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 = CMSmessageDict[cmsID].cms.message;
        // show the message in the display
        document.getElementById('msgdisplay1').value = justifyCMStext(message.phase1.Line1);
        document.getElementById('msgdisplay2').value = justifyCMStext(message.phase1.Line2);
        document.getElementById('msgdisplay3').value = justifyCMStext(message.phase1.Line3);
        document.getElementById('msgdisplay4').value = justifyCMStext(message.phase2.Line1);
        document.getElementById('msgdisplay5').value = justifyCMStext(message.phase2.Line2);
        document.getElementById('msgdisplay6').value = justifyCMStext(message.phase2.Line3);
    }
    function loadAllcmsMessages()
    {
        loadJSON("../dynamicdata/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];
                CMSmessageDict[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})
                }
            }
        });
    }


