<html><head><title>North52 Formula Source Entity</title>

<style type="text/css">

html, body{
margin: 0px;
padding: 0px;
background-color: transparent;
}
</style>

<script src="ClientGlobalContext.js.aspx"></script>

<script type="text/javascript" src="north52_/javascript/jquery"></script>

<script type="text/javascript" src="north52_/javascript/JSON2"></script>

<script type="text/javascript" src="north52_/Javascript/sdk.metadata.js"></script>

<script type="text/javascript" src="north52_/javascript/north52.htmlwebresource.helper"></script>








<script id="scriptInit" type="text/javascript">

  $(document).ready(function () { SourceEntity.Initialize();
     });


if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

var SourceEntity = {}; 

SourceEntity.Entities;
SourceEntity.InitialLoad = true;
SourceEntity.CacheKey = 'EntityList52' + parent.Xrm.Page.context.getOrgUniqueName();

SourceEntity.Disable= function() {  
   $("#sourceentity").attr("disabled", true);
}

SourceEntity.Initialize = function() {  

  $('#loading').show(); 
  $("#sourceentity").hide();

     if ((parent.Xrm.Page.ui.getFormType() == 6) || ( parent.Xrm.Page.data.entity.attributes.get("north52_formulatype").getValue() == 217890017) )
            return;

        if (localStorage&& localStorage.getItem(SourceEntity.CacheKey ) != null)
         {
             var data = JSON.parse(localStorage.getItem(SourceEntity.CacheKey ));
              SourceEntity.successRetrieveAllEntitiesCache(data);
          }   
          else
          {
                  SDK.Metadata.RetrieveAllEntities(SDK.Metadata.EntityFilters.Entity, false, SourceEntity.successRetrieveAllEntities,SourceEntity.errorRetrieveAllEntities);
           }  
                              
};

SourceEntity.Sort = function(a, b) {  
   
   if (a.innerHTML == 'All Properties') {
       return -1;
  }
  else if (b.innerHTML == 'All Properties') {
     return 1;
  }

  return (a.innerHTML > b.innerHTML ) ? 1 : -1;
};


SourceEntity.GetEntityDisplayName= function(entitylogicalname, entityMetadataCollection) {  

   var entityDisplayName = "";

   for (var i = 0; i < entityMetadataCollection.length; i++)
   {
        var splitArray = entityMetadataCollection[i].split('|');
        var label =  splitArray[0]; 
        var logicalname =  splitArray[1]; 

        if (entitylogicalname == logicalname )
              entityDisplayName = label;

   }

return entityDisplayName;
};

SourceEntity.successRetrieveAllEntitiesCache = function(entityMetadataCollection) {  

  var currentLogicalName = "";
  var currentDisplayName  = "";

  for (var i = 0; i < entityMetadataCollection.length; i++)
  {   
        var splitArray = entityMetadataCollection[i].split('|');
        var label =  splitArray[0]; 
        var logicalname =  splitArray[1]; 

        N52.HTMLWebResourceHelper.InsertOptionSetItem("sourceentity", label,logicalname); 
  }

    $("#sourceentity option").sort(SourceEntity.Sort).appendTo("#sourceentity");
   
    //if ( parent.Xrm.Page.data.entity.attributes.get("north52_formulatype").getValue() == 217890016)  N52.HTMLWebResourceHelper.InsertOptionSetItem("sourceentity", 'None (global)','none');

    savedEntity = parent.Xrm.Page.getAttribute("north52_sourceentityname").getValue();
   
    if (savedEntity !== null && savedEntity !=="") {  
            $("#sourceentity").val(savedEntity);
             currentLogicalName = savedEntity;
             currentDisplayName  = SourceEntity.GetEntityDisplayName(currentLogicalName, entityMetadataCollection);
      }
      else
      {
         $("#sourceentity").val('account');
         currentLogicalName  = 'account'
         currentDisplayName  = SourceEntity.GetEntityDisplayName(currentLogicalName, entityMetadataCollection);
      }

    $('#loading').hide(); 
    $('#sourceentity').show(); 

    SourceEntity.DropDownChanged(currentLogicalName,currentDisplayName,true );


};

