﻿<!DOCTYPE html>
<html lang="en">

<head>
    <title></title>
    <meta charset="utf-8">
    <!--<meta http-equiv="X-UA-Compatible" content="IE=edge;" />-->

    <style>
        #cleft, #cright, #left, #right, header ul {
            float: left;
        }

            #comments time, #right li, header li {
                display: inline;
            }

        html {
            overflow-y: scroll;
        }

        body {
            margin: 0;
        }

        h1, h2, h3, h4, p {
            margin: 0;
            padding: 0;
            font-weight: 400;
            font-family: Georgia,"Times New Roman",serif;
        }

        #main {
            padding: 20px;
        }

        .wrap {
            /*margin: auto;*/
            width: 100%;
            /*border-bottom: 2px solid #203;*/
        }

        #left h2, #left h3, #left h4 {
            margin-top: 20px;
            margin-bottom: 10px;
        }

        .clear {
            clear: both;
        }

        .unicode {
            font-family: Code2000,Sun-ExtA,'Arial Unicode MS',NSimSun,sans-serif;
        }

        a {
            color: #c00;
            font-weight: 700;
            text-decoration: none;
        }

        img {
            border: 0;
        }

        a:hover {
            text-decoration: underline;
        }

        #left {
            width: 100%;
            /*visibility:hidden;*/
        }

            #left p {
                font-family: Georgia,"Times New Roman",serif;
                font-size: 16px;
                line-height: 1.5em;
                margin-bottom: 8px;
                text-align: justify;
            }

            #left .button, header a {
                font-family: Arial,Tahoma,Verdana;
            }

            #left h1 a, #left h2 a {
                color: #000;
            }

            #left h1 {
                font-size: 30px;
                margin-top: 20px;
            }

            #left h2 {
                font-size: 28px;
            }

            #left h3 {
                font-size: 26px;
            }

            #left h4 {
                font-size: 24px;
            }

            #left img {
                padding: 10px;
                border: 1px solid #ccc;
            }

            #left .button a, #left pre {
                color: #fff;
                -webkit-border-radius: 8px;
                font-size: 13px;
            }

            #left li {
                list-style-type: square;
            }

            #left pre {
                background: #211;
                -moz-border-radius: 8px;
                border-radius: 8px;
                padding: 10px 20px;
            }

            #left .button {
                text-align: center;
                margin: 30px;
            }

        #right, header li {
            margin-left: 20px;
        }

        #left .button a {
            padding: 10px 30px;
            text-decoration: none;
            -moz-border-radius: 8px;
            border-radius: 8px;
            -webkit-box-shadow: 0 1px 3px #666;
            -moz-box-shadow: 0 1px 3px #666;
            text-shadow: 0 1px 3px #666;
            border: 2px solid #c00;
            background: #c00;
            background: -webkit-gradient(linear,0 0,0 100%,from(red),to(#811));
            background: -moz-linear-gradient(top,red,#811);
        }

        #left time {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
            margin-top: 3px;
            display: block;
        }

            #left time a {
                color: #000;
            }

        #right {
            width: 25%;
        }

            #right ul {
                list-style: none;
                padding: 0;
                margin: 0;
            }

            #right li {
                margin-left: 5px;
            }

        header a {
            font-weight: 300;
            font-size: 30px;
            color: #333;
        }

        header > div {
            position: relative;
        }


        header ul {
            list-style: none;
            margin-left: 140px;
            margin-top: 60px;
        }

        header li a {
            font-size: 19px;
        }

        footer div {
            height: 65px;
            font-size: 14px;
            padding-top: 10px;
            font-family: Arial,Tahoma,Verdana;
        }

        #cleft {
            width: 60px;
        }

        #cright {
            width: 500px;
        }

        textarea {
            resize: vertical;
            width: 500px;
        }

        input {
            width: 100px;
            padding: 4px;
        }

        form p {
            margin-top: 5px;
        }

        form .button {
            text-align: left!important;
            margin: 5px 0 0!important;
        }

            form .button a {
                padding: 5px 10px!important;
                font-size: 13px!important;
            }

        #comments img {
            border: 0;
            padding: 0;
        }

        #comments h3, form h3 {
            font-size: 23px;
            margin-top: 40px;
        }

        #comments .comments {
            margin-top: 30px;
        }

        #comments time {
            padding: 0;
            margin: 0;
        }

        code .str, pre .str {
            color: #65B042;
        }

        code .kwd, pre .kwd {
            color: #E28964;
        }

        code .com, pre .com {
            color: #AEAEAE;
            font-style: italic;
        }

        code .typ, pre .typ {
            color: #89bdff;
        }

        code .lit, pre .lit {
            color: #3387CC;
        }

        code .pln, code .pun, pre .pln, pre .pun {
            color: #fff;
        }

        code .tag, pre .tag {
            color: #89bdff;
        }

        code .atn, pre .atn {
            color: #bdb76b;
        }

        code .atv, pre .atv {
            color: #65B042;
        }

        code .dec, pre .dec {
            color: #3387CC;
        }

        code.prettyprint, pre.prettyprint {
            background-color: #000;
            -moz-border-radius: 8px;
            -webkit-border-radius: 8px;
            -o-border-radius: 8px;
            -ms-border-radius: 8px;
            -khtml-border-radius: 8px;
            border-radius: 8px;
        }

        pre.prettyprint {
            width: 95%;
            margin: 1em auto;
            padding: 1em;
            white-space: pre-wrap;
        }

        #webcam, #canvas {
            width: 500px;
            height: 380px;
            /*border: 20px solid #333;*/
            background: #9e9e9e;
            /*-webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    border-radius: 20px;*/
        }

        #webcam {
            position: relative;
            margin-top: 50px;
            margin-bottom: 50px;
        }

            #webcam > span {
                z-index: 2;
                position: absolute;
                color: #eee;
                font-size: 10px;
                bottom: -16px;
                left: 152px;
            }

            #webcam > img {
                z-index: 1;
                position: absolute;
                border: 0px none;
                padding: 0px;
                bottom: -40px;
                left: 89px;
            }

            #webcam > div {
                border: 5px solid #333;
                position: absolute;
                right: -90px;
                padding: 5px;
                -webkit-border-radius: 8px;
                -moz-border-radius: 8px;
                border-radius: 8px;
                cursor: pointer;
            }

            #webcam a {
                background: #fff;
                font-weight: bold;
            }

                #webcam a > img {
                    border: 0px none;
                }

        #canvas {
            /*border: 20px solid #ccc;*/
            background: #9e9e9e;
        }

        #flash {
            position: absolute;
            top: 0px;
            left: 0px;
            z-index: 5000;
            width: 100%;
            height: 500px;
            background-color: #c00;
            display: none;
        }

        object {
            display: block; /* HTML5 fix */
            position: relative;
            z-index: 1000;
        }

        .booth {
            width: 100%;
            height: 400px;
        }

        #videoElement {
            width: 500px;
            height: 420px;
            background-color: #9e9e9e;
        }

        #button {
            color: #9966FF;
            font-size: 10%;
            width: 135px;
            height: 60px;
            border: none;
            margin: 0;
            padding: 0;
            background: #0c0 url(image) 0 0 no-repeat;
        }
        /*#gum {
visibility:hidden;
}*/

        #canvasGUM {
            background-color: #9e9e9e;
        }

        #cams {
            background-color: #9e9e9e;
        }
    </style>

    <script type="text/javascript" src="../../../ClientGlobalContext.js.aspx"></script>
    <script type="text/javascript" src="/WebResources/mtccp_/CrmPictures/javascripts/jquery"></script>
    <!--<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>-->
   <!-- <script type="text/javascript" src="../../../WebResources/mtcic_/Javascripts/XrmSvcToolkit.js"></script>-->
    <script type="text/javascript" src="/WebResources/mtccp_/CrmPictures/javascripts/xrmsvctoolkit"></script>
    <script type="text/javascript" src="/WebResources/mtccp_/CrmPictures/javascripts/prettify.js"></script>  
    <script>
        window.onload = function () {
            (function () {
                debugger;
                window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
               navigator.getUserMedia = navigator.getUserMedia ||
                                    navigator.webkitGetUserMedia ||
                                    navigator.mozGetUserMedia ||
                                    navigator.msGetUserMedia;

                if (navigator.getUserMedia) {
                    $("#gum").show();
                    $("#left").hide();
                    navigator.getUserMedia({ video: true }, function (stream) {
                        videoElement.src = window.URL.createObjectURL(stream);
                        videoElement.play();
                    }, function (error) {
                        Xrm.Utility.alertDialog("Camera Not Found");
                        document.getElementById("btnCapture").disabled = true;
                        document.getElementById("btnSaveImg").disabled = true;
                    });
                }
                else {
                    $("#gum").hide();
                    $("#left").show();
                    prettyPrint();
                }
            })();
        }

        function capture() {
            video = document.getElementById('videoElement');
            canvas = document.getElementById('canvasGUM');
            var context = canvas.getContext('2d');
            context.drawImage(video, 0, 0, 500, 420);
            var data = canvas.toDataURL('image/png');
        }
        var base64Image = "";
        function saveImage() {
            var formType = contentWindow505[1].split("=")[1];
            if (typeof navigator.getUserMedia !== "undefined") {
                video = document.getElementById('videoElement');
                canvas = document.getElementById('canvasGUM');
            } else {
                canvas = document.getElementById('canvas');
            }
            var ctx = canvas.getContext("2d");
            if (typeof ctx !== "undefined" && ctx !== null) {
                ctx.drawImage(canvas, 0, 0);
                var dataURL = canvas.toDataURL("image/png");
                var base64Image = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
            } else {
                Xrm.Utility.alertDialog("Please capture image");
                return;
            }
            if (formType === 1) {
                Xrm.Utility.alertDialog("Please save the record and then capture image");
            } else {
                debugger;
                var RecId = contentWindow505[0].split("=")[1];
                // RecId = RecId.split("{")[1].split("}")[0];
                RecId = RecId.replace("'", "").replace("'", "");
                var entityName = contentWindow505[2].split("=")[1];
                entityName = entityName.replace("'", "").replace("'", "");
                if (entityName.endsWith('s')) {
                    entityName = entityName + "es";
                } else {
                    entityName = entityName + "s";
                }
                var xhr = new XMLHttpRequest();
                xhr.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + entityName + "(" + RecId + ")", false);
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                xhr.setRequestHeader("OData-MaxVersion", "4.0");
                xhr.setRequestHeader("OData-Version", "4.0");
                xhr.onreadystatechange = function () {
                    if (this.readyState == 4) {
                        xhr.onreadystatechange = null;
                        if (this.status == 204) {
                            //parent.window.opener.location.reload();
                            //if (Mscrm.Utilities.isChrome()) {
                                callback();
                          // }
                            closeWindow(true);
                            
                        }
                        else {
                            var error = JSON.parse(this.response).error;
                            //show error
                            Xrm.Utility.alertDialog(error.message);
                        }
                    }
                };
                var entity = {};
                entity.entityimage = base64Image;
                var body = JSON.stringify(entity);

                xhr.send(body);
                //XrmSvcToolkit.updateRecord({
                //    entityName: "Contact",
                //    id: RecId,
                //    entity: { EntityImage: base64Image },
                //    async: false,
                //    successCallback: function (result) {
                //        window.opener.location.reload();
                //        closeWindow(true);
                //    },
                //    errorCallback: function (error) {
                //        Xrm.Utility.alertDialog(error.message);
                //    }
                //});
            }
        }

        function parseDataValue(datavalue) {
            if (datavalue != "") {
                var vals = new Array();
                vals = decodeURIComponent(datavalue).split("&");
                return vals;
            }
        }

        function getDataParam() {
            //Get the any query string parameters and load them
            //into the vals array
            var values = null;
            var vals = new Array();
            if (location.search != "") {
                vals = location.search.substr(1).split("&");
                for (var i in vals) {
                    vals[i] = vals[i].replace(/\+/g, " ").split("=");
                }
                //look for the parameter named 'data'
                var found = false;
                for (var i in vals) {
                    if (vals[i][0].toLowerCase() == "data") {
                        values = parseDataValue(vals[i][1]);
                        found = true;
                        break;
                    }
                }
                if (!found)
                { noParams(); }
            }
            else {
                noParams();
            }
            return values;
        }

        function previewOnClick() {
            var context = canvas.getContext('2d');
            context.drawImage(video, 0, 0, 500, 420);
            var data = canvas.toDataURL('image/png');
        }
    </script>

