﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
<link rel="stylesheet" type="text/css" href="../Styles/Crmstyle.css" /> 
<script type="text/javascript" src="../Scripts/jquery1.9.1.js"></script>
    <script type="text/javascript" src="../Scripts/json.js"></script>
<script src="../../../ClientGlobalContext.js.aspx"></script>
<script type="text/javascript">

    var webApiUrl = window.parent.Xrm.Page.context.getClientUrl() + "/api/data/v8.0/";
    var FORM_CREATE = 1;
    var FORM_QUICK_CREATE = 5;
    var AccountAtrributeArray = null;
    var ContactAttributeArray = null;
    var XRM = window.parent.Xrm; //Page.getAttribute('iotap_contactattribute').getValue()

    window.onload = function ()
    {
       //RetrieveOptionSetAttributeMetadata( "608861bc-50a4-4c5f-a02c-21fe1943e2cf", "contact" );
       //RetrieveOptionSetAttributeMetadata( "70816501-edb9-4740-a16c-6a5efbc05d84", "account" );


        RetrieveOptionSetAttributeMetadata("contact");
        RetrieveOptionSetAttributeMetadata("account" );
        
    }

    function CaseOwnerOverrideOptions() {
        var ownerOverrideOption = XRM.Page.getAttribute('iotap_caseowneroverride').getValue();
        //var control = XRM.Page.ui.controls.get("WebResource_GetAccountContactAttributes");
        switch (ownerOverrideOption) {
            case 1:
                $('#SelectContactAttribute').attr('disabled', 'disabled');
                $('#SelectAccountAttribute').attr('disabled', 'disabled');
                break;

            case 2:
                //RetrieveOptionSetAttributeMetadata("contact");
                //RetrieveOptionSetAttributeMetadata("account");
                $('#SelectContactAttribute').attr('enabled', 'enabled');
                $('#SelectAccountAttribute').attr('enabled', 'enabled');
                break;

            default:
                $('#SelectContactAttribute').attr('disabled', 'disabled');
                $('#SelectAccountAttribute').attr('disabled', 'disabled');
                break;
        }

    }
    
    function RetrieveOptionSetAttributeMetadata(entityName)
    {   
        var counter = 0;
        var AttributeArray = [];
        var attriArray = [];
        var filterQuery = "EntityDefinitions(LogicalName='" + entityName +"')?$select=LogicalName&$expand=Attributes($filter=AttributeType eq Microsoft.Dynamics.CRM.AttributeTypeCode'Lookup')";
        var isexecute = false;

        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: webApiUrl + filterQuery,
            beforeSend: function (XMLHttpRequest) {
                //Specifying this header ensures that the results will be returned as JSON.
                XMLHttpRequest.setRequestHeader("Accept", "application/json");
                XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
                XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
                XMLHttpRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            },
            success: function (data, textStatus, XmlHttpRequest) {

                var convertedData = window.JSON.stringify(data);
  
                return convertedData;
            },
            error: function (xhr, textStatus, errorThrown) {
                Xrm.Utility.alertDialog(textStatus + " " + errorThrown);
            }
        }).then(function (data)
        {
            for (var i = 0; i < data.Attributes.length; i++) {
                if (data.Attributes[i].SchemaName != null && data.Attributes[i].DisplayName != null && data.Attributes[i].DisplayName.UserLocalizedLabel != null && data.Attributes[i].AttributeType == "Lookup" && (data.Attributes[i].Targets[0] == "systemuser" || data.Attributes[i].Targets[0] == "team")) {
                    attriArray[i] = new Array(2);
                    attriArray[i][0] = data.Attributes[i].SchemaName.toLowerCase();
                    attriArray[i][1] = data.Attributes[i].DisplayName.UserLocalizedLabel.Label;
                    counter++;
                }
            }

            for (var i = 0; i < attriArray.length; i++) {
                if (entityName == "contact") {
                    try {
                        $('#SelectContactAttribute').append('<option  value="' + attriArray[i][0].toLowerCase() + '">' + attriArray[i][1].toString() + '</option>')
                    }
                    catch (err) {

                    }
                }else if (entityName == "account") {
                    try {
                        $('#SelectAccountAttribute').append('<option  value="' + attriArray[i][0].toLowerCase() + '">' + attriArray[i][1].toString() + '</option>')
                    }
                    catch (err) {

                    }

                }


            }

            if (window.parent.Xrm.Page.getAttribute('iotap_contactattribute').getValue() != null) {
                $('#SelectContactAttribute').val(XRM.Page.getAttribute('iotap_contactattribute').getValue().toLowerCase());
            }

            if (window.parent.Xrm.Page.getAttribute('iotap_accountattribute').getValue() != null) {
                $('#SelectAccountAttribute').val(XRM.Page.getAttribute('iotap_accountattribute').getValue().toLowerCase());
            }

            CaseOwnerOverrideOptions()

        });

        return isexecute;
         
    }
       
    //////////////***************Retrieve & Load Contact & Account Attributes (Systemuser & team Lookup Fields) End********************///////////////////
    function UpdateAttribute() {
        var selectedContactAttribute = SelectContactAttribute.value;
        var selectedAccountAttribute = SelectAccountAttribute.value;
        var contactField = "iotap_contactattribute";
        var accountField = "iotap_accountattribute";
        XRM.Page.getAttribute(contactField).setValue(selectedContactAttribute);
        XRM.Page.getAttribute(accountField).setValue(selectedAccountAttribute);
    }

    
    function sortMultiDimensional(a, b) {
        // for instance, this will sort the array using the second element
        return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
    }

</script>
    <style type="text/css">
        .label
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            font-weight: normal;
        }
        .label1
        {
            font-family: Segoe UI, Tahoma, Arial;
            font-size: 11px;
            font-weight: normal;
            color: Red;
        }
        .body
        {
            margin-left: 0px;
            margin-top: 0px;
            margin-right: 0px;
            margin-bottom: 0px;
            background-color: White;
            padding: 0px;
        }
        .style1
        {
            width: 8%;
        }
        .style2
        {
            width:42%;
        }
        .style3
        {
            padding-left:10px;
            width: 8%;
        }
    </style>
</head>
<body style="width:100%;margin:0 0 0 0;padding:0 0 0 0;">
<table style="width: 100%; border-style: none; table-layout: fixed;" cellpadding="0"
        cellspacing="0">
<colgroup>
            <col width="108">
            <col>
            <col width="123">
            <col>
            <tbody>
        <tr>
            <td align="left"style="width:8%">
                <label class="label">Contact (Override)</label></td>
            <td align="right" width="42%" >
                <select id="SelectContactAttribute" class="ms-crm-SelectBox" name="D1" onchange="UpdateAttribute()" >
                    <option ></option>
                </select></td>
            <td align="left"style="padding-left:15px; width:8%;">
            <label class="label">Account (Override)</label></td>
            <td align="right" style=" width:42%;">
                <select id="SelectAccountAttribute" class="ms-crm-SelectBox" name="D2" onchange="UpdateAttribute()" >
                    <option ></option>
                </select></td>
        </tr>
        </tbody>
        </table>
</body>
</html>