SourceEntity.successRetrieveAllEntities = function(entityMetadataCollection) {  

  var objCache = new Array();
  var currentLogicalName = "";
  var currentDisplayName = "";
  SourceEntity.Entities = entityMetadataCollection;

  for (var i = 0; i < entityMetadataCollection.length; i++)
  {
    var entity = entityMetadataCollection[i];
    var logicalname =  entity.LogicalName;

    var arraytoexclude = ["principalattributeaccessmap",
                                      "metric",
"rollupfield",
"goalrollupquery",
"principalobjectattributeaccess",
"applicationfile",
"dependency",
"activitypointer",
"dependencynode",
"invaliddependency",
"roletemplate",
"systemuserlicenses",
"lookupmapping",
"monthlyfiscalcalendar",
"businessunitnewsarticle",
"contracttemplate",
"isvconfig",
"sdkmessageprocessingstepsecureconfig",
"organization",
"workflowlog",
"customerrelationship",
"importmap",
"systemuserroles",
"north52_formuladetail",
"userquery",
"publisher",
"dataperformance",
"azureserviceconnection",
"customcontrol",
"customcontroldefaultconfig",
"customcontrolresource",
"userentityuisettings",
"north52_trace",
"uom",
"tracelog",
"traceassociation",
"traceregarding",
"userapplicationmetadata",
"msdyn_wallsavedquery",
"teamtemplate",
"partnerapplication",
"processstage",
"processtrigger",
"multientitysearch",
"mailbox",
"postlike",
"imagedescriptor",
"postfollow",
"exchangesyncidmapping",
"emailserverprofile",
"businessprocessflowinstance",
"authorizationserver",
"owner",
"stringmap",
"salesprocessinstance",
"msdyn_postconfig",
"msdyn_postruleconfig",
"notification",
"postregarding",
"postrole",
"commitment",
"replicationbacklog",
"msdyn_postalbum",
"campaignactivityitem",
"campaignitem",
"complexcontrol",
"roletemplateprivileges",
"mailmergetemplate",
"north52_xcache",
"timestampdatemapping",
"usermapping",
"teamsyncattributemappingprofiles",
"systemusermanagermap",
"syncattributemappingprofile",
"syncattribuemapping",
"msdyn_wallsavedqueryusersettings",
"mailboxtrackingfolder",
"north52_schedule",
"hierarchyrule",
"syncattributemapping",
"hierarchyruleconfiguration",
"hierarchysecurityconfiguration",
"businessdatalocalizedlabel",
"principalsyncattributemap",
"rollupjob",
"rollupproperties",
"ribboncustomization",
"teamprofiles",
"import",
"resourcegroupexpansion",
"workflowwaitsubscription",
"serviceendpoint",
"subscriptionsyncinfo",
"savedqueryvisualization",
"productsubstitute",
"recurrencerule",
"systemform",
"connectionroleassociation",
"report",
"teammembership",
"discount",
"solutioncomponent",
"plugintypestatistic",
"statusmap",
"documentindex",
"attributemap",
"sdkmessagepair",
"emailsearch",
"userfiscalcalendar",
"reportentity",
"timezonedefinition",
"uomschedule",
"reportlink",
"subscriptionclients",
"subscriptiontrackingdeletedobject",
"columnmapping",
"ownermapping",
"wizardpage",
"entitymap",
"unresolvedaddress",
"wizardaccessprivilege",
"bulkoperation",
"publisheraddress",
"webresource",
"businessunit",
"constraintbasedgroup",
"transformationmapping",
"role",
"connectionroleobjecttype",
"bulkdeleteoperation",
"solution",
"transformationparametermapping",
"sitemap",
"recommendationcache",
"recommendationmodelversion",
"recommendationmodelversionhistory",
"subscriptionstatisticsoffline",
"subscriptionstatisticsoutlook",
"subscriptionsyncentryoffline",
"subscriptionsyncentryoutlook",
"importfile",
"fieldpermission",
"bulkdeletefailure",
"productassociation",
"connectionrole",
"competitorsalesliterature",
"north52_configuration",
"timezonelocalizedname",
"systemuserprincipals",
"picklistmapping",
"webwizard",
"principalobjectaccess",
"reportcategory",
"bulkoperationlog",
"workflowdependency",
"sdkmessagerequest",
"clientupdate",
"customeropportunityrole",
"resource",
"principalentitymap",
"sdkmessagerequestfield",
"relationshiprolemap",
"north52_formulacalculation",
"reportvisibility",
"north52_formula",
"recurringappointmentmaster",
"importlog",
"sdkmessage",
"usersettings",
"relationshiprole",
"duplicaterecord",
"interprocesslock",
"businessunitmap",
"timezonerule",
"sdkmessagefilter",
"sdkmessageprocessingstepimage",
"calendarrule",
"sdkmessageresponse",
"importjob",
"resourcespec",
"site",
"plugintype",
"sdkmessageprocessingstep",
"duplicaterulecondition",
"teamroles",
"subscriptionmanuallytrackedobject",
"duplicaterule",
"sharepointsite",
"audit",
"semiannualfiscalcalendar",
"discounttype",
"userform",
"privilege",
"importdata",
"organizationui",
"pluginassembly",
"resourcegroup",
"asyncoperation",
"team",
"integrationstatus",
"sdkmessageresponsefield",
"fieldsecurityprofile",
"savedquery",
"privilegeobjecttypecodes",
"displaystringmap",
"sharepointdocumentlocation",
"emailhash",
"fixedmonthlyfiscalcalendar",
"displaystring",
"activityparty",
"roleprivileges",
"organizationstatistic",
"subscription",
"systemuserprofiles",
"filtertemplate",
"convertrule",
"convertruleitem",
"childincidentcount",
"dependencyfeature",
"entitlementtemplate",
"entitlementtemplatechannel",
"mailboxstatistics",
"metadatadifference",
"queueitemcount",
"queuemembercount",
"routingrule",
"routingruleitem",
"socialinsightsconfiguration",
"systemapplicationmetadata",
"socialactivity",
"socialprofile",
"kbarticletemplate",
"internaladdress",
"userentityinstancedata",
"license",
"userqueryvisualization",
"importentitymapping",
"productsalesliterature",
"annualfiscalcalendar",
"systemuserbusinessunitentitymap",
"ribbontabtocommandmap",
"ribboncontextgroup",
"ribboncommand",
"ribbonrule",
"ribbondiff",
"competitor",
"competitorsalesliterature",
"competitoraddress",
"competitorproduct",
"connectionroleassociation",
"connectionroleobjecttypecode",
"quarterlyfiscalcalendar",
"workflow",
"resource"];

    var index = arraytoexclude.indexOf(logicalname);
    var isbusinessprocessenabled = ''; 
    var primaryidattribute = entity.PrimaryIdAttribute;
    if (entity.IsBusinessProcessEnabled != null)    
          isbusinessprocessenabled = entity.IsBusinessProcessEnabled;
  
       if (index == -1)
       {
          if (entity.DisplayName.UserLocalizedLabel != null)    
          {
             if (entity.DisplayName.UserLocalizedLabel.Label != null)
              {
                   var label = entity.DisplayName.UserLocalizedLabel.Label;  

                   if (currentLogicalName == "") { currentLogicalName = logicalname;}
                   if (currentDisplayName == "") { currentDisplayName = label;}

                    N52.HTMLWebResourceHelper.InsertOptionSetItem("sourceentity", label,logicalname);
                    objCache.push(label + "|" + logicalname + "|" + isbusinessprocessenabled + "|" + primaryidattribute);
                  
               }
             }
           }
   }
   

     if (localStorage)
    {

       try
       {
         var stringEntityList = JSON.stringify(objCache);
         localStorage.setItem(SourceEntity.CacheKey , stringEntityList);
      }
       catch(ex)
       {
          localStorage.removeItem(SourceEntity.CacheKey); 
        }

      }



    $("#sourceentity option").sort(SourceEntity.Sort).appendTo("#sourceentity");
   
    savedEntity = parent.Xrm.Page.getAttribute("north52_sourceentityname").getValue();

 
    if (savedEntity !== null && savedEntity !=="") {  
            $("#sourceentity").val(savedEntity);
             currentLogicalName = savedEntity;
             currentDisplayName  = SourceEntity.GetEntityDisplayName(currentLogicalName, objCache);
      }
      else
      {
         $("#sourceentity").val('account');
         currentLogicalName  = 'account'
         currentDisplayName  = SourceEntity.GetEntityDisplayName(currentLogicalName, objCache);
      }

    $('#loading').hide(); 
    $('#sourceentity').show(); 

    SourceEntity.DropDownChanged(currentLogicalName,currentDisplayName,true );
 
};


