﻿function BindEmailConfiguration(otc, schemaname)
{
    RetrieveEmailTemplates(otc);
    BindEmailToDropdown(schemaname);
}

function RetrieveEmailTemplates(otc)
{
    DdlHelper.Clear('ddlEmailTemplate');

    var result = false;
    var fetchXml = '<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0">' +
                        '<entity name="template">' +
                            '<attribute name="title"/>' +
                            '<attribute name="templateid"/>' +
                            '<order descending="false" attribute="title"/>' +
                            '<filter type="and">' +
                                '<condition attribute="templatetypecode" value="' + otc + '" operator="eq"/>' +//112
                            '</filter>' +
                        '</entity>' +
                    '</fetch>';
    var ResultXml = GetFetchXmlResult(fetchXml);
    try
    {
        xmlDoc = $.parseXML(ResultXml);
    }
    catch (E)
    {
        alert(error_Xml);
        return;
    }
    $xml = $(xmlDoc);
    var XmlChildNodeList, emailTemplates;
    if (navigator.appName == "Netscape" && navigator.vendor == "Google Inc.")
    {
        XmlChildNodeList = $xml.find("Results").find("Entity");
        emailTemplates = ForChrome(XmlChildNodeList);
    }
    else
    {
        XmlChildNodeList = $xml.find("a\\:Results").find("a\\:Entity");
        emailTemplates = ForIEandFireFox(XmlChildNodeList);
    }

    //return emailTemplates;
    for (var i = 0; i < emailTemplates.length; i++)
    {
        $('#ddlEmailTemplate').append('<option value="' + emailTemplates[i].TemplateId + '">' + emailTemplates[i].Title + '</option>')
    }
}

function ForChrome(XMLEntityNodes)
{
    var templates = [];
    for (var i = 0; i < XMLEntityNodes.length; i++)
    {
        var KVPSanytype = XMLEntityNodes[i].getElementsByTagName("KeyValuePairOfstringanyType");
        templates[i] = new Object();
        for (var j = 0; j < KVPSanytype.length; j++)
        {
            if (KVPSanytype[j].getElementsByTagName("key")[0].textContent == "templateid")
            {
                templates[i].TemplateId = KVPSanytype[j].getElementsByTagName("value")[0].textContent;
            }
            if (KVPSanytype[j].getElementsByTagName("key")[0].textContent == "title")
            {
                templates[i].Title = KVPSanytype[j].getElementsByTagName("value")[0].textContent;
            }
        }
    }
    return templates;
}

function ForIEandFireFox(XMLEntityNodes)
{
    var templates = [];
    for (var i = 0; i < XMLEntityNodes.length; i++)
    {
        var KVPSanytype = XMLEntityNodes[i].getElementsByTagName("a:KeyValuePairOfstringanyType");
        templates[i] = new Object();
        for (var j = 0; j < KVPSanytype.length; j++)
        {
            if (KVPSanytype[j].getElementsByTagName("b:key")[0].textContent == "templateid")
            {
                templates[i].TemplateId = KVPSanytype[j].getElementsByTagName("b:value")[0].textContent;
            }
            if (KVPSanytype[j].getElementsByTagName("b:key")[0].textContent == "title")
            {
                templates[i].Title = KVPSanytype[j].getElementsByTagName("b:value")[0].textContent;
            }
        }
    }
    return templates;
}

function GetFetchXmlResult(sFetchXml)
{
    var request = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    request += "<s:Body>";
    request += '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services">' +
'<request i:type="b:RetrieveMultipleRequest" ' +
' xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" ' +
' xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +
'<b:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' +
    '<b:KeyValuePairOfstringanyType>' +
        '<c:key>Query</c:key>' +
        '<c:value i:type="b:FetchExpression">' +
            '<b:Query>';
    request += CrmEncodeDecode.CrmXmlEncode(sFetchXml);
    request += '</b:Query>' +
        '</c:value>' +
    '</b:KeyValuePairOfstringanyType>' +
'</b:Parameters>' +
'<b:RequestId i:nil="true"/>' +
'<b:RequestName>RetrieveMultiple</b:RequestName>' +
'</request>' +
'</Execute>';
    request += '</s:Body></s:Envelope>';

    var xmlhttp;
    if (navigator.appName == "Microsoft Internet Explorer")
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    else
        xmlhttp = new XMLHttpRequest();

    xmlhttp.open("POST", GetGlobalContext().getClientUrl() + "/XRMServices/2011/Organization.svc/web", false);
    xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
    xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    xmlhttp.send(request);

    var resultXml = xmlhttp.responseXML;

    if (navigator.appName == "Microsoft Internet Explorer")
        var xmlText = resultXml.xml || resultXml.activeElement.innerHTML;
    else
        var xmlText = (new XMLSerializer()).serializeToString(resultXml);
    return xmlText;
}

