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


var TargetEntity = {}; 

North52.TargetEntity.Disable= function() {  

$("#targetentity").attr("disabled", true);
};

North52.TargetEntity.Load= function(type, name, value, isreset) {  

   $("#targetentity").hide();

       
     if (type == 'insert')
        North52.TargetEntity.InsertRecord(name, value, isreset );
     else if (type == 'query')
        North52.TargetEntity.BuildTargetEntityDownhierarchy();
        
   
  };


North52.TargetEntity.InsertRecord = function(Name, Value, isReset ) {  

  $("select[id$=targetentity] > option").remove();
  if (isReset == true) {parent.Xrm.Page.data.entity.attributes.get("north52_targetentityproperty").setValue(""); }


  if (Name != Value)
  {
     N52.HTMLWebResourceHelper.InsertOptionSetItem("targetentity", Name,Value);
      
     North52.TargetEntity.DropDownChanged(Value);
        $('#loading-targetentity').hide(); 
        $('#targetentity').show(); 
   }
   else
   {
       SDK.Metadata.RetrieveEntity(SDK.Metadata.EntityFilters.Relationships, Value, null, false, function (entityMetadata) {North52.TargetEntity.successRetrieveAttributes (entityMetadata, Value); }, North52.TargetEntity.errorRetrieveAttributes);

   }


};

North52.TargetEntity.successRetrieveAttributes = function(entityMetadata, entityLogicalName) {  

     var entityDisplayName = entityMetadata.DisplayName.UserLocalizedLabel.Label;
     N52.HTMLWebResourceHelper.InsertOptionSetItem("targetentity", entityDisplayName ,entityLogicalName);
      
     North52.TargetEntity.DropDownChanged(entityLogicalName);
        $('#loading-targetentity').hide(); 
        $('#targetentity').show(); 

};

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

North52.TargetEntity.DropDownChanged= function(value) {  

try
{
    if (value != null && value!="")
    {  
       parent.Xrm.Page.data.entity.attributes.get("north52_targetentityname").setValue(value);
       
		North52.TargetProperty.Load("load", value, "north52_targetentityproperty", "false");
         
     }

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



North52.TargetEntity.BuildTargetEntityDownhierarchy= function() {  

try
{

    $("select[id$=targetentity] > option").remove();
    var querystringparams = parent.Xrm.Page.context.getQueryStringParameters();
    var guid = querystringparams['id'];

    if (guid  != undefined)
    {
    var serverUrl = N52.DialogHelpers.GetServerUrl();

    var oDataServer = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
   
    var oDataQuery = "north52_formuladetailSet?$select=north52_name,north52_Query&$filter=north52_formula_north52_formuladetail_Id/Id eq guid'" + guid + "' and north52_QueryType/Value eq 217890001";

     var oDataSelect = oDataServer + oDataQuery;

     $.ajax({
     type: "GET",
     contentType: "application/json; charset=utf-8",
     datatype: "json",
     url: oDataSelect,
     beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
     success: function (data, textStatus, XmlHttpRequest)
     {
            North52.TargetEntity.RetrieveEntityData(data.d);

     },
     error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + oDataSelect ); }
     });
    
   } 
   else {
          N52.HTMLWebResourceHelper.InsertOptionSetItem("targetentity", "No Target data found.","Note if you have just created a formula detail record then you will need to click the refresh button on the ribbon to view the data.");

 		  North52.TargetProperty.Load("clear");

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

   }

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

 }

};

North52.TargetEntity.RetrieveEntityData= function(Entity) {  

 try
 {

   if (Entity.results[0] == undefined)
   {
         N52.HTMLWebResourceHelper.InsertOptionSetItem("targetentity", "No Target data found.","Note if you have just created a formula detail record then you will need to click the refresh button on the ribbon to view the data.");

		 North52.TargetProperty.Load("clear");
    }
   else
   {
    var name  = Entity.results[0].north52_name;
    var query = Entity.results[0].north52_Query;

    var doc = N52.HTMLWebResourceHelper.GetXmlDocument(query);
    var entityNode = N52.HTMLWebResourceHelper.GetXmlNodes(doc , "//entity");
    var entityName = entityNode[0].attributes[0].value;

    N52.HTMLWebResourceHelper.InsertOptionSetItem("targetentity", name,name);

    var queryAttributes = '';
    var attributes = N52.HTMLWebResourceHelper.GetXmlNodes(doc , "//attribute");     
                  
   for (var i = 0; i < attributes.length; i++) 
   {
    var node = attributes [i];
    var value = node.attributes[0].value;
    queryAttributes += value + ',';
   
     }  
       queryAttributes = queryAttributes.substring(0, queryAttributes .length-1);

		North52.TargetProperty.Load("query", name, "north52_targetentityproperty", queryAttributes);

     }

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

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

  };