﻿<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <style type="text/css">
        .style1
        {
            font-family: "Segoe UI";
            text-align: left;
            font-size: large;
        }
        .label
        {
            font-family: "Segoe UI";
            font-size: 11px;
        }
        
        .selectlist
        {
            font-family: "Segoe UI";
            font-size: 11px;
            width: 260px;
            height: 260px;
        }
        .Button
        {
            font-family: "Segoe UI";
            font-size: 12px;
            text-align: center;
            width: 50px;
        }
        .crmbutton
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            height: 20px;
            padding-right: 5px;
            padding-left: 5px;
            border-top-width: 1px;
            border-right-width: 1px;
            border-bottom-width: 1px;
            border-left-width: 1px;
            border-top-style: solid;
            border-left-style: solid;
            border-bottom-style: solid;
            border-right-style: solid;
            cursor: pointer;
            background-repeat: repeat-x;
            border-bottom-color: #666666;
            border-top-color: #666666;
            border-left-color: #666666;
            border-right-color: #666666;
            background-image: url('iotap_ButtonNormalGradient.png');
        }
        .header
        {
            background-color: rgb(233, 237, 241);
            border-width: 1px;
            border-style: inherit;
            border-color: Aqua;
            padding: 0 0 0 0;
        }
        
        .errormsg
        {
            font-family: "Segoe UI";
            text-align: left;
            color: Red;
            font-size: 11px;
        }
        .msg
        {
            font-family: "Segoe UI";
            text-align: left;
            color: Black;
            font-size: 11px;
        }
    </style>