function SetUi()
{
    if (IsCRM2013())
    {
        $('.dynamic-col').width(145);
        $('#tblEmailConfig').css({ 'width': '100%' });
        if ($.browser.webkit) //($.browser.chrome)
            $('#tblEmailConfig').css({ 'margin-top': '-5px' });
        else
            $('#tblEmailConfig').css({ 'margin-top': '-3px' });
    }
    else
    {
        $('#tblEmailConfig').css({ 'table-layout': 'fixed' });
        $('#tblEmailConfig').css({ 'margin-top': '-3px' });
        $('#tblEmailConfig').css({ 'margin-left': '-4px' });
        $('#tblEmailConfig').css({ 'width': '102%' });
        $('.dynamic-col').width(110);
    }
}

function BindEmailToDropdown(schemaname)
{
    DdlHelper.Clear('ddlEmailTo');
    //SDK.Metadata.RetrieveEntity(SDK.Metadata.EntityFilters.Attributes, schemaname, null, false, successRetrieveEntity, errorRetrieveEntity);

    var requestMain = ""
    requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    requestMain += "  <s:Body>";
    requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
    requestMain += "      <request i:type=\"a:RetrieveEntityRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
    requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <b:key>EntityFilters</b:key>";
    requestMain += "            <b:value i:type=\"c:EntityFilters\" xmlns:c=\"http://schemas.microsoft.com/xrm/2011/Metadata\">Relationships</b:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <b:key>MetadataId</b:key>";
    requestMain += "            <b:value i:type=\"c:guid\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/\">00000000-0000-0000-0000-000000000000</b:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <b:key>RetrieveAsIfPublished</b:key>";
    requestMain += "            <b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">false</b:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "          <a:KeyValuePairOfstringanyType>";
    requestMain += "            <b:key>LogicalName</b:key>";
    requestMain += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + schemaname + "</b:value>";
    requestMain += "          </a:KeyValuePairOfstringanyType>";
    requestMain += "        </a:Parameters>";
    requestMain += "        <a:RequestId i:nil=\"true\" />";
    requestMain += "        <a:RequestName>RetrieveEntity</a:RequestName>";
    requestMain += "      </request>";
    requestMain += "    </Execute>";
    requestMain += "  </s:Body>";
    requestMain += "</s:Envelope>";

    try
    {
        var req = new XMLHttpRequest();
    }
    catch (e)
    {
        var req = new ActiveXObject("Msxml2.XMLHTTP");
    }

    req.open("POST", prependOrgName("/XRMServices/2011/Organization.svc/web"), false);
    req.setRequestHeader("Accept", "application/xml, text/xml, */*");
    req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
    req.send(requestMain);

    if (req.responseXML)
    {

        var resolver = {
            s: "http://schemas.xmlsoap.org/soap/envelope/",
            a: "http://schemas.microsoft.com/xrm/2011/Contracts",
            b: "http://schemas.datacontract.org/2004/07/System.Collections.Generic",
            c: "http://schemas.microsoft.com/xrm/2011/Metadata"
        };

        var xmlDocument = XUI.Xml.LoadXml(req.responseText.replace('xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"', ''));
        var relationships = XUI.Xml.SelectNodes(xmlDocument, "/s:Envelope/s:Body/ExecuteResponse/ExecuteResult/a:Results/a:KeyValuePairOfstringanyType/b:value/c:ManyToOneRelationships/c:OneToManyRelationshipMetadata", resolver);

        if (relationships && relationships.length > 0)
        {
            retVal = [];
            for (var i = 0; i < relationships.length; i++)
            {
                var entityNode = XUI.Xml.SelectSingleNode(relationships[i], "./c:ReferencedEntity", resolver);
                var attrNode = XUI.Xml.SelectSingleNode(relationships[i], "./c:ReferencingAttribute", resolver);

                if (entityNode && XUI.Xml.GetText(entityNode) && attrNode && XUI.Xml.GetText(attrNode))
                {

                    var entityName = XUI.Xml.GetText(entityNode);
                    var attrName = XUI.Xml.GetText(attrNode);

                    if (attrName != "masterid" && attrName != "createdby" && attrName != "createdonbehalfby"
                        && attrName != "modifiedby" && attrName != "modifiedonbehalfby")
                    {

                        var isEmailableEntity = IsEmailableEntity(entityName);

                        if (isEmailableEntity)
                        {

                            var displayName = GetAttributeDisplayName(attrName, schemaname);

                            lblObject = {};
                            if (attrName == "regardingobjectid")
                                lblObject.Value = displayName + " - " + entityName;
                            else
                                lblObject.Value = displayName;
                            lblObject.Key = attrName;
                            lblObject.Number = i;
                            retVal.push(lblObject);

                            //    AddOptionToFieldNamePicklist(attrName, displayName);
                        }
                    }
                }
            }

            retVal.sort(CompareDictionary);
            var customerid = false;
            for (var i = 0; i < retVal.length; i++)
            {
                if (retVal[i].Key == "customerid" || retVal[i].Key == "parentcustomerid")
                {
                    if (!customerid)
                    {
                        customerid = true;
                        $('#ddlEmailTo').append('<option value="' + retVal[i].Key + '">' + retVal[i].Value + '</option>');
                    }
                }
                else
                    $('#ddlEmailTo').append('<option value="' + retVal[i].Key + '">' + retVal[i].Value + '</option>');
            }
        }
        OnFormtypeUpdate();
    }
}

