<HTML><HEAD><TITLE>North52 Formula Manager Formula Detail Relationship</TITLE>
<SCRIPT src="ClientGlobalContext.js.aspx"></SCRIPT>

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

<SCRIPT type=text/javascript src="north52_/javascript/north52_dialog_helper"></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 type=text/javascript src="north52_/javascript/north52.formula.load">



</SCRIPT>
<LINK rel=stylesheet type=text/css href="/_common/styles/fonts.css.aspx?lcid=1033"><LINK rel=stylesheet type=text/css href="/_common/styles/global.css.aspx?lcid=1033"><LINK rel=stylesheet type=text/css href="/_common/styles/select.css.aspx?lcid=1033">
<SCRIPT type=text/javascript>

var Settings = {};  
Settings.CurrentRelationship = ""; 
Settings.SourceEntity = ""; 
Settings.TargetEntity = ""; 

var SourceRelationship = {}; 


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

SourceRelationship.Init= function() {  
 SourceRelationship.CallFormulaSourceTarget();
 
}


SourceRelationship.Sort = function(a, b) {  
   
  return (a.innerHTML > b.innerHTML ) ? 1 : -1;
}

SourceRelationship.Load = function(entityDisplayName, entityLogicalName, IsFromPageLoad) {  

 //Retrieve attributes
     SDK.Metadata.RetrieveEntity(SDK.Metadata.EntityFilters.Relationships, entityLogicalName, null, false, function (entityMetadata) {
SourceRelationship.successRetrieveAttributes(entityMetadata, entityDisplayName, IsFromPageLoad); }, SourceRelationship.errorRetrieveAttributes);

};

SourceRelationship.successRetrieveAttributes = function(entityMetadata, entityDisplayName, IsFromPageLoad) {  

var filterEntity = "";
$("select[id$=sourcerelationship] > option").remove();

filterType = parent.Xrm.Page.data.entity.attributes.get("north52_filter").getValue();

if (filterType == 217890001)
   filterEntity = Settings.SourceEntity;
else if (filterType == 217890002)
 filterEntity = Settings.TargetEntity;
else
{
    N52.HTMLWebResourceHelper.InsertOptionSetItem("sourcerelationship", "Click here to refresh if an Advanced Find query has been created.","");

   return;
}

if (entityMetadata.ManyToOneRelationships!= null)
{
 
 for (var i = 0; i < entityMetadata.ManyToOneRelationships.length; i++)
 {
   var relationship = entityMetadata.ManyToOneRelationships[i];

   var txt = relationship.ReferencedEntity;
   var val = relationship.ReferencingAttribute;
   
   text = val + " (" + txt + ")";
   value = val+"|"+txt;
   if (filterEntity == txt) {
      N52.HTMLWebResourceHelper.InsertOptionSetItem("sourcerelationship", text,value);
    }
  }  

 }

    if ($('select#sourcerelationship option').length == 0) {
           var msg = "No relationship exists on the " + Settings.CurrentRelationship + " entity relating to the " + filterEntity + " entity.";
           N52.HTMLWebResourceHelper.InsertOptionSetItem("sourcerelationship", msg,"");
     }
       var filterentityname = parent.Xrm.Page.getAttribute("north52_filterentityname").getValue();
      var filterattributename = parent.Xrm.Page.getAttribute("north52_filterattributename").getValue();
      var currentValue = filterattributename + "|" + filterentityname ;
   
    if ((filterentityname != null ) && (filterattributename != null) && (IsFromPageLoad =='true' )){
        $("#sourcerelationship").val(currentValue );
        SourceRelationship.DropDownChanged(currentValue);    
    }
    else {
       $('#sourcerelationship option:first-child').attr("selected", "selected");        
       currentValue = $("#sourcerelationship option:selected").val();
       SourceRelationship.DropDownChanged(currentValue);    
     }
    
};

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