</head>
<script src="ClientGlobalContext.js.aspx"></script>
<script type="text/javascript" language="javascript">
<!--  REST -->
if(typeof SDK=="undefined"){SDK={__namespace:true}}SDK.REST={_context:function(){if(typeof GetGlobalContext!="undefined"){return GetGlobalContext()}else{if(typeof Xrm!="undefined"){return Xrm.Page.context}else{throw new Error("Context is not available.")}}},_getServerUrl:function(){var a=this._context().getServerUrl();if(a.match(/\/$/)){a=a.substring(0,a.length-1)}return a},_ODataPath:function(){return this._getServerUrl()+"/XRMServices/2011/OrganizationData.svc/"},_errorHandler:function(a){return new Error("Error : "+a.status+": "+a.statusText+": "+JSON.parse(a.responseText).error.message.value)},_dateReviver:function(a,b){var c;if(typeof b==="string"){c=/Date\(([-+]?\d+)\)/.exec(b);if(c){return new Date(parseInt(b.replace("/Date(","").replace(")/",""),10))}}return b},_parameterCheck:function(a,b){if(typeof a==="undefined"||a===null){throw new Error(b)}},_stringParameterCheck:function(a,b){if(typeof a!="string"){throw new Error(b)}},_callbackParameterCheck:function(a,b){if(typeof a!="function"){throw new Error(b)}},createRecord:function(a,b,c,d){this._parameterCheck(a,"SDK.REST.createRecord requires the object parameter.");this._stringParameterCheck(b,"SDK.REST.createRecord requires the type parameter is a string.");this._callbackParameterCheck(c,"SDK.REST.createRecord requires the successCallback is a function.");this._callbackParameterCheck(d,"SDK.REST.createRecord requires the errorCallback is a function.");var e=new XMLHttpRequest;e.open("POST",this._ODataPath()+b+"Set",true);e.setRequestHeader("Accept","application/json");e.setRequestHeader("Content-Type","application/json; charset=utf-8");e.onreadystatechange=function(){if(this.readyState==4){if(this.status==201){c(JSON.parse(this.responseText,SDK.REST._dateReviver).d)}else{d(SDK.REST._errorHandler(this))}}};e.send(JSON.stringify(a))},retrieveRecord:function(a,b,c,d,e,f){this._stringParameterCheck(a,"SDK.REST.retrieveRecord requires the id parameter is a string.");this._stringParameterCheck(b,"SDK.REST.retrieveRecord requires the type parameter is a string.");if(c!=null)this._stringParameterCheck(c,"SDK.REST.retrieveRecord requires the select parameter is a string.");if(d!=null)this._stringParameterCheck(d,"SDK.REST.retrieveRecord requires the expand parameter is a string.");this._callbackParameterCheck(e,"SDK.REST.retrieveRecord requires the successCallback parameter is a function.");this._callbackParameterCheck(f,"SDK.REST.retrieveRecord requires the errorCallback parameter is a function.");var g="";if(c!=null||d!=null){g="?";if(c!=null){var h="$select="+c;if(d!=null){h=h+","+d}g=g+h}if(d!=null){g=g+"&$expand="+d}}var i=new XMLHttpRequest;i.open("GET",this._ODataPath()+b+"Set(guid'"+a+"')"+g,true);i.setRequestHeader("Accept","application/json");i.setRequestHeader("Content-Type","application/json; charset=utf-8");i.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){e(JSON.parse(this.responseText,SDK.REST._dateReviver).d)}else{f(SDK.REST._errorHandler(this))}}};i.send()},updateRecord:function(a,b,c,d,e){this._stringParameterCheck(a,"SDK.REST.updateRecord requires the id parameter.");this._parameterCheck(b,"SDK.REST.updateRecord requires the object parameter.");this._stringParameterCheck(c,"SDK.REST.updateRecord requires the type parameter.");this._callbackParameterCheck(d,"SDK.REST.updateRecord requires the successCallback is a function.");this._callbackParameterCheck(e,"SDK.REST.updateRecord requires the errorCallback is a function.");var f=new XMLHttpRequest;f.open("POST",this._ODataPath()+c+"Set(guid'"+a+"')",true);f.setRequestHeader("Accept","application/json");f.setRequestHeader("Content-Type","application/json; charset=utf-8");f.setRequestHeader("X-HTTP-Method","MERGE");f.onreadystatechange=function(){if(this.readyState==4){if(this.status==204||this.status==1223){d()}else{e(SDK.REST._errorHandler(this))}}};f.send(JSON.stringify(b))},deleteRecord:function(a,b,c,d){this._stringParameterCheck(a,"SDK.REST.deleteRecord requires the id parameter.");this._stringParameterCheck(b,"SDK.REST.deleteRecord requires the type parameter.");this._callbackParameterCheck(c,"SDK.REST.deleteRecord requires the successCallback is a function.");this._callbackParameterCheck(d,"SDK.REST.deleteRecord requires the errorCallback is a function.");var e=new XMLHttpRequest;e.open("POST",this._ODataPath()+b+"Set(guid'"+a+"')",true);e.setRequestHeader("Accept","application/json");e.setRequestHeader("Content-Type","application/json; charset=utf-8");e.setRequestHeader("X-HTTP-Method","DELETE");e.onreadystatechange=function(){if(this.readyState==4){if(this.status==204||this.status==1223){c()}else{d(SDK.REST._errorHandler(this))}}};e.send()},retrieveMultipleRecords:function(a,b,c,d,e){this._stringParameterCheck(a,"SDK.REST.retrieveMultipleRecords requires the type parameter is a string.");if(b!=null)this._stringParameterCheck(b,"SDK.REST.retrieveMultipleRecords requires the options parameter is a string.");this._callbackParameterCheck(c,"SDK.REST.retrieveMultipleRecords requires the successCallback parameter is a function.");this._callbackParameterCheck(d,"SDK.REST.retrieveMultipleRecords requires the errorCallback parameter is a function.");this._callbackParameterCheck(e,"SDK.REST.retrieveMultipleRecords requires the OnComplete parameter is a function.");var f="";if(b!=null){if(b.charAt(0)!="?"){f="?"+b}else{f=b}}var g=new XMLHttpRequest;g.open("GET",this._ODataPath()+a+"Set"+f,true);g.setRequestHeader("Accept","application/json");g.setRequestHeader("Content-Type","application/json; charset=utf-8");g.onreadystatechange=function(){if(this.readyState==4){if(this.status==200){var b=JSON.parse(this.responseText,SDK.REST._dateReviver).d;c(b.results);if(b.__next!=null){var f=b.__next.substring((SDK.REST._ODataPath()+a+"Set").length);SDK.REST.retrieveMultipleRecords(a,f,c,d,e)}else{e()}}else{d(SDK.REST._errorHandler(this))}}};g.send()},__namespace:true}
</script>
<script type="text/javascript" language="javascript">
    //<!--  JSON Code-->
    if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());