function CompareDictionary(a, b)
{
    var x = a.Value.toLowerCase();
    var y = b.Value.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function GetAttributeDisplayName(attrName, entityName)
{

    var retVal = attrName;

    try
    {

        var requestMain = ""
        requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        requestMain += "  <s:Body>";
        requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        requestMain += "      <request i:type=\"a:RetrieveAttributeRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
        requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>MetadataId</b:key>";
        requestMain += "            <b:value i:type=\"c:guid\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/\">00000000-0000-0000-0000-000000000000</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>RetrieveAsIfPublished</b:key>";
        requestMain += "            <b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">false</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>EntityLogicalName</b:key>";
        requestMain += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + entityName + "</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>LogicalName</b:key>";
        requestMain += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + attrName + "</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "        </a:Parameters>";
        requestMain += "        <a:RequestId i:nil=\"true\" />";
        requestMain += "        <a:RequestName>RetrieveAttribute</a:RequestName>";
        requestMain += "      </request>";
        requestMain += "    </Execute>";
        requestMain += "  </s:Body>";
        requestMain += "</s:Envelope>";

        try
        {
            var req = new XMLHttpRequest();
        }
        catch (e)
        {
            var req = new ActiveXObject("Msxml2.XMLHTTP");
        }

        req.open("POST", prependOrgName("/XRMServices/2011/Organization.svc/web"), false);
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        req.send(requestMain);

        if (req.responseXML)
        {

            var resolver = {
                s: "http://schemas.xmlsoap.org/soap/envelope/",
                a: "http://schemas.microsoft.com/xrm/2011/Contracts",
                b: "http://schemas.datacontract.org/2004/07/System.Collections.Generic",
                c: "http://schemas.microsoft.com/xrm/2011/Metadata"
            };

            var xmlDocument = XUI.Xml.LoadXml(req.responseText.replace('xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"', ''));

            var labelNode = XUI.Xml.SelectSingleNode(xmlDocument, "s:Envelope/s:Body/ExecuteResponse/ExecuteResult/a:Results/a:KeyValuePairOfstringanyType/b:value/c:DisplayName/a:UserLocalizedLabel/a:Label", resolver);

            if (labelNode && XUI.Xml.GetText(labelNode))
            {

                retVal = XUI.Xml.GetText(labelNode);
            }
        }
    }
    catch (e)
    {
    }

    return retVal;
}

function IsEmailableEntity(entity)
{
    try
    {

        var retVal = false;

        if (entity == "account" || entity == "contact"
            || entity == "equipment" || entity == "lead"
            || entity == "queue" || entity == "systemuser")
        {

            return true;
        }

        var requestMain = ""
        requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        requestMain += "  <s:Body>";
        requestMain += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        requestMain += "      <request i:type=\"a:RetrieveEntityRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
        requestMain += "        <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>EntityFilters</b:key>";
        requestMain += "            <b:value i:type=\"c:EntityFilters\" xmlns:c=\"http://schemas.microsoft.com/xrm/2011/Metadata\">Attributes</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>MetadataId</b:key>";
        requestMain += "            <b:value i:type=\"c:guid\" xmlns:c=\"http://schemas.microsoft.com/2003/10/Serialization/\">00000000-0000-0000-0000-000000000000</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>RetrieveAsIfPublished</b:key>";
        requestMain += "            <b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">false</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "          <a:KeyValuePairOfstringanyType>";
        requestMain += "            <b:key>LogicalName</b:key>";
        requestMain += "            <b:value i:type=\"c:string\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">" + entity + "</b:value>";
        requestMain += "          </a:KeyValuePairOfstringanyType>";
        requestMain += "        </a:Parameters>";
        requestMain += "        <a:RequestId i:nil=\"true\" />";
        requestMain += "        <a:RequestName>RetrieveEntity</a:RequestName>";
        requestMain += "      </request>";
        requestMain += "    </Execute>";
        requestMain += "  </s:Body>";
        requestMain += "</s:Envelope>";

        try
        {
            var req = new XMLHttpRequest();
        }
        catch (e)
        {
            var req = new ActiveXObject("Msxml2.XMLHTTP");
        }

        req.open("POST", prependOrgName("/XRMServices/2011/Organization.svc/web"), false);
        req.setRequestHeader("Accept", "application/xml, text/xml, */*");
        req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
        req.send(requestMain);

        if (req.responseXML)
        {

            var resolver = {
                s: "http://schemas.xmlsoap.org/soap/envelope/",
                a: "http://schemas.microsoft.com/xrm/2011/Contracts",
                b: "http://schemas.datacontract.org/2004/07/System.Collections.Generic",
                c: "http://schemas.microsoft.com/2003/10/Serialization/"
            };

            var activityPartyNode = XUI.Xml.SelectSingleNode(req.responseXML, "//c:IsActivityParty", resolver);
            var emailAddressNode = XUI.Xml.SelectSingleNode(req.responseXML, "//c:LogicalName[text()='emailaddress']", resolver);

            if (activityPartyNode && XUI.Xml.GetText(activityPartyNode) == "true"
                && emailAddressNode)
            {

                retVal = true;
            }
        }

        return retVal;
    }
    catch (e)
    {
        return false;
    }
}

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));
}

