<html>
<head>
<title>Beacon Sample: Attach Note With File</title>
    <script>
        var maxFileSize = 5000000; // Maximum file size, in bytes.
        var beaconUrl = "https://data2011.peak15systems.com/beacon2011/service.svc/insert/entity/annotation";


        // This reads the file from the "file" input. If there is a file read, form fields are filled out.
        function readFile(event) {
            var fileElement = document.getElementById("file");

            if (fileElement.files && fileElement.files.length > 0) {
                var f = fileElement.files[0];
                // Validate File Size
                if (f.size > maxFileSize) {
                    alert('Error: File size (' + f.size + ') exceeds max file size (' + maxFileSize + ').');
                } else {
                    // Load File Information
                    var FR = new FileReader();
                    FR.onload = function (e) {
                        document.getElementById("mimetype").value = f.type; // Get mime type of selected file
                        document.getElementById("FileName").value = f.name; // Get name of selected file
                        document.getElementById("documentbody").innerHTML = e.target.result.split(',')[1]; // Get only the base 64 encoded file string
                        document.getElementById("isencoded").value = "true"; // We are submitting an encoded string

                        checkFileLoaded();
                    };
                    FR.readAsDataURL(fileElement.files[0]);
                }
            }
        }

        function updateStatus(statusText) {
            var statusDiv = document.getElementById("statusDiv");
            if (statusDiv != null && statusText != null) {
                statusDiv.innerHTML = statusText;
            }
        }

        // This makes one huge string to call from ajax.
        function submitNote() {
            updateStatus('Submitted.');

            // Create the ajax params
            var beaconServer = "";
            beaconServer += "token=" + document.getElementById("token").value;
            beaconServer += "&isencoded=" + document.getElementById("isencoded").value;
            beaconServer += "&objectid=" + document.getElementById("objectid").value;
            beaconServer += "&subject=" + document.getElementById("subject").value;
            beaconServer += "&notetext=" + document.getElementById("notetext").value;
            beaconServer += "&objecttypecode=" + document.getElementById("objecttypecode").value;
            beaconServer += "&mimetype=" + document.getElementById("mimetype").value;
            beaconServer += "&FileName=" + document.getElementById("FileName").value;
            beaconServer += "&documentbody=" + encodeURIComponent(document.getElementById("documentbody").innerHTML); // NOTE: we encode the base64 string because '+' get stripped out, which will make crm blow up.

            // Now do the call
            var http = new XMLHttpRequest();
            http.open("POST", beaconUrl, true);

            //Send the proper header information along with the request
            http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            http.setRequestHeader("Content-length", beaconServer.length);
            http.setRequestHeader("Connection", "close");

            http.onreadystatechange = function () {//Call a function when the state changes.
                var status = 'Received ' + http.responseText + ' response: ' + http.readyState + ' ' + http.status;
                updateStatus(status);
            }
            http.send(beaconServer);
            updateStatus('Request Sent.');
        }

        // File not loaded
        function checkFileLoaded() {
            var documentBody = document.getElementById("documentbody").innerHTML;

            var loaded = (documentBody != null && documentBody.length > 0) ? "(File Loaded)" : "(File Not Loaded)";
            document.getElementById("filestatus").innerHTML = loaded;
            document.getElementById("submitButton").disabled = (documentBody != null && documentBody.length <= 0);
        }

        // Window Onload Events
        function startFunction() {
            var fileElement = document.getElementById("file");
            var submitButtonElement = document.getElementById("submitButton");
            if (fileElement.addEventListener) {
                fileElement.addEventListener("change", readFile, false);
            } else if (fileElement.attachEvent) {
                fileElement.attachEvent("onchange", readFile);
            }
            if (submitButtonElement.addEventListener) {
                submitButtonElement.addEventListener("click", submitNote, false);
            } else if (submitButtonElement.attachEvent) {
                submitButtonElement.attachEvent("onclick", submitNote);
            }
            checkFileLoaded();
        }
        window.onload = startFunction;
    </script>
</head>
    <body>
        <div>This page creates an annotation via AJAX.</div>
        <div>Status:</div>
        <div id="statusDiv">-</div>
        <br />
        File
        <input type="file" name="file" id="file" />
        <br/>
        Encoded File
        <div id="filestatus"></div>
        <br/>
        Is Encoded
        <input type="text" name="isencoded" id="isencoded" value="false" />
        <br/>
        Token
        <input type="text" name="token" id="token" />
        <br />
        Object Id
        <input type="text" name="objectid" id="objectid" maxlength="50" />
        <br />
        Subject
        <input type="text" name="subject" id="subject" maxlength="50" />
        <br />
        Note Text
        <input type="text" name="notetext" id="notetext" maxlength="50"/>
        <br />
        Object Type Code
        <input type="text" name="objecttypecode" id ="objecttypecode" maxlength="50" value="contact"/>
        <br />
        Mime Type
        <input type="text" name="mimetype" id="mimetype" maxlength="50"/>
        <br />
        File Name
        <input type="text" name="FileName" id="FileName" maxlength="50"/>
        <br />
        <input type="button" id="submitButton" name="submitButton" value="Submit" />

        <div id="documentbody" style="visibility:hidden;display:none"></div>
    </body>
</html>