SourceEntity.errorRetrieveAllEntities = function(error) {  
    alert("North52 Formula Manager : " + error.message);
  }

SourceEntity.DropDownChanged= function(value, display, initialLoad) {  

try
{

    if (value !== null && value!=="" && value !== 'none') {  
       isReset = false; 
       parent.Xrm.Page.data.entity.attributes.get("north52_sourceentityname").setValue(value);
       parent.Xrm.Page.data.entity.attributes.get("north52_sourceentityname").fireOnChange();

       display = display.indexOf('&') > 0 ? display.replace('&', '^^^') : display;        

       if (typeof initialLoad === 'undefined')  initialLoad = false;
       if (initialLoad == false) {SourceEntity.ResetValues();  isReset = true;}     

       var url = parent.Xrm.Page.ui.controls.get('WebResource_html_metadata_sourceproperty').getSrc();
       url = url.indexOf('?') > 0 ? url.substring(0, url.indexOf('?')) : url;

       var command = encodeURIComponent("parentReferenceProperty=north52_sourceentityproperty&allProperties=true&initialLoad=" +initialLoad + "&random=" + Math.random());
       url = url + "?data=" +command;
       parent.Xrm.Page.ui.controls.get("WebResource_html_metadata_sourceproperty").setSrc(url);
       
       formulaType = parent.Xrm.Page.data.entity.attributes.get("north52_formulatype").getValue();

   
         //save parent
         if (  ( formulaType  != 217890001999)  )
         { 

                    var url = parent.Xrm.Page.ui.controls.get('WebResource_html_sourcerelationship').getSrc();
                    url = url.indexOf('?') > 0 ? url.substring(0, url.indexOf('?')) : url;

                    command = encodeURIComponent("display="+display + "&value=" + value + "&initialLoad=" + initialLoad + "&random=" + Math.random());
                    url = url + "?data=" +command;

                    parent.Xrm.Page.ui.controls.get('WebResource_html_sourcerelationship').setSrc(url);

          }

        //save current autonumber
        if ( formulaType  == 217890003 || formulaType  == 217890005)
          { 
                     var url = parent.Xrm.Page.ui.controls.get('WebResource_html_targetentity').getSrc();
                    url = url.indexOf('?') > 0 ? url.substring(0, url.indexOf('?')) : url;

                    command = encodeURIComponent("type=insert&display="+display + "&value=" + value + "&isReset=" + isReset + "&random=" + Math.random());
                    url = url + "?data=" +command;

                    parent.Xrm.Page.ui.controls.get('WebResource_html_targetentity').setSrc(url);
          }

     }
}
catch(ex)
{
   alert('North52 Formula Manager: Communication issue, please click Ok & then F5 to refresh the screen. Message: ' + ex.message);
}

} ; 

SourceEntity.ResetValues = function(value) {  

       parent.Xrm.Page.data.entity.attributes.get("north52_sourceentityproperty").setValue("");
       parent.Xrm.Page.data.entity.attributes.get("north52_sourcerelationship").setValue("");
       parent.Xrm.Page.data.entity.attributes.get("north52_targetentityname").setValue("");
       parent.Xrm.Page.data.entity.attributes.get("north52_targetentityproperty").setValue("");
       parent.Xrm.Page.data.entity.attributes.get("north52_sourceentitypropertyclientside").setValue("");
} ; 


</script>

<style type="text\css">
#loading { 
  width: 100%; 
  height: 100%; 
  top: 0px; 
  left: 0px; 
  position: fixed; 
  display: block; 
  opacity: 0.7; 
  background-color: #fff; 
  z-index: 99; 
  text-align: center; 
} 
 
#loading-image { 
  position: absolute; 
  top: 100px; 
  left: 240px; 
  z-index: 100; 
}



</style>

<meta charset="utf-8">
<meta><meta></head><body style="word-wrap: break-word;">&nbsp;</body></html>