function successRetrieveEntity(entityMetadata)
{
    var attributeArray = new Array(entityMetadata.Attributes.length);
    var data = entityMetadata.Attributes;
    var counter = 0;
    for (var i = 0; i < data.length; i++)
    {
        if (data[i].DisplayName != null && data[i].DisplayName.UserLocalizedLabel != null && data[i].AttributeType == "Lookup" && data[i].LogicalName.toLowerCase() != "masterid")
        {
            if (data[i].Targets[0] == "contact" || data[i].Targets[0] == "account")
            {
                attributeArray[i] = new Array(2);
                attributeArray[i][0] = data[i].LogicalName.toLowerCase();
                attributeArray[i][1] = data[i].DisplayName.UserLocalizedLabel.Label;
                attributeArray[i][2] = data[i].MetadataId;

                counter++;
            }
        }

        if (data[i].DisplayName != null && data[i].DisplayName.UserLocalizedLabel != null && data[i].AttributeType == "Owner")
        {
            attributeArray[i] = new Array(2);
            attributeArray[i][0] = data[i].LogicalName.toLowerCase();
            attributeArray[i][1] = data[i].DisplayName.UserLocalizedLabel.Label;
            attributeArray[i][2] = data[i].MetadataId;

            counter++;
        }

        if (data[i].DisplayName != null && data[i].DisplayName.UserLocalizedLabel != null && data[i].AttributeType == "Customer")
        {
            attributeArray[i] = new Array(2);
            attributeArray[i][0] = data[i].LogicalName.toLowerCase();
            attributeArray[i][1] = data[i].DisplayName.UserLocalizedLabel.Label;
            attributeArray[i][2] = data[i].MetadataId;

            counter++;
        }
    }
    attributeArray.sort(sortMultiDimensional);
    for (var i = 0; i < counter; i++)
    {
        $('#ddlEmailTo').append('<option metadataid= "' + attributeArray[i][2].toString() + '" value="' + attributeArray[i][0].toString() + '">' + attributeArray[i][1].toString() + '</option>')
    }
    OnFormtypeUpdate();
}

function errorRetrieveEntity(error)
{
    message.innerText = error.message;
}

function ddlEmailTo_OnChange()
{
    var value = $("#ddlEmailTo").val();
    parent.Xrm.Page.getAttribute('iotap_emailto').setValue(value);
}

function ddlEmailTemplate_OnChange()
{
    var value = $("#ddlEmailTemplate").val();
    parent.Xrm.Page.getAttribute('iotap_emailtemplate').setValue(value);
}

function OnFormtypeUpdate()
{
    var _formType = parent.Xrm.Page.ui.getFormType();
    if (_formType == FormType.UPDATE)
    {
        var emailTo = parent.Xrm.Page.getAttribute('iotap_emailto').getValue();
        var emailTemplate = parent.Xrm.Page.getAttribute('iotap_emailtemplate').getValue();
        DdlHelper.SelectDefault('ddlEmailTo', emailTo);
        DdlHelper.SelectDefault('ddlEmailTemplate', emailTemplate);
    }
}