</head>

<body>
    <div id="main">
        <div class="wrap">
            <h2>CRM Image Capture</h2>
            <div id="left">
                <article>
                    <script type="text/javascript" src="/WebResources/mtccp_/CrmPictures/javascripts/jquerywebcam.min.js"></script>
                    <table style="width: 100%;" cellpadding="3" cellspacing="0">

                        <tr>
                            <td>
                                <p id="status" style="color: #c00; font-weight: bold;"></p>
                                <div id="webcam"></div>
                                <div style="width: 360px; text-align: center; font-size: 12px">
                                    <a href="javascript:webcam.capture();changeFilter();void(0);">Capture Image</a>
                                    <button onclick="saveImage();">Save Image</button>
                                </div>
                            </td>
                            <td>
                                <div>
                                    <!--style="float: left; margin-top: 5px;"-->
                                    <canvas id="canvas" height="240" width="320"></canvas>
                                </div>
                                <ul id="cams"></ul>
                            </td>
                        </tr>
                    </table>
                    <script type="text/javascript">
                        //parent.$(parent.parent.document).find("#crmContentPanel").find("iframe").filter(function (index) { return parent.$(this).css("visibility") == "visible" })[0].contentWindow
                        var contentWindow505 = getDataParam();
                        var pos = 0;
                        var ctx = null;
                        var cam = null;
                        var image = null;

                        var filter_on = false;
                        var filter_id = 0;

                        function changeFilter() {
                            if (filter_on) {
                                filter_id = (filter_id + 1) & 7;
                            }
                        }

                        function toggleFilter(obj) {
                            if (filter_on = !filter_on) {
                                obj.parentNode.style.borderColor = "#c00";
                            } else {
                                obj.parentNode.style.borderColor = "#333";
                            }
                        }
                        jQuery("#webcam").webcam({
                            width: 500,
                            height: 380,
                            mode: "callback",
                            swffile: "/WebResources/mtccp_/CrmPictures/Html/jscam_canvas_only.html",// "/WebResources/mtcic_/HTML/jscam_canvas_only.html",
                            onTick: function (remain) {
                                if (remain == 0) {
                                    jQuery("#status").text("Cheese!");
                                } else {
                                    jQuery("#status").text(remain + " seconds remaining...");
                                }
                            },
                            onSave: function (data) {
                                var col = data.split(";");
                                var img = image;
                                if (false == filter_on) {
                                    for (var i = 0; i < 320; i++) {
                                        var tmp = parseInt(col[i]);
                                        img.data[pos + 0] = (tmp >> 16) & 0xff;
                                        img.data[pos + 1] = (tmp >> 8) & 0xff;
                                        img.data[pos + 2] = tmp & 0xff;
                                        img.data[pos + 3] = 0xff;
                                        pos += 4;
                                    }

                                } else {

                                    var id = filter_id;
                                    var r, g, b;
                                    var r1 = Math.floor(Math.random() * 255);
                                    var r2 = Math.floor(Math.random() * 255);
                                    var r3 = Math.floor(Math.random() * 255);

                                    for (var i = 0; i < 320; i++) {
                                        var tmp = parseInt(col[i]);

                                        /* Copied some xcolor methods here to be faster than calling all methods inside of xcolor and to not serve complete library with every req */

                                        if (id == 0) {
                                            r = (tmp >> 16) & 0xff;
                                            g = 0xff;
                                            b = 0xff;
                                        } else if (id == 1) {
                                            r = 0xff;
                                            g = (tmp >> 8) & 0xff;
                                            b = 0xff;
                                        } else if (id == 2) {
                                            r = 0xff;
                                            g = 0xff;
                                            b = tmp & 0xff;
                                        } else if (id == 3) {
                                            r = 0xff ^ ((tmp >> 16) & 0xff);
                                            g = 0xff ^ ((tmp >> 8) & 0xff);
                                            b = 0xff ^ (tmp & 0xff);
                                        } else if (id == 4) {

                                            r = (tmp >> 16) & 0xff;
                                            g = (tmp >> 8) & 0xff;
                                            b = tmp & 0xff;
                                            var v = Math.min(Math.floor(.35 + 13 * (r + g + b) / 60), 255);
                                            r = v;
                                            g = v;
                                            b = v;
                                        } else if (id == 5) {
                                            r = (tmp >> 16) & 0xff;
                                            g = (tmp >> 8) & 0xff;
                                            b = tmp & 0xff;
                                            if ((r += 32) < 0) r = 0;
                                            if ((g += 32) < 0) g = 0;
                                            if ((b += 32) < 0) b = 0;
                                        } else if (id == 6) {
                                            r = (tmp >> 16) & 0xff;
                                            g = (tmp >> 8) & 0xff;
                                            b = tmp & 0xff;
                                            if ((r -= 32) < 0) r = 0;
                                            if ((g -= 32) < 0) g = 0;
                                            if ((b -= 32) < 0) b = 0;
                                        } else if (id == 7) {
                                            r = (tmp >> 16) & 0xff;
                                            g = (tmp >> 8) & 0xff;
                                            b = tmp & 0xff;
                                            r = Math.floor(r / 255 * r1);
                                            g = Math.floor(g / 255 * r2);
                                            b = Math.floor(b / 255 * r3);
                                        }

                                        img.data[pos + 0] = r;
                                        img.data[pos + 1] = g;
                                        img.data[pos + 2] = b;
                                        img.data[pos + 3] = 0xff;
                                        pos += 4;
                                    }
                                }

                                if (pos >= 0x4B000) {
                                    ctx.putImageData(img, 0, 0);
                                    pos = 0;
                                }
                            },
                            onCapture: function () {
                                webcam.save();
                                jQuery("#flash").css("display", "block");
                                jQuery("#flash").fadeOut(100, function () {
                                    jQuery("#flash").css("opacity", 1);
                                });
                            },
                            debug: function (type, string) {
                                if (string === "Flash movie not yet registered!") {
                                    string = string + " <a href='https://get.adobe.com/flashplayer/'>ClickHere</a>" + " Flash Player"
                                }
                                jQuery("#status").html(type + ": " + string);
                            },
                            onLoad: function () {
                                var cams = webcam.getCameraList();
                            }
                        });
                        function getPageSize() {
                            var xScroll, yScroll;
                            if (window.innerHeight && window.scrollMaxY) {
                                xScroll = window.innerWidth + window.scrollMaxX;
                                yScroll = window.innerHeight + window.scrollMaxY;
                            } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
                                xScroll = document.body.scrollWidth;
                                yScroll = document.body.scrollHeight;
                            } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                                xScroll = document.body.offsetWidth;
                                yScroll = document.body.offsetHeight;
                            }

                            var windowWidth, windowHeight;

                            if (self.innerHeight) { // all except Explorer
                                if (document.documentElement.clientWidth) {
                                    windowWidth = document.documentElement.clientWidth;
                                } else {
                                    windowWidth = self.innerWidth;
                                }
                                windowHeight = self.innerHeight;
                            } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                                windowWidth = document.documentElement.clientWidth;
                                windowHeight = document.documentElement.clientHeight;
                            } else if (document.body) { // other Explorers
                                windowWidth = document.body.clientWidth;
                                windowHeight = document.body.clientHeight;
                            }
                            // for small pages with total height less then height of the viewport
                            if (yScroll < windowHeight) {
                                pageHeight = windowHeight;
                            } else {
                                pageHeight = yScroll;
                            }
                            // for small pages with total width less then width of the viewport
                            if (xScroll < windowWidth) {
                                pageWidth = xScroll;
                            } else {
                                pageWidth = windowWidth;
                            }

                            return [pageWidth, pageHeight];
                        }

                        window.addEventListener("load", function () {

                            jQuery("body").append("<div id=\"flash\"></div>");

                            var canvas = document.getElementById("canvas");

                            if (canvas.getContext) {
                                ctx = document.getElementById("canvas").getContext("2d");
                                ctx.clearRect(0, 0, 320, 240);

                                var img = new Image();
                                img.src = "/image/logo.gif";
                                img.onload = function () {
                                    ctx.drawImage(img, 129, 89);
                                }
                                image = ctx.getImageData(0, 0, 320, 240);
                            }

                            var pageSize = getPageSize();
                            jQuery("#flash").css({ height: pageSize[1] + "px" });

                        }, false);

                        window.addEventListener("resize", function () {
                            var pageSize = getPageSize();
                            jQuery("#flash").css({ height: pageSize[1] + "px" });

                        }, false);

                    </script>
                </article>
            </div>

            <div id="gum" class="booth">
                <table style="width: 100%; table-layout: fixed;" cellpadding="3" cellspacing="0">
                    <tbody>
                        <tr>
                            <td style="text-align: center;">
                                <video id="videoElement"></video>
                            </td>
                            <td style="text-align: center;">
                                <canvas width="500" height="420" id="canvasGUM"></canvas>
                            </td>

                        </tr>
                        <tr>
                            <td style="text-align: center;">
                                <input id="btnCapture" onclick="capture(); void (0);" type="button" value="Capture Image" />
                            </td>
                            <td style="text-align: center;">
                                <label id="labPreview">Preview</label>

                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td style="text-align: right; padding-right: 7%;">
                                <input id="btnSaveImg" onclick="saveImage()" type="button" value="Save image" />
                            </td>
                        </tr>
                    </tbody>
                </table>

            </div>
        </div>
    </div>

</body>

</html>
