if (typeof North52 == 'undefined') { North52 = {}; }
if (typeof North52.SourceEntity == 'undefined') { North52.SourceEntity = {}; } 


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 = '';


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

North52.SourceEntity.Initialize = function() {   

  $('#loading-sourceentity').show(); 
  $("#sourceentity").hide();
  SourceEntity.CacheKey = 'EntityList52' + North52.SourceEntity.XrmParent().Page.context.getOrgUniqueName();
  


     if (North52.SourceEntity.XrmParent().Page.ui.getFormType() == 6)
		return;

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

North52.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;
};


North52.SourceEntity.GetEntityDisplayName= function(entitylogicalname, entityMetadataCollection) {  

    var entityDisplayName = "";
   if (entitylogicalname == null) entitylogicalname = 'account';
   if (entityMetadataCollection == null) return entitylogicalname;

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

North52.SourceEntity.successRetrieveAllEntitiesCache = function(entityMetadataCollection) {  

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

  if (SourceEntity.InitialLoad == true)
  {
	  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(North52.SourceEntity.Sort).appendTo("#sourceentity");
   

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

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

    North52.SourceEntity.DropDownChanged(currentLogicalName,currentDisplayName, SourceEntity.InitialLoad );
    SourceEntity.InitialLoad = false;


};

North52.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",
"bookableresourcebookingexchangesyncidmapping",
"north52_formuladetail",
"userquery",
"publisher",
"dataperformance",
"azureserviceconnection",
"customcontrol",
"customcontroldefaultconfig",
"customcontrolresource",
"userentityuisettings",
"north52_trace",
"uom",
"tracelog",
"traceassociation",
"traceregarding",
"userapplicationmetadata",
"msdyn_wallsavedquery",
"teamtemplate",
"partnerapplication",
"processstage",
"processtrigger",
"localconfigstore",
"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",
"attachment",
"integrationstatus",
"sdkmessageresponsefield",
"fieldsecurityprofile",
"savedquery",
"orginsightsmetric",
"plugintracelog",
"savedorginsightsconfiguration",
"privilegeobjecttypecodes",
"displaystringmap",
"advancedsimilarityrule",
"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",
"attachment",
"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(North52.SourceEntity.Sort).appendTo("#sourceentity");
   
    savedEntity = North52.SourceEntity.XrmParent().Page.getAttribute("north52_sourceentityname").getValue();

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

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

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


North52.SourceEntity.errorRetrieveAllEntities = function(error) {  
    alert("North52 Formula Manager : " + error.message);
  };
  
  
   North52.SourceEntity.XrmParent = function() {  
                    return window.parent.Xrm;
    };
    
     North52.SourceEntity.JSParent = function() {  
           return window;
    };
    
North52.SourceEntity.DropDownChanged= function(value, display, initialLoad) {  

try
{

    if (value !== null && value!=="" && value !== 'none') 
    {  
       isReset = false; 
       North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_sourceentityname").setValue(value);
       North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_sourceentityname").fireOnChange();
       North52.SourceEntity.JSParent().$("#sourceentity").val(value);

       if (North52.SourceEntity.IsFormulaEntity() == false)
      {
           return;
      }


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

       if (typeof initialLoad === 'undefined')  initialLoad = false;
       if (initialLoad == false) {North52.SourceEntity.ResetValues();  isReset = true;}     
       
       var entityName = North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_sourceentityname").getValue();
        North52.SourceEntity.JSParent().North52.MetadataProperty.Load(entityName, "north52_sourceentityproperty", "true", initialLoad);


       var formulaType = $("#formulaType").val();
   
         //save parent
         if (formulaType == 217890001 )  
         {
         	North52.SourceEntity.JSParent().North52.SourceRelationship.Load(display, value, initialLoad );
         }
 
          
        //save current and autonumber
        if (formulaType == 217890003 || formulaType  == 217890005)
        {
			North52.SourceEntity.JSParent().North52.TargetEntity.Load("insert", display, value, isReset);
	    }

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

} ; 

North52.SourceEntity.IsFormulaEntity = function () {

    if (North52.SourceEntity.XrmParent().Page.data.entity.getEntityName() == 'north52_formula')
        return true;
    else
        return false;

};

North52.SourceEntity.ResetValues = function(value) {  

      if (North52.SourceEntity.IsFormulaEntity() == false)
      {
           return;
      }

       North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_sourceentityproperty").setValue("");
       North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_sourcerelationship").setValue("");
       North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_targetentityname").setValue("");
       North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_targetentityproperty").setValue("");
       North52.SourceEntity.XrmParent().Page.data.entity.attributes.get("north52_sourceentitypropertyclientside").setValue("");
} ; 