</script>
<script type="text/javascript" language="javascript">

    var olicense = null;

    //Constant
    var cWebResource = 'WebResource';
    var cLicenseUpdated = 'Settings updated successfully.Kindly publish the solution to complete the process.';
    var cLicenseNotFound = 'Settings file not available';
    var cLicenseLoad = 'Loading Settings...';


    function fetchlicense() {
        UpdateMessage(cLicenseLoad);
        var productName = document.getElementById('ProductName').value;
        var selectQry = "$filter=Name eq 'iotap_" + productName + "config.xml'";
        SDK.REST.retrieveMultipleRecords(cWebResource, selectQry, fetchlicense_success, onerror, oncomplete);

    }

    function fetchlicense_success(e, p) {

        UpdateMessage('');

        if (e != null && e.length > 0) {
            olicense = e[0];
            var license = Base64.decode(e[0].Content);

            if (window.DOMParser) {
                parser = new DOMParser();
                xmlDoc = parser.parseFromString(license, "text/xml");
            }
            else // Internet Explorer
            {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = false;
                xmlDoc.loadXML(license);
            }
            var enableLog = xmlDoc.getElementsByTagName("EnableLogging")[0].childNodes[0].nodeValue;
            if (enableLog.toLowerCase() == 'yes') {
                document.getElementById("chkLogEnable").checked = true;
            }
            else {
                document.getElementById("chkLogEnable").checked = false;
            }
        }

    }
    function onerror(e) {
        UpdateMessage(e.message);
    }
    function oncomplete(e) {

    }

    function Save() {

        if (olicense != null) { // Update
            var license = "";
            if (document.getElementById("chkLogEnable").checked) {
                //enableLog.nodeValue = "Yes";
                license = "<?xml version='1.0' encoding='utf-8'?><Configuration><EnableLogging>Yes</EnableLogging></Configuration>"
            }
            else {
                //enableLog.nodeValue = "No";
                license = "<?xml version='1.0' encoding='utf-8'?><Configuration><EnableLogging>No</EnableLogging></Configuration>"
            }

            olicense.Content = Base64.encode(license);
            SDK.REST.updateRecord(olicense.WebResourceId, olicense, cWebResource, update_success, onerror);
        }
        else {//Create
            UpdateMessage(cLicenseNotFound);
        }
    }


    var license = {
        LanguageCode: 1033,
        Name: '',
        Content: '',
        WebResourceType: 4
    };

    function update_success(e, p) {
        UpdateMessage(cLicenseUpdated);
    }


    var Base64 = {

        // private property
        _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

        // public method for encoding
        encode: function (input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;

            input = Base64._utf8_encode(input);

            while (i < input.length) {

                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);

                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;

                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }

                output = output +
        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

            }

            return output;
        },

        // public method for decoding
        decode: function (input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;

            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

            while (i < input.length) {

                enc1 = this._keyStr.indexOf(input.charAt(i++));
                enc2 = this._keyStr.indexOf(input.charAt(i++));
                enc3 = this._keyStr.indexOf(input.charAt(i++));
                enc4 = this._keyStr.indexOf(input.charAt(i++));

                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;

                output = output + String.fromCharCode(chr1);

                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }

            }

            output = Base64._utf8_decode(output);

            return output;

        },

        // private method for UTF-8 encoding
        _utf8_encode: function (string) {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";

            for (var n = 0; n < string.length; n++) {

                var c = string.charCodeAt(n);

                if (c < 128) {
                    utftext += String.fromCharCode(c);
                }
                else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }

            return utftext;
        },

        // private method for UTF-8 decoding
        _utf8_decode: function (utftext) {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;

            while (i < utftext.length) {

                c = utftext.charCodeAt(i);

                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                }
                else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                }
                else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }

            }

            return string;
        }

    }
    function UpdateMessage(msg) {
        var spnMessage = document.getElementById('spnMessage');
        spnMessage.innerHTML = msg;
    }

</script>
<body onload="fetchlicense();">
    <b><span class="style1">Setting</span> </b>
    <br />
    <label class="label">
        <input type="checkbox" name="checkbox" id="chkLogEnable" value="value" class="label"></input>
        Enable Event Logging</label>
    <br />
    <br />
    <input type="button" value="Save" onclick="javascript:Save();" class="crmbutton" />
    <br />
    <br />
    <span id="spnMessage" class="msg"></span>
    <!-- PRODUCT name will be maintained in below field -->
    <input type="hidden" id="ProductName" value="clone" />
    <!--<hr />-->
    <!--<i>Copyright IOTAP as 2012. www.iotap.com</i>-->
</body>
</html>
