if (typeof (N52) == "undefined")
{ N52 = {}; } 

N52.FormulaSave =
{    

SaveFormula: function (executionContext)
{
  try
  {

    if (N52.FormulaSave.CheckSave(executionContext) == false)
         return;

  
   Xrm.Page.getControl("WebResource_formulaeditor").getObject().contentWindow.window.SaveFormula();
   
   N52.FormulaSave.SetClientSidePayLoad();
   
    N52.FormulaSave.SetDefaultName();

   
  }
  catch(ex)
  {
    alert("North52 Formula Manager Exception: " + ex.message);
  } 

},


CheckSave: function (executionContext)
{
   var eventArgs = executionContext.getEventArgs(); 
    if (eventArgs.getSaveMode() == 70) {
        eventArgs.preventDefault();
        return false;
    }
 
    if (eventArgs.getSaveMode() == 2) {
        eventArgs.preventDefault();
        return false;
    }
   
    
    return true;
},

SetDefaultName: function ()
{

   if ((Xrm.Page.ui.getFormType() == 1) && (Xrm.Page.data.entity.attributes.get("north52_formulatype").getValue() != 217890017) )
   {
      name = Xrm.Page.getAttribute('north52_sourceentityname').getValue();
      name = name + " - " + Xrm.Page.getAttribute("north52_formulatype").getText();
      name = name + " - " + new Date();
      Xrm.Page.getAttribute('north52_name').setValue(name);
   }
},

SetClientSidePayLoad: function ()
{
    var existingPayLoad =  Xrm.Page.getAttribute('north52_clientsidedatapayload').getValue();
   if ((existingPayLoad == null) || (existingPayLoad == '') )
         existingPayLoad = '*'; 
   else
        existingPayLoad = existingPayLoad.split(':')[0];

   var additionalEvents = '';
   if ((Xrm.Page.getAttribute('north52_sourceentitypropertyclientside').getValue() != null) && (Xrm.Page.getAttribute('north52_sourceentitypropertyclientside').getValue().indexOf('.onload.stageid') > -1 ))
       additionalEvents = ':stageid';
   else
       additionalEvents = ':';  
       
   var saveMode = ':' + Xrm.Page.getControl("WebResource_formulaeditor").getObject().contentWindow.window.GetSaveModeInfo();
   
   if  ((Xrm.Page.data.entity.attributes.get("north52_pipelineevent").getValue() == 217890000)  || (Xrm.Page.data.entity.attributes.get("north52_pipelineevent").getValue() == 217890005) )
        Xrm.Page.getAttribute('north52_clientsidedatapayload').setValue(existingPayLoad  + ':Create' + additionalEvents+saveMode);
   else if  ((Xrm.Page.data.entity.attributes.get("north52_pipelineevent").getValue() == 217890001)  || (Xrm.Page.data.entity.attributes.get("north52_pipelineevent").getValue() == 217890006) )
        Xrm.Page.getAttribute('north52_clientsidedatapayload').setValue(existingPayLoad + ':Update' + additionalEvents+saveMode);
   else if  ((Xrm.Page.data.entity.attributes.get("north52_pipelineevent").getValue() == 217890002)  || (Xrm.Page.data.entity.attributes.get("north52_pipelineevent").getValue() == 217890004) )
        Xrm.Page.getAttribute('north52_clientsidedatapayload').setValue(existingPayLoad + ':CreateUpdate' + additionalEvents+saveMode);
}

}