﻿<html>
<head>
    <title></title>
    <style>

        .hideCtrl{
            display:none;
        }

        .tabText {
            color: #262626;
            font-family: 'Segoe UI';
            font-size: 21px;
            font-weight:normal;
        }

        .labelText {
            font-family: 'Segoe UI';
            font-size: 12px;
            color: #444444;
        }

        .tinyText {
            font-family: 'Segoe UI';
            font-size: 10px;
            color: #444444;           
           
        }

        .toggle {
            font-family: 'Segoe UI';
            font-size: 10px;
            color: #444444;
        }        

        .controlText {
            font-family: 'Segoe UI';
            font-size: 12px;
            color: black;
        }
        .controlText label {
            display: block;
            padding: 2px 2px 2px 2px;
            border-bottom: #E6E6E6 1px dashed;
        }
        .controlText label:hover {
            background-color: #B1D6F0;
        }

        .tooltip {
            display: none;
            position: absolute;
            border: 1px solid #333;
            background-color: #ffff99;
            border-radius: 1px;
            padding: 5px;
            color: black;
            font-size: 12px;
            font-family: 'Segoe UI';            
        }
           
    </style>

    <script src="ClientGlobalContext.js.aspx"></script>
    <script src="iotap_addon_recordclone_jquery3.1.0.min.js" type="text/javascript"></script>
    <script src="iotap_addon_recordclone_json2.js" type="text/javascript"></script>
    <script src="iotap_addon_recordclone.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">

        var showDiv;
        var currUserLcid = Xrm.Page.context.getUserLcid();
        var parentIdDict = new Object();
        var customizableEntityList;
        var isOrgOwned = false;
        var adminSectionVisible = false;

        $(document).ready(function () {
            // Tooltip only Text
            $('.customToolTip').hover(function () {
                // Hover over code                
                var title = $(this).attr('title');
                $(this).data('tipText', title).removeAttr('title');
                $('<p class="tooltip"></p>')
                .html(title)
                .appendTo('body')
                .fadeIn('slow');
            }, function () {
                // Hover out code
                $(this).attr('title', $(this).data('tipText'));
                $('.tooltip').remove();
            }).mousemove(function (e) {
                var mousex = e.pageX + 20; //Get X coordinates
                var mousey = e.pageY + 10; //Get Y coordinates
                $('.tooltip')
                .css({ top: mousey, left: mousex })
            });

            IOTAP_AddOn_RecordClone_PopulateEntityList(currUserLcid);

            //Load existing values in case of an existing record
            if (window.parent.Xrm.Page.ui.getFormType() != 1)
                IOTAP_AddOn_RecordClone_LoadExistingValues();

            if (window.parent.Xrm.Page.ui.getFormType() == 1) {
                $("body :input").prop("disabled", true);
                $("#cboEntityList").prop("disabled", false);
                IOTAP_AddOn_RecordClone_LoadDefaultValues();
            }

        });
        

        IOTAP_AddOn_RecordClone_LoadDefaultValues = function ()
        {
            window.parent.Xrm.Page.data.entity.attributes.get("iotap_ignoredattributes").setValue("activityid, createdby, createdon, createdonbehalfby, exchangerate, extendedamount, extendedamount_base, importsequencenumber, modifiedon, modifiedby, modifiedonbehalfby, overriddencreatedon, owningbusinessunit, manualdiscountamount_base, baseamount_base, owninguser, priceperunit_base, tax_base, timezoneruleversionnumber, utcconversiontimezonecode, versionnumber, volumediscountamount_base, opportunitystatecode, quotestatecode, invoicestatecode, salesorderstatecode, quotenumber, organizer, address1_addressid, address2_addressid, address3_addressid, yomifirstname, yomilastname, processid, stageid, yomifullname, yomimiddlename, merged, masterid, participatesinworkflow, owneridyominame, createdbyyominame, modifiedbyyominame, yominame,objecttypecode");
            window.parent.Xrm.Page.data.entity.attributes.get("iotap_ignoredrelationships").setValue("principalobjectattributeaccess, postfollow, postregarding, postrole, customerrelationship, userentityinstancedata, socialactivity, duplicaterecord, mailboxtrackingfolder, bulkoperationlog, bulkdeletefailure, activitypointer, socialprofile, activityparty, customerrelationship, sharepointdocument, asyncoperation, customeropportunityrole, recurringappointmentmaster, processsession, sharepointdocumentlocation, connection, list, quoteclose, orderclose, opportunityclose");
        }

        IOTAP_AddOn_RecordClone_PopulateEntityList = function( lcd )
        {
            try {

                var entityColl = [];
                var ctrlEntityList = document.getElementById( "cboEntityList" );

                customizableEntityList = IOTAP_AddOn_RecordClone_GetCustomizableEntityList();

                for (var i = 0; i < customizableEntityList.length; i++) {
                    if ( customizableEntityList[i].DisplayName.UserLocalizedLabel )
                    {
                        entityColl.push({                            
                            'SchemaName': customizableEntityList[i].LogicalName + "|" + customizableEntityList[i].MetadataId + "|" + customizableEntityList[i].PrimaryNameAttribute,
                            'DisplayName': customizableEntityList[i].DisplayName.UserLocalizedLabel.Label
                        });
                    }
                    else {
                        var labelColl = customizableEntityList[i].DisplayName.LocalizedLabels;
                        for (var key in labelColl) {
                            if (labelColl.hasOwnProperty(key)) {
                                if (labelColl[key].LanguageCode == lcd) {
                                    entityColl.push({                                        
                                        'SchemaName': customizableEntityList[i].LogicalName + "|" + customizableEntityList[i].MetadataId + "|" + customizableEntityList[i].PrimaryNameAttribute,
                                        'DisplayName': labelColl[key].Label
                                    });                                    
                                }                                    
                            }
                        }
                    }
                }

                entityColl.sort(function (a, b) {
                    var textA = a.DisplayName;
                    var textB = b.DisplayName;
                    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
                });

                for (var i = 0; i < entityColl.length; i++) {
                    ctrlEntityList.add(new Option(entityColl[i].DisplayName, entityColl[i].SchemaName));
                }

            }
            catch ( ex ) {
                alert( ex.message )
            }
        }

        
        IOTAP_AddOn_RecordClone_IOTAP_ShowHideAdminSetting = function()
        {
            if(adminSectionVisible)
            {
                $( "#adminSetting" ).hide();
                adminSectionVisible = false;
            }
            else {
                $( "#adminSetting" ).show();
                adminSectionVisible = true;
            }
        }

        IOTAP_AddOn_RecordClone_ToggleSelection = function(ctrl, sectionId, statusId)
        {
            var ticked = true;
            var counter = 0;
            var section = $( '#' + sectionId );                      
            var status = $( '#' + statusId );  
          
            if ( $(ctrl).hasClass( "toggle" ) )
                ticked = false;            

            try{
                $.each( $( "input[name='" + sectionId + "']" ), function ()
                {   
                    $(this).prop("checked", ticked);
                    if (ticked) {
                        $(this).parent().css('background-color', '#B1D6F0');
                        counter++;
                    }
                    else {
                        $(this).parent().css('background-color', 'white');                        
                    }
                } );

                if ( ticked )
                    $(ctrl).addClass( "toggle" );                
                else                    
                    $(ctrl).removeClass( "toggle" );                

                status.html( "Total Selected : " + counter );
            }
            catch(ex)
            {
                throw ex;
            }
        }

        IOTAP_AddOn_RecordClone_LoadExistingValues = function ()
        {
            var entityName = window.parent.Xrm.Page.data.entity.attributes.get( "iotap_entityschemaname" ).getValue();            
            var entityMetadataId = window.parent.Xrm.Page.data.entity.attributes.get( "iotap_entitymetadataid" ).getValue();
            var parentAttributeName = window.parent.Xrm.Page.data.entity.attributes.get( "iotap_primaryattributename" ).getValue();
            var entityVal = entityName + "|" + entityMetadataId + "|" + parentAttributeName;
            var counter = 0;
            var relLst;
            
            $( "#cboEntityList" ).val( entityVal );
            IOTAP_AddOn_RecordClone_PopulateFormControls( entityVal, currUserLcid );

            $( "#txtIdentifierText" ).val( window.parent.Xrm.Page.data.entity.attributes.get( "iotap_identifiertext" ).getValue() );
            $( "#cboCloneIdentifier" ).val( window.parent.Xrm.Page.data.entity.attributes.get( "iotap_cloneidentifier" ).getValue() );
            $( "#chkClonePrompt").prop('checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_cloneprompt" ).getValue());
            $( '#chkCloneMultiple' ).prop( 'checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_clonemultiple" ).getValue() );
            $( '#chkResetOwner' ).prop( 'checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_resetowner" ).getValue() );
            $( '#chkResetStatus' ).prop( 'checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_resetstatus" ).getValue() );
            $( '#chkApplyExlusionInRelatedRelationship' ).prop( 'checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_applyexclusioninrelatedrelationship" ).getValue() );
            $( '#chkIncludeActiveInRelatedRelationship' ).prop( 'checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_includeactiveinrelatedrelationship" ).getValue() );
            $( '#chkOpenClone' ).prop( 'checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_openclonerecord" ).getValue() );
            $("#cboParentIdList").val(window.parent.Xrm.Page.data.entity.attributes.get("iotap_parentidattribute").getValue()); 

            //Reset CreatedBy field
            $( '#chkResetCreatedBy' ).prop( 'checked', window.parent.Xrm.Page.data.entity.attributes.get( "iotap_resetcreatedby" ).getValue() );

            var exclFldLst = window.parent.Xrm.Page.data.entity.attributes.get( "iotap_excludedattributes" ).getValue();
            if ( exclFldLst != null ) {
                var fldLst = exclFldLst.replace( /\s/g, "" ).split(',');               
                $.each($("input[name='excludefields']"), function () {                   
                if ( $.inArray( $(this).val(), fldLst) >= 0) {
                    $(this).prop("checked", true);
                    $(this).parent().css('background-color', '#B1D6F0');
                    counter++;
                }
                else {
                    $(this).parent().css('background-color', 'white');
                }
            });
                             
            $( "#lblExcludeStatus" ).html( "Total Selected : " + counter );
            }

            counter = 0;
            var one2nRelLst = window.parent.Xrm.Page.data.entity.attributes.get( "iotap_1tonrelationship" ).getValue();
            if ( one2nRelLst != null ) {
                relLst = one2nRelLst.replace( /\s/g, "" ).split( ',' );

            $.each($("input[name='onetonrelationship']"), function () {
                if ($.inArray($(this).val(), relLst) >= 0) {
                    $(this).prop("checked", true);
                    $(this).parent().css('background-color', '#B1D6F0');
                    counter++;
                }
                else
                    $(this).parent().css('background-color', 'white');
            });
            $( "#lblOneToNStatus" ).html( "Total Selected : " + counter );
            }            

            counter = 0;
            relLst = "";
            var n2nRelLst = window.parent.Xrm.Page.data.entity.attributes.get( "iotap_ntonrelationship" ).getValue();
            if ( n2nRelLst != null ) {
                relLst = n2nRelLst.replace( /\s/g, "" ).split( ',' );

            $.each($("input[name='ntonrelationship']"), function () {
                if ($.inArray($(this).val(), relLst) >= 0) {
                    $(this).prop("checked", true);
                    $(this).parent().css('background-color', '#B1D6F0');
                    counter++;
                }
                else
                    $(this).parent().css('background-color', 'white');
            });
            $( "#lblNToNStatus" ).html( "Total Selected : " + counter );
            }
        }


        IOTAP_AddOn_RecordClone_GetCustomizableEntityList = function ()
        {
            var coll;
            try {
                var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "GET", "EntityDefinitions?$select=LogicalName,DisplayName,PrimaryNameAttribute,MetadataId&$filter=IsCustomizable/Value eq true", false );
                httpReq.send( null );

                if ( httpReq.status === 200 ) {
                    coll = JSON.parse( httpReq.responseText ).value;
                }
                return coll;
            }
            catch ( ex ) {
                throw ex;
            }
        }

        IOTAP_AddOn_RecordClone_PopulateFormControls = function ( entityVal, currUserLcid )
        {
            try {
                
                isOrgOwned = false;

                //script to trigger population of the ignored fields/relationships (set via business rule)
                window.parent.Xrm.Page.data.entity.attributes.get("iotap_entityname").setValue($("#cboEntityList option:selected").text());
                window.parent.Xrm.Page.getAttribute("iotap_entityname").fireOnChange();

                if ( entityVal == "" )
                {  
                    IOTAP_AddOn_RecordClone_ResetValues();
                    return;
                }

                //warn user of form changes if fired on an existing record
                if (window.parent.Xrm.Page.ui.getFormType() != 1) {

                    $("#cboEntityList option[value='']").remove();

                    var entityName = window.parent.Xrm.Page.data.entity.attributes.get("iotap_entityschemaname").getValue();
                    var entityMetadataId = window.parent.Xrm.Page.data.entity.attributes.get("iotap_entitymetadataid").getValue();
                    var parentAttributeName = window.parent.Xrm.Page.data.entity.attributes.get("iotap_primaryattributename").getValue();

                    //this is triggered via entity name change. prompt user before re-loading controls
                    if ( entityVal != entityName + "|" + entityMetadataId + "|" + parentAttributeName ) {
                        window.parent.Xrm.Utility.confirmDialog( "This will clear all values on this form.\nDo you want to Proceed?", function ()
                        {
                            IOTAP_AddOn_RecordClone_ProcessLoad( entityVal, currUserLcid );
                            IOTAP_AddOn_RecordClone_SetDefaultValues();

                            if ( isOrgOwned ) {
                                $( "#chkResetOwner" ).prop( "checked", false );
                                $("#chkResetOwner").prop("disabled", true);

                                $("#chkResetCreatedBy").prop( "checked", false ); 
                                $("#chkResetCreatedBy").prop("disabled", true);

                            }

                        }, function ()
                        {
                            //update entity dropdown back to the original value (available on the crm form )
                            $( "#cboEntityList" ).val( entityName + "|" + entityMetadataId + "|" + parentAttributeName );
                            return false;
                        } );
                    }
                    else //this is update mode load all controls
                    {
                        IOTAP_AddOn_RecordClone_ProcessLoad( entityVal, currUserLcid );

                        if ( isOrgOwned ) {
                            $( "#chkResetOwner" ).prop( "checked", false );
                            $("#chkResetOwner").prop("disabled", true);

                            $("#chkResetCreatedBy").prop( "checked", false );                               
                            $("#chkResetCreatedBy").prop("disabled", true);

                        }
                    }
                }
                else  //this is new record create mode. load all controls
                {
                    IOTAP_AddOn_RecordClone_ProcessLoad(entityVal, currUserLcid);
                    IOTAP_AddOn_RecordClone_SetDefaultValues();

                    if ( isOrgOwned ) {
                        $( "#chkResetOwner" ).prop( "checked", false );
                        $("#chkResetOwner").prop("disabled", true);

                         $("#chkResetCreatedBy").prop( "checked", false ); 
                        $("#chkResetCreatedBy").prop("disabled", true);
                    }
                }
                
            }
            catch(ex)
            {
                alert( ex.message );
            }

        }

        IOTAP_AddOn_RecordClone_SetDefaultValues = function()
        {
            //load all default values on the form
            $( "#txtIdentifierText" ).val( "[Clone {0}] {1}" );
            $('#chkClonePrompt').prop('checked', false);
            $('#chkCloneMultiple').prop('checked', true);
            $('#chkOpenClone').prop('checked', true);
            $('#chkResetOwner').prop('checked', true);
            $('#chkResetStatus').prop('checked', true);
            $("#cboParentIdList").val($("#target option:first").val());
            //$("#cboCloneIdentifier").val($("#target option:first").val());
            $('#chkApplyExlusionInRelatedRelationship').prop('checked', true);
            $('#chkIncludeActiveInRelatedRelationship').prop('checked', true);
            $("#lblExcludeStatus").html("Total Selected : 0");
            //$("#lblOneToNStatus").html("Total Selected : 0");
            $("#lblNToNStatus").html("Total Selected : 0");
            //Reset Createdby default set to false
            $('#chkResetCreatedBy').prop('checked', false);
        }

        IOTAP_AddOn_RecordClone_ResetValues = function ()
        {
            $( "#txtIdentifierText" ).val( "[Clone {0}] {1}" );
            $( '#chkClonePrompt' ).prop( 'checked', false );
            $( '#chkCloneMultiple' ).prop( 'checked', true );
            $( '#chkOpenClone' ).prop( 'checked', true );
            $( '#chkResetOwner' ).prop( 'checked', true );
            $('#chkResetStatus').prop('checked', true);
            $('#chkResetCreatedBy').prop('checked', false);
            $( "#cboParentIdList" ).val( $( "#target option:first" ).val() );
            $("#cboCloneIdentifier").val($("#target option:first").val());
            $( '#chkApplyExlusionInRelatedRelationship' ).prop( 'checked', true );
            $( '#chkIncludeActiveInRelatedRelationship' ).prop( 'checked', true );
            $( "#lblExcludeStatus" ).html( "Total Selected : 0" );
            $( "#lblNToNStatus" ).html( "Total Selected : 0" );
            $( "#excludeList" ).html( "--Please select an Entity--" );
            $( "#oneToNList" ).html( "--Please select an Entity--" );
            $( "#nToNList" ).html( "--Please select an Entity--" );
                        
        }

        IOTAP_AddOn_RecordClone_ProcessLoad = function ( entityVal, currUserLcid )
        {
            try {
                
                var entityName = entityVal.split( '|' )[0].toLowerCase();
                var entityMetadataId = entityVal.split( '|' )[1];
                var primaryAttributeName = entityVal.split( '|' )[2];

                var fieldColl = IOTAP_AddOn_RecordClone_RetrieveAttributesValidForCreate(entityMetadataId);
                var fieldList = IOTAP_AddOn_RecordClone_SortFieldList(fieldColl, entityName);
               
                IOTAP_AddOn_RecordClone_PopulateExludeList( fieldList, currUserLcid );
                IOTAP_AddOn_RecordClone_PopulateFieldList( fieldList, currUserLcid );

                IOTAP_AddOn_RecordClone_SetDefaultIdentifierText( entityName, primaryAttributeName );

                IOTAP_AddOn_RecordClone_Populate1ToNList( entityName, entityMetadataId );
                IOTAP_AddOn_RecordClone_PopulateNToNList( entityName, entityMetadataId );

                //enable all form fields
                if ( window.parent.Xrm.Page.ui.getFormType() == 1 ) 
                    $( "body :input" ).prop( "disabled", false );
            }
            catch(ex)
            {
                throw ex;
            }
        }


        IOTAP_AddOn_RecordClone_SetDefaultIdentifierText = function (entityName, primaryAttributeName)
        {
            try
            {
                switch(entityName)
                {
                    case "contact":
                        $( "#cboCloneIdentifier" ).val( "lastname" );
                        break;
                    case "lead":
                        $("#cboCloneIdentifier").val("subject");
                        break;
                    case "product":
                        $("#cboCloneIdentifier").val("productnumber");
                        break;
                    default:
                        $("#cboCloneIdentifier").val(primaryAttributeName);
                        break;
                }               
                
            }
            catch(ex)
            {
                throw ex;
            }
        }


        IOTAP_AddOn_RecordClone_PopulateNToNList = function ( entityName, entityMetadataId )
        {
            var displayName;
            var schemaName;
            var ignoreList;
            var ignoredRelations;
            
            if(window.parent.Xrm.Page.data.entity.attributes.get( "iotap_ignoredrelationships" ).getValue() != null)
                ignoredRelations = window.parent.Xrm.Page.data.entity.attributes.get( "iotap_ignoredrelationships" ).getValue().replace( /\s/g, "" );

            var ctrlNToNList = document.getElementById("nToNList");
            ctrlNToNList.innerHTML = "";

            if ( ignoredRelations != null )
                ignoreList = ignoredRelations.split( ',' );

            var relationshipList = IOTAP_AddOn_RecordClone_RetrieveNToNRelationships( entityMetadataId );

            if ( relationshipList.length == 0 )
                ctrlNToNList.innerHTML = "--No relationships available--";

            for ( var i = 0; i < relationshipList.length; i++ ) {
               
                if ( relationshipList[i].Entity1LogicalName.toLowerCase() == entityName ) {
                    displayName = relationshipList[i].Entity1NavigationPropertyName.toLowerCase() + " (" + relationshipList[i].Entity2LogicalName.toLowerCase() + ")";
                    schemaName = relationshipList[i].Entity1NavigationPropertyName + "|" + relationshipList[i].Entity2LogicalName.toLowerCase() + "|" + relationshipList[i].MetadataId;
                }
                else {
                    displayName = relationshipList[i].Entity1NavigationPropertyName.toLowerCase() + " (" + relationshipList[i].Entity1LogicalName.toLowerCase() + ")";
                    schemaName = relationshipList[i].Entity1NavigationPropertyName + "|" + relationshipList[i].Entity1LogicalName.toLowerCase() + "|" + relationshipList[i].MetadataId;
                }
                
                if ( $.inArray( schemaName.split("|")[1], ignoreList ) == -1 ) {
                    IOTAP_AddOn_RecordClone_CreateChkboxControl( ctrlNToNList, "ntonrelationship", displayName, schemaName, false );
                }
            }
        }

        IOTAP_AddOn_RecordClone_Populate1ToNList = function ( entityName, entityMetadataId )
        {
            var ignoreList;
            var ignoredRelations;
            var defaultCloneRelations = ["salesorderdetail", "opportunityproduct", "quotedetail", "invoicedetail", "productpricelevel"];
            var ctrl1ToNList = document.getElementById( "oneToNList" );
            ctrl1ToNList.innerHTML = "";

            if(window.parent.Xrm.Page.data.entity.attributes.get("iotap_ignoredrelationships").getValue() != null)
                ignoredRelations = window.parent.Xrm.Page.data.entity.attributes.get("iotap_ignoredrelationships").getValue().replace(/\s/g, "");

            if (ignoredRelations != null)
                ignoreList = ignoredRelations.split( ',' );

            var relationshipList = IOTAP_AddOn_RecordClone_Retrieve1ToNRelationships( entityMetadataId );

            if ( relationshipList.length == 0 )
                ctrl1ToNList.innerHTML = "--No relationships available--";

            //get the parent id list control
            var ctrlParentIdList = document.getElementById( "cboParentIdList" );            
            var tickCounter = 0;

            for ( var i = 0; i < relationshipList.length; i++ ) {

                var ticked = false;

                //add attribute to the parent id control if the referencing entity is the same as the refered entity
                if ( relationshipList[i].ReferencingEntity.toLowerCase() == entityName ) {

                    //Do not add option if there is not lookup control available (it might be internal/system lookup field)
                    //set an * with the lookup name field so that the plugin can identify this is a lookup. 
                    var attrDisplayName = IOTAP_AddOn_RecordClone_GetLookupDisplayName( relationshipList[i].ReferencingAttribute );
                    if ( attrDisplayName != undefined ) {
                        ctrlParentIdList.add( new Option( attrDisplayName, relationshipList[i].ReferencingAttribute + "*") );
                    }
                }

                //set  some default relationships when a new config record is created (if parent entity is not the child entity itself)           
                if ( window.parent.Xrm.Page.ui.getFormType() == 1 ) {

                    if ( entityName == "salesorder" && relationshipList[i].ReferencingEntity == "salesorderdetail" )
                        ticked = true;

                    if ( entityName == "opportunity" && relationshipList[i].ReferencingEntity == "opportunityproduct" )
                        ticked = true;

                    if ( entityName == "quote" && relationshipList[i].ReferencingEntity == "quotedetail" )
                        ticked = true;

                    if ( entityName == "invoice" && relationshipList[i].ReferencingEntity == "invoicedetail" )
                        ticked = true;

                    if ( entityName == "product" && relationshipList[i].ReferencingEntity == "productpricelevel" )
                        ticked = true;

                    if ( ticked )
                        tickCounter++;
                }

                if ( $.inArray( relationshipList[i].ReferencingEntity, ignoreList ) == -1 ) {
                    IOTAP_AddOn_RecordClone_CreateChkboxControl( ctrl1ToNList, "onetonrelationship", relationshipList[i].SchemaName.toLowerCase() + " (" + relationshipList[i].ReferencingEntity + ")", relationshipList[i].SchemaName + "|" + relationshipList[i].ReferencingEntity + "|" + relationshipList[i].ReferencingAttribute + "|" + relationshipList[i].MetadataId, ticked );                   
                }                
            }

            $( "#lblOneToNStatus" ).html( "Total Selected : " + tickCounter );
            
            //IOTAP_AddOn_RecordClone_PopulateDrilldownRelationships( drilldownRelations )
        }

        IOTAP_AddOn_RecordClone_Populate1ToNSubList = function ( sectionName, relations )
        {
            
            
        }

        IOTAP_AddOn_RecordClone_PopulateDrilldownRelationships = function ( drilldownRelations )
        {
            var coll= [];
            var tempRelations = [];
            var i = 0;
            var len = 0;

            try {
                
                for ( i = 0, len = drilldownRelations.length; i < len; i += 20 ) {
                    tempRelations.push( drilldownRelations.slice( i, i + 20 ) );
                }

                for ( i = 0, len = tempRelations.length; i < len; i++ ) {
                    var drilldownRelationFilter = tempRelations[i].join( ' or ' );

                    var query = "RelationshipDefinitions/Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata?$select=SchemaName,ReferencedEntity,ReferencingAttribute,ReferencingEntity&$filter=" + drilldownRelationFilter;                   
                    var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "GET", query, false );
                    httpReq.send( null );

                    if ( httpReq.status === 200 ) {                       
                        coll = coll.concat(JSON.parse( httpReq.responseText ).value);
                    }
                }                                             

                return coll;
            }
            catch ( ex ) {
                throw ex;
            }
        }


        IOTAP_AddOn_RecordClone_GetLookupDisplayName = function ( attrName )
        {
            try {
                for (var key in parentIdDict) {
                    if ( key == attrName )
                        return parentIdDict[key];
                }
            }
            catch ( ex ) {
                throw ex;
            }
        }

        IOTAP_AddOn_RecordClone_PopulateExludeList = function ( fieldList, currUserLcid )
        {
            var ctrlExcludeList = document.getElementById( "excludeList" );
            ctrlExcludeList.innerHTML = "";

            if ( fieldList.length == 0 )
                ctrlExcludeList.innerHTML = "--No fields available--";

            for ( var i = 0; i < fieldList.length; i++ ) {
                if ( fieldList[i].DisplayName) {
                    IOTAP_AddOn_RecordClone_CreateChkboxControl( ctrlExcludeList, "excludefields", fieldList[i].DisplayName, fieldList[i].LogicalName, false );                    
                }                
            }            
        }


        IOTAP_AddOn_RecordClone_PopulateFieldList = function ( fieldList, currUserLcid )
        {
            try{
                var ctrlParentIdList = document.getElementById( "cboParentIdList" );
                var ctrlCloneIdentifier = document.getElementById( "cboCloneIdentifier" );
                //clear all existing options
                ctrlParentIdList.innerHTML = "<option value=''>--Select One--</option>";
                ctrlCloneIdentifier.innerHTML = "<option value=''>--Select One--</option>";

                for ( var i = 0; i < fieldList.length; i++ ) {
                    if ( fieldList[i].AttributeType.toLowerCase() == "string" || fieldList[i].AttributeType.toLowerCase() == "memo" || fieldList[i].AttributeType.toLowerCase() == "lookup" ) {                       
                        if ( fieldList[i].AttributeType.toLowerCase() == "string" || fieldList[i].AttributeType.toLowerCase() == "memo" ) {
                            ctrlParentIdList.add(new Option(fieldList[i].DisplayName, fieldList[i].LogicalName));
                            ctrlCloneIdentifier.add(new Option(fieldList[i].DisplayName, fieldList[i].LogicalName));
                        }
                        if ( fieldList[i].AttributeType.toLowerCase() == "lookup" )
                            parentIdDict[fieldList[i].LogicalName] = fieldList[i].DisplayName + " (lookup)"; 
                    }
                }                              
            }
            catch(ex)
            {
                throw ex;
            }
        }

        IOTAP_AddOn_RecordClone_SortFieldList = function (fieldList, entityName) {

            var jsonObj = [];
            var ignoreList;
            var ignoredFields;
            
            if(window.parent.Xrm.Page.data.entity.attributes.get("iotap_ignoredattributes").getValue() != null)
                ignoredFields = window.parent.Xrm.Page.data.entity.attributes.get("iotap_ignoredattributes").getValue().replace(/\s/g, "");

            //remove owner/statecode & status code fields as well
            //this is hardcoded here since the plugin needs these 3 fields. these fields are later removed by the plugin
            ignoredFields += ",ownerid,statuscode,statecode";

            if (ignoredFields != null)
                ignoreList = ignoredFields.split(',');

            try{

                for (var i = 0; i < fieldList.length; i++) {
                    if (fieldList[i].LogicalName != entityName + "id" && fieldList[i].LogicalName != "activityid" && $.inArray( fieldList[i].LogicalName, ignoreList ) == -1 ) {
                        if (fieldList[i].DisplayName.UserLocalizedLabel) {
                            jsonObj.push({
                                'AttributeType': fieldList[i].AttributeType,
                                'LogicalName': fieldList[i].LogicalName,
                                'DisplayName': fieldList[i].DisplayName.UserLocalizedLabel.Label
                            });
                        }
                        else {
                            var labelColl = fieldList[i].DisplayName.LocalizedLabels;
                            for (var key in labelColl) {
                                if (labelColl.hasOwnProperty(key)) {
                                    if (labelColl[key].LanguageCode == currUserLcid) {
                                        jsonObj.push({
                                            'AttributeType': fieldList[i].AttributeType,
                                            'LogicalName': fieldList[i].LogicalName,
                                            'DisplayName': labelColl[key].Label
                                        });
                                    }
                                }
                            }
                        }
                    }
                }

                jsonObj.sort(function (a, b) {
                    var textA = a.DisplayName;
                    var textB = b.DisplayName;
                    return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
                });

            }
            catch(ex)
            {
                throw ex;
            }
            return jsonObj;
        }

        IOTAP_AddOn_RecordClone_RetrieveNToNRelationships = function ( entityMetadataId )
        {
            var coll;

            try {
                var query = "EntityDefinitions(" + entityMetadataId + ")/ManyToManyRelationships?$select=Entity1NavigationPropertyName,Entity1LogicalName,Entity1IntersectAttribute,Entity2LogicalName,Entity2IntersectAttribute,MetadataId";
                var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "GET", query, false );
                httpReq.send( null );

                if ( httpReq.status === 200 ) {
                    coll = JSON.parse( httpReq.responseText ).value;
                }
                return coll;
            }
            catch ( ex ) {
                throw ex;
            }
        }

        IOTAP_AddOn_RecordClone_Retrieve1ToNRelationships = function ( entityMetadataId )
        {
            var coll;

            try {
                var query = "EntityDefinitions(" + entityMetadataId + ")/OneToManyRelationships?$select=SchemaName,ReferencingAttribute,ReferencingEntity,MetadataId";
                var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "GET", query, false );
                httpReq.send( null );

                if ( httpReq.status === 200 ) {
                    coll = JSON.parse( httpReq.responseText ).value;
                }
                return coll;
            }
            catch ( ex ) {
                throw ex;
            }
        }

        IOTAP_AddOn_RecordClone_RetrieveAttributesValidForCreate = function ( entityMetadataId )
        {
            var coll;

            try {
                var query = "EntityDefinitions(" + entityMetadataId + ")?$select=LogicalName,OwnershipType&$expand=Attributes($select=LogicalName,AttributeType,DisplayName;$filter=IsValidForCreate%20eq%20true)";
                var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "GET", query, false );
                httpReq.send( null );

                if ( httpReq.status === 200 ) {

                    //disable reset owner field if the entity is org owned
                    if ( JSON.parse( httpReq.responseText ).OwnershipType.toLowerCase() == "organizationowned" )
                        isOrgOwned = true;

                    coll = JSON.parse( httpReq.responseText ).Attributes;
                }
                return coll;
            }
            catch ( ex ) {
                throw ex;
            }
        }

        IOTAP_AddOn_RecordClone_SetLabelStatus = function ( ctrl )
        {            
            var counter = 0;
            var statusCtrl;
            $.each( $( "input[name='" + ctrl.name + "']" ), function ()
            {
                if ( $( this ).prop( "checked" ) == true ) {
                    $( this ).parent().css( 'background-color', '#B1D6F0' );
                    counter++;
                }
                else {
                    $( this ).parent().css( 'background-color', 'white' );
                }
            } );

            switch(ctrl.name)
            {
                case "excludefields" :
                    statusCtrl = "lblExcludeStatus";
                    break;
                case "onetonrelationship" :
                    statusCtrl = "lblOneToNStatus";
                    break;
                case "ntonrelationship" :
                    statusCtrl = "lblNToNStatus";
                    break;
                default:
                    statusCtrl = "";
                    break;
            }
            
            $( "#" + statusCtrl ).html( "Total Selected : " + counter );
        }

        IOTAP_AddOn_RecordClone_CreateChkboxControl = function ( parentElm, chkboxGrpName, chkboxDisplayName, chkboxValue, isChecked )
        {
            var chkd = "";
            var style = "";
            if ( isChecked == true ) {
                chkd = "checked";
                style = "style=background-color:#B1D6F0;";
            }

            try {                
                $( parentElm ).append( "<label id='lbl" + chkboxValue + "' " + style +"><input type='checkbox'  name='" + chkboxGrpName + "' value='" + chkboxValue + "' " + chkd + " onclick='IOTAP_AddOn_RecordClone_SetLabelStatus(this)' /> " + chkboxDisplayName + "</label>" );                
            }
            catch(ex)
            {
                throw ex;
            }

        }

        IOTAP_AddOn_RecordClone_CheckStateCodeAndKeyAttribute = function ( entityMetadataId )
        {
            try {                
                var coll = [];
                var keys = [];
                var entObj = new Object();
                var keyvalues = "";
                
                var query = "EntityDefinitions(" + entityMetadataId + ")?$select=LogicalName&$expand=Attributes($select=LogicalName;$filter=AttributeType eq Microsoft.Dynamics.CRM.AttributeTypeCode'State'),Keys($select=KeyAttributes)";
                var httpReq = IOTAP_AddOn_RecordClone_CreateHTTPRequest( "GET", query, false );
                httpReq.send( null );

                if ( httpReq.status === 200 ) {
                    coll = JSON.parse( httpReq.responseText ).Attributes;
                    keys = JSON.parse( httpReq.responseText ).Keys;
                }
                
                if ( coll.length > 0 )
                    entObj.IsStateCodeAvailable = true;
                else
                    entObj.IsStateCodeAvailable = false;

                for ( var i = 0; i < keys.length; i++ ) {
                    keyvalues += keys[i].KeyAttributes.toString() + ";";
                }
                                
                if ( keyvalues != "" )
                    keyvalues = keyvalues.substring( 0, keyvalues.length - 1 );

                entObj.Keys = keyvalues;

                return entObj;
            }
            catch ( ex ) {
                throw ex;
            }
        }

        function IOTAP_AddOn_RecordClone_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" ) {
                        IOTAP_AddOn_RecordClone_ParseDataValue( vals[i][1] );
                        found = true;
                        break;
                    }
                }
                if ( !found )
                { IOTAP_AddOn_RecordClone_NoParams(); }
            }
            else {
                IOTAP_AddOn_RecordClone_NoParams();
            }

        }

        IOTAP_AddOn_RecordClone_ParseDataValue = function ( 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 )
                        showDiv = vals[0][0];
                }
            }
            else {
                IOTAP_AddOn_RecordClone_NoParams();
            }
        }

        IOTAP_AddOn_RecordClone_NoParams = function ()
        {
            document.clear();
            var message = document.createElement( "p" );

            setText( message, "No data parameter was passed to this page" );
            document.body.appendChild( message );
        }


        IOTAP_AddOn_RecordClone_ProcessSave = function ()
        {
            var stateCodeEntityList = [];            
            var keyColl = [];
            //Retrieve values from the custom webresource form
            var entityVal = $( "#cboEntityList" ).val();

            //do not process further if entity name is blank
            if ( entityVal == "" ) {
                window.parent.Xrm.Page.ui.setFormNotification("You must provide a value for Entity", "ERROR","1");
                $( "#cboEntityList" ).focus();
                return false;
            }

            //clear any existing form notifications
            window.parent.Xrm.Page.ui.clearFormNotification( "1" );

            var entityName = entityVal.split( '|' )[0].toLowerCase();
            var entityMetadataId = entityVal.split( '|' )[1];
            var primaryAttributeName = entityVal.split( '|' )[2];

            var identiferText = $( "#txtIdentifierText" ).val();
            var cloneIdentifier = $( "#cboCloneIdentifier" ).val();
            var showPrompt = $( "#chkClonePrompt" ).is(":checked");
            var cloneMultiple = $( "#chkCloneMultiple" ).is( ":checked" );
            var openCloneRecord = $( "#chkOpenClone" ).is( ":checked" );
            var resetOwner = $( "#chkResetOwner" ).is( ":checked" );
            var resetStatus = $("#chkResetStatus").is(":checked");
            var resetCreatedBy = $( "#chkResetCreatedBy" ).is( ":checked" );
            var parentId = $( "#cboParentIdList" ).val();            
            var applyExlusionInRelatedRelationship = $( "#chkApplyExlusionInRelatedRelationship" ).is( ":checked" );
            var includeActiveInRelatedRelationship = $( "#chkIncludeActiveInRelatedRelationship" ).is( ":checked" );

            //get alternate keys for main entity
            for ( var i = 0; i < customizableEntityList.length; i++ ) {
                if ( customizableEntityList[i].LogicalName == entityName ) {
                    var entObj = IOTAP_AddOn_RecordClone_CheckStateCodeAndKeyAttribute( customizableEntityList[i].MetadataId );
                    if ( entObj.Keys != "" ) {
                        keyColl.push( entityName + ":" + entObj.Keys );
                    }
                    break;
                }
            }           

            var exclFlds = [];
            $.each( $( "input[name='excludefields']:checked" ), function ()
            {
                exclFlds.push( $( this ).val() );
            } );
            var excludeFields = exclFlds.join( ", " );

            var ntonRltn = [];
            $.each( $( "input[name='ntonrelationship']:checked" ), function ()
            {
                ntonRltn.push( $( this ).val() );

                //check if statecode exists for this entity 
                var relName = $( this ).val().split( "|" );
                for ( var i = 0; i < customizableEntityList.length; i++ ) {
                    if ( customizableEntityList[i].LogicalName == relName[1] ) {
                        var entObj = IOTAP_AddOn_RecordClone_CheckStateCodeAndKeyAttribute( customizableEntityList[i].MetadataId )
                        
                        if ( entObj.IsStateCodeAvailable )
                            stateCodeEntityList.push( relName[1] );

                        break;
                    }
                }
            } );
            var ntonRelations = ntonRltn.join( ", " );

            var onetonRltn = [];
            $.each( $( "input[name='onetonrelationship']:checked" ), function ()
            {
                onetonRltn.push( $( this ).val() );

                //check if statecode exists for this entity 
                var relName = $( this ).val().split( "|" );
                for ( var i = 0; i < customizableEntityList.length; i++ ) {
                    if ( customizableEntityList[i].LogicalName == relName[1] ) {
                        var entObj = IOTAP_AddOn_RecordClone_CheckStateCodeAndKeyAttribute( customizableEntityList[i].MetadataId )
                        if ( entObj.IsStateCodeAvailable )
                            stateCodeEntityList.push( relName[1] );

                        if ( entObj.Keys != "" ) {
                            keyColl.push(relName[1] + ":" + entObj.Keys);
                        }
                        break;
                    }
                }

            } );
            var onetonRelations = onetonRltn.join( ", " );
            var stateCodeEntities = stateCodeEntityList.join( "," );
            var keys = keyColl.join( "|" );
            
            //set values in crm form
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_entityschemaname" ).setValue( entityName );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_entityname" ).setValue( $( "#cboEntityList option:selected" ).text() );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_identifiertext" ).setValue( identiferText );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_cloneidentifier" ).setValue(cloneIdentifier);
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_cloneprompt" ).setValue( showPrompt );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_clonemultiple" ).setValue( cloneMultiple );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_resetowner" ).setValue( resetOwner );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_resetstatus" ).setValue( resetStatus );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_applyexclusioninrelatedrelationship" ).setValue( applyExlusionInRelatedRelationship );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_includeactiveinrelatedrelationship" ).setValue( includeActiveInRelatedRelationship );

            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_resetcreatedby" ).setValue( resetCreatedBy );

            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_parentidattribute" ).setValue( parentId );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_openclonerecord" ).setValue( openCloneRecord );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_excludedattributes" ).setValue( excludeFields );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_1tonrelationship" ).setValue( onetonRelations );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_ntonrelationship" ).setValue( ntonRelations );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_entitymetadataid" ).setValue( entityMetadataId );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_primaryattributename" ).setValue( primaryAttributeName );
            
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_statecodeentities" ).setValue( stateCodeEntities );
            window.parent.Xrm.Page.data.entity.attributes.get( "iotap_alternatekeys" ).setValue( keys );

            return true;
        }

    </script>
