﻿<html>
<head>
    <title>Record Clone (IOTAP)</title>
    <script src="ClientGlobalContext.js.aspx" type="text/javascript"></script>
    <script src="iotap_clonejson2.js" type="text/javascript"></script>
    <script src="iotap_clonejquery1.7.1.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">

        var entityRecordID = "";
        var entityName = "";
        var noOfClone = "";
        var oDataPath = "";
        ///////*************Loading window Start **************///////
        window.onload = function () {
            Form_onload();
            $('#loadingDiv').css('display', 'block');
            getDataParam();
            setTimeout(createClone, 500);

        }

        /*
        * Set clone message window on page. Invoke ConfigureAjaxLoading method for clone message with predefined style.
        */
        function Form_onload() {
            jQuery.fn.center = function () {
                this.css("position", "absolute");
                this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
                this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
                return this;
            }
            ConfigureAjaxLoading('Cloning in progress, Please wait');
        }

        /*
        * Show clone message.        
        */
        function ConfigureAjaxLoading(text, otherText) {
            $('BODY').append('<div id="loadingDiv" style="z-index:100; top:0; left:10px;top:10px;vertical-align:center;align:middle"></div>');
            $('#loadingDiv').append('<p id="loadingText">' + text + '</p>')
                                                  .css('background', 'url(/_imgs/AdvFind/progress.gif) no-repeat center')
                                                  .css('background-color', '#e2e6eb')
                                                  .css('height', '100%')
                                                  .css('width', '100%')
                                                  .css('vertical-align', 'middle').css('display', 'none')
                                        .center();

            $('#loadingText').css('text-align', 'center')
                                                  .css('font', '18px bolder')
                                                  .css('font-family', 'Segoe UI, Tahoma, Arial');
        }


        /*
        * Generate odata url.        
        * @returns odata url to invoked method.
        */
        function getODataPath() {

            if (typeof Xrm.Page.context.getClientUrl !== 'function') {
                serverUrl = Xrm.Page.context.getServerUrl();
            }
            else {
                serverUrl = Xrm.Page.context.getClientUrl();
            }
            var lastChar = serverUrl.charAt(serverUrl.length - 1);
            if (lastChar != "/")
                serverUrl += "/";

            var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
            return serverUrl + ODATA_ENDPOINT;

        }

        /*
        * Creates a clone request & open the cloned record if single record was cloned.
        */
        function createClone() {

            var objClone = new Object();
            objClone.iotap_entityschemaname = entityName;
            objClone.iotap_noofclone = noOfClone;
            objClone.iotap_entityid = entityRecordID;

            var jsonEntity = window.JSON.stringify(objClone);
            oDataPath = getODataPath();

            var createRecordReq = new XMLHttpRequest();
            var odataSetName = "iotap_cloneSet";
            createRecordReq.open('POST', oDataPath + "/" + odataSetName, false);
            createRecordReq.setRequestHeader("Accept", "application/json");
            createRecordReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            createRecordReq.send(jsonEntity);

            var newRecord = JSON.parse(createRecordReq.responseText).d;

            if (typeof newRecord != "object") {
                alert(JSON.parse(createRecordReq.responseText).error.message.value);
            }
            else {
                if (noOfClone == 1 && entityRecordID.length < 38) {
                    openClonnedRecord(newRecord.iotap_cloneId);
                }
            }

            window.close();
        }

        /*
        * Open cloned record by data retrieve from odata request.
        * @newRecordId Cloned record id        
        */
        function openClonnedRecord(newRecordId) {
            var retrieveReq = new XMLHttpRequest();
            oDataPath = getODataPath();
            var odataUri = oDataPath + "/iotap_cloneSet?$select=iotap_clonnedrecordid&$filter=iotap_cloneId eq guid'" + newRecordId + "'";
            retrieveReq.open("GET", odataUri, false);
            retrieveReq.setRequestHeader("Accept", "application/json");
            retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            retrieveReq.send();
            var result = jQuery.parseJSON(retrieveReq.responseText).d;
            var clonnedRecordId = result.results[0].iotap_clonnedrecordid;
            Xrm.Utility.openEntityForm(entityName, clonnedRecordId);
        }

        /*
        * Get the query string parameters        
        */
        function getDataParam() {
            //Get the any query string parameters and load them //into the vals array
            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") {
                        parseDataValue(vals[i][1]);
                        found = true;
                        break;
                    }
                }
                if (!found)
                { noParams(); }
            }
            else {
                noParams();
            }

        }

        /*
        * Parse query string parameters
        * @datavalue string parameter value from querystring after data key.
        */
        function parseDataValue(datavalue) {
            if (datavalue != "") {
                var vals = new Array();
                var message = document.createElement("p");
                message.innerText = "These are the data parameters values that were passed to this page:";
                vals = decodeURIComponent(datavalue).split("&");
                for (var i in vals) {
                    vals[i] = vals[i].replace(/\+/g, " ").split("=");
                }
                for (var i in vals) {

                    if (vals[0][0] != null)
                        entityName = vals[0][0];
                    if (vals[1][0] != null)
                        entityRecordID = vals[1][0];
                    if (vals[2][0] != null)
                        noOfClone = vals[2][0];
                }
                entityRecordID = entityRecordID.replace(new RegExp('%7b', 'g'), '');
                entityRecordID = entityRecordID.replace(new RegExp('%7d', 'g'), '');
                entityRecordID = entityRecordID.replace(new RegExp('{', 'g'), '');
                entityRecordID = entityRecordID.replace(new RegExp('}', 'g'), '');
            }
            else {
                noParams();
            }
        }

        /*
        * Display "No Params found" message if querystring paramter is empty
        */
        function noParams() {
            document.clear();
            var message = document.createElement("p");

            setText(message, "No data parameter was passed to this page");
            document.body.appendChild(message);
        }
        //////*************Loading window End **************///////
    </script>
</head>
<body id="BODY" style="padding-bottom: 0px; background-color: #f6f8fa; margin: 0px; padding-left: 0px; width: 100%; padding-right: 0px; padding-top: 0px">
</body>
</html>