SourceRelationship.DropDownChanged= function(value) {  
  if (value !== null) {  

           var split = value.split("|");
          attribute = split[0];
           entity = split[1];
          parent.Xrm.Page.data.entity.attributes.get("north52_filterentityname").setValue(entity);   
          parent.Xrm.Page.data.entity.attributes.get("north52_filterattributename").setValue(attribute);   
       }


  } ; 

SourceRelationship.OnClick = function(IsFromPageLoad) {  

  var fetchxml = "";
  var fetchxmlAdvancedFind = "";
  var fetchxmlSaved = parent.Xrm.Page.getAttribute("north52_query").getValue();

  if (IsFromPageLoad == 'false') 
  {
     //fetchxmlAdvancedFind = parent.document.getElementById("IFRAME_advancedfind").contentWindow.document.getElementById("contentIFrame").contentWindow.document.getElementById("resultRender").FetchXml.value; 
     fetchxmlAdvancedFind = parent.Xrm.Page.data.entity.attributes.get("north52_query").getValue() ;
  }


   if (fetchxmlAdvancedFind != "")   {
      fetchxml =  fetchxmlAdvancedFind;
   }
   else  {
      fetchxml =  fetchxmlSaved;
   }

   if ((fetchxml != "") && (fetchxml != null))
   {

       var doc = N52.HTMLWebResourceHelper.GetXmlDocument(fetchxml);
       var entityNode = N52.HTMLWebResourceHelper.GetXmlNodes(doc , "//entity");

       
       var entityName = entityNode[0].attributes[0].value;
       var entityFilterName = parent.Xrm.Page.data.entity.attributes.get("north52_filterentityname").getValue() ;

        if ((Settings.CurrentRelationship != entityName) || (entityFilterName == "") || (entityFilterName == null)) {
                         Settings.CurrentRelationship = entityName;
                         SourceRelationship.Load(entityName,entityName, IsFromPageLoad);
        }
     }
    else {
         $("select[id$=sourcerelationship] > option").remove();
         N52.HTMLWebResourceHelper.InsertOptionSetItem("sourcerelationship", "Click here to refresh if an Advanced Find query has been created.","");
    }
      

} ; 

SourceRelationship.CallFormulaSourceTarget = function() {  

    var querystringparams = parent.Xrm.Page.context.getQueryStringParameters();
    var lookupFormula = parent.Xrm.Page.data.entity.attributes.get("north52_formula_north52_formuladetail_id").getValue();

    var guid = lookupFormula[0].id;
    guid = guid.replace("{", "");
    guid = guid.replace("}", "");

    if (guid  != undefined)
    {
    var serverUrl = N52.DialogHelpers.GetServerUrl();
    var oDataServer = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
   
    var oDataQuery = "north52_formulaSet?$select=north52_SourceEntityName,north52_TargetEntityName&$filter=north52_formulaId eq guid'" + guid + "'";

     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)
     {
            SourceRelationship.SetFormulaSourceTarget (data.d);

     },
     error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + oDataSelect ); }
     });
    
   } 
  

};

SourceRelationship.SetFormulaSourceTarget = function(Entity) {  

   if (Entity.results[0] == undefined)
   {
        alert("North52 Formula Manager - Could not find formula.");
    }
   else
   {
    var source = Entity.results[0].north52_SourceEntityName;
    var target = Entity.results[0].north52_TargetEntityName;
  
    Settings.SourceEntity = source;
    Settings.TargetEntity = target;

    //Part of the init process
    SourceRelationship.OnClick('true');

   }

};

</SCRIPT>
</STYLE>
<META charset=utf-8></HEAD>
<BODY onload=SourceRelationship.Init() bgColor=transparent>
<DIV id=container>
<DIV id=main><SELECT style="WIDTH: 100%; IME-MODE: auto" id=sourcerelationship onchange=SourceRelationship.DropDownChanged(this.value) class=ms-crm-SelectBox onclick="SourceRelationship.OnClick('false')"></SELECT> </DIV></DIV></BODY></HTML>