</head>
<body style="margin-left:0px;margin-top:0px;margin-bottom:0px;margin-right:0px;padding-top:0px;padding-bottom:0px;padding-left:0px;padding-right:0px;">

    <div>
        <span class="tabText">General</span>
        <table width="100%" cellpadding="2px" cellspacing="10px">
            <thead>
                <tr style="height:1px">
                    <td width="12%"></td>
                    <td width="37%"></td>
                    <td width="2%"></td>
                    <td width="12%"></td>
                    <td width="37%"></td>
                </tr>
            </thead>
            <tr>
                <td class="labelText customToolTip" style="text-align:left;vertical-align:top" title="Select the entity which needs to be enabled for cloning">Entity<span class="labelText" style="color:red">*</span></td>
                <td style="text-align:left">
                    <select id="cboEntityList" class="controlText" style=" height:22px" onchange="IOTAP_AddOn_RecordClone_PopulateFormControls( this.value, currUserLcid )">
                        <option value="">--Select One--</option>
                    </select>
                </td>
                <td>&nbsp;</td>
                <td class="labelText" style="text-align:left;vertical-align:top">&nbsp;</td>
                <td style="text-align:left">&nbsp;</td>
            </tr>
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Select the list of fields that need to be excluded in the cloning process">Excluded Fields</td>
                <td style="text-align: left;; vertical-align: top">
                    <span class="tinyText" style="text-align: left" id="lblExcludeStatus"></span><span class="tinyText" style="text-align: right; cursor: hand; text-decoration: underline; float: right; width: 50%; min-width: 50%;" onclick="IOTAP_AddOn_RecordClone_ToggleSelection(this, 'excludefields', 'lblExcludeStatus')">Select/Unselect All</span>
                    <div id="excludeList" style="width: 100%; height: 165px; overflow-y: scroll; border: #d6d6d6 1px solid; " class="controlText"> --Please select an Entity-- </div>
                </td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr> 
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top;" title="Select the list of 1:N related entities you need to clone">1:N Relationships</td>
                <td style="text-align: left; vertical-align: top;">
                    <span class="tinyText" style="text-align: left" id="lblOneToNStatus"></span><span class="tinyText" style="text-align: right; cursor: hand; text-decoration: underline; float: right; width: 50%; min-width: 50%; " onclick="IOTAP_AddOn_RecordClone_ToggleSelection(this, 'onetonrelationship', 'lblOneToNStatus')">Select/Unselect All</span>
                    <div id="oneToNList" style="width: 100%; height: 165px; overflow-y: scroll; border: #d6d6d6 1px solid; " class="controlText">--Please select an Entity-- </div>
                </td>
                <td>&nbsp;</td>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Select the list of N:N related entities you need to clone">N:N Relationships</td>
                <td style="text-align: left; vertical-align: top">
                    <span class="tinyText" style="text-align: left" id="lblNToNStatus"></span><span class="tinyText" style="text-align: right; cursor: hand; text-decoration:underline; float: right; width: 50%; min-width: 50%; " onclick="IOTAP_AddOn_RecordClone_ToggleSelection(this, 'ntonrelationship', 'lblNToNStatus')">Select/Unselect All</span>
                    <div id="nToNList" style="width: 100%; height: 165px; overflow-y: scroll; border: #d6d6d6 1px solid; " class="controlText"> --Please select an Entity-- </div>
                </td>
            </tr>    
        </table>
    </div>

    <div>
        <span class="tabText">Advanced Settings</span>
        <table width="100%" cellpadding="2px" cellspacing="10px">
            <thead>
                <tr style="height:1px">
                    <td width="12%"></td>
                    <td width="37%"></td>
                    <td width="2%"></td>
                    <td width="12%"></td>
                    <td width="37%"></td>
                </tr>
            </thead>
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="This field will be automatically set in the newly cloned record with the custom text declared in the 'Identifier Text' field.<br>Helps to easily identify the newly cloned record">Clone Prefix</td>
                <td style="text-align:left">
                    <select id="cboCloneIdentifier" class="controlText">
                        <option value="">--Select One--</option>
                    </select>
                </td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Select a field which can be used to identify the record thru which the record was clone.<br>You can select a text or a lookup field<br>Text field would store the guid of the parent record in string format">Original Record Field</td>
                <td style="text-align:left">
                    <select id="cboParentIdList" class="controlText">
                        <option value="">--Select One--</option>
                    </select>
                </td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Keep this checked if you want the logged in user to be the owner of the newly cloned record">Reset Owner</td>
                <td style="text-align:left">
                    <input type="checkbox" id="chkResetOwner" checked />
                </td>
                <td>&nbsp;</td>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Keep this checked if you want the status reason of the newly cloned record to be set to the default value(as defined within crm customziations)">Reset Status</td>
                <td style="text-align:left">
                    <input type="checkbox" id="chkResetStatus" checked />
                </td>
            </tr>
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top;" title="Keep this checked if you need only open/active records to be cloned while cloning related entities">Include only Active records for related Entity</td>
                <td style="text-align: left; vertical-align: top">
                    <input type="checkbox" id="chkIncludeActiveInRelatedRelationship" checked />
                </td>
                <td>&nbsp;</td>
                <!-- <td class="labelText" style="text-align: left; vertical-align: top">&nbsp;</td>
    <td style="text-align: left; vertical-align: top">&nbsp;</td> -->
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Keep this checked if you want the logged in user to be the Author of the Record (Created By Logged in user))">Reset Created By</td>
                <td style="text-align:left">
                    <input type="checkbox" id="chkResetCreatedBy" />
                </td>
            </tr>           
        </table>
        </div>

    <div>
        <span class="tabText" style="cursor:hand" onclick="IOTAP_AddOn_RecordClone_IOTAP_ShowHideAdminSetting()">Administrator Settings</span>
        <table width="100%" cellpadding="2px" cellspacing="10px" id="adminSetting" style="display:none">
            <thead>
                <tr style="height:1px">
                    <td width="12%"></td>
                    <td width="37%"></td>
                    <td width="2%"></td>
                    <td width="12%"></td>
                    <td width="37%"></td>
                </tr>
            </thead>
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Keep this checked if you want the exclusion field criteria to be set when the current entity is avialable as a related entity for some other entity">Apply Exlcusion under Relationship</td>
                <td style="text-align:left;vertical-align:top">
                    <input type="checkbox" id="chkApplyExlusionInRelatedRelationship" />
                </td>
                <td>&nbsp;</td>
                <td class="labelText customToolTip" style="text-align:left;vertical-align:top" title="Add a custom text here which would be appended to the 'Clone Identifier' field.<br>There are 2 placeholders {0} and {1}.<br>{0} is used only during Clone Multiple to apply sequential numbering.<br>{1} is used to set the sequece of the existing value in the field.<br>Below are the some examples of cloning an account record with the accountnumber A005<br>[Clone {1}] will result in [Clone A005]<br>{1}[Clone] will result in A005[Clone]<br>{1}[Clone {0}] will result in A005[Clone 1](only applicable to multiclone)">Prefix Text</td>
                <td style="text-align:left">
                    <input type="text" class="controlText" id="txtIdentifierText" value="[Clone {0}] {1}" maxlength="20" />
                </td>
            </tr>
            <tr>
                <td class="labelText customToolTip" style="text-align:left;vertical-align:top" title="Keep this checked if you want users to be warned before the clone process is initiated (only applicable for single record cloning) ">Clone Confirmation</td>
                <td style="text-align:left">
                    <input type="checkbox" class="controlText" id="chkClonePrompt" />
                </td>
                <td>&nbsp;</td>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Keep this checked for cloning multiple records">Clone Multiple Records</td>
                <td style="text-align:left">
                    <input type="checkbox" class="controlText" id="chkCloneMultiple" checked />
                </td>
            </tr>
            <tr>
                <td class="labelText customToolTip" style="text-align: left; vertical-align: top" title="Keep this checked if you need the cloned record to be automatically loaded on the screen after the cloning process<br>This is only applicable when a single record is cloned">Open Clone Record</td>
                <td style="text-align:left">
                    <input type="checkbox" id="chkOpenClone" checked />
                </td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </div>

</body>
</html>
