//If the SDK namespace object is not defined, create it.
if (typeof (N52) == "undefined")
{ N52 = {}; }
// Create Namespace container for functions in this library;
N52.Helpers = {

GetServerUrl: function()
{
    var context, crmServerUrl;  
    if (typeof GetGlobalContext != "undefined") {  
        context = GetGlobalContext();  
    }  
    else if (typeof Xrm != "undefined") {  
        context = Xrm.Page.context;  
    }  
    else {  
        throw new Error("CRM context is not available.");  
    }  
  

  
    if (typeof context.getClientUrl != "undefined") 
    {
       crmServerUrl = context.getClientUrl();
    }
    else
    {
         crmServerUrl = context.getServerUrl();  
         crmServerUrl = crmServerUrl.replace(/^(http|https):\/\/([_a-zA-Z0-9\-\.]+)(:([0-9]{1,5}))?/, window.location.protocol + "//" + window.location.host);  
         crmServerUrl = crmServerUrl.replace(/\/$/, ""); // remove trailing slash if any  
     }
  
    return crmServerUrl; 
},

SearchTraceLog: function()
{   
   var finalUrl = N52.Helpers.GetServerUrl() + '/advancedfind/advfind.aspx?etn=north52_trace';
   window.open(finalUrl);
},

openFormulaView: function() 
{ 

window.open(N52.Helpers.GetServerUrl() + "/main.aspx?etn=north52_formula&pagetype=entitylist");
},

openXCacheView: function() 
{ 

window.open(N52.Helpers.GetServerUrl() + "/main.aspx?etn=north52_xcache&pagetype=entitylist");
},


doNothing: function() 
{ 

return false;
},

openGenieView: function() 
{ 

window.open(N52.Helpers.GetServerUrl() + "/main.aspx?etn=north52_formula&extraqs=%3fpagemode%3diframe%26sitemappath%3dSettings%257cNorth52%257cnorth52_formula&pagetype=entitylist&viewid=%7b08B5937B-7D36-E311-89F7-00155DF5B00D%7d&viewtype=1039");
},

openSmartFlowView: function() 
{ 

window.open(N52.Helpers.GetServerUrl() + "/main.aspx?etn=north52_formula&extraqs=%3fpagemode%3diframe%26sitemappath%3dSettings%257cNorth52%257cnorth52_formula&pagetype=entitylist&viewid=%7bFB1F9BAE-5F57-E211-8F46-00155DF5B00D%7d&viewtype=1039");
},


openScheduleView: function() 
{ 

window.open(N52.Helpers.GetServerUrl() + "/main.aspx?etn=north52_schedule&pagetype=entitylist");
},

openFormula: function(formulaType) 
{ 

var param ="north52_formulatype=" +  formulaType;

var paramsLocal = {};
paramsLocal["north52_formulatype"] = formulaType;

Xrm.Utility.openEntityForm("north52_formula", null, paramsLocal);


},



openXCache: function()
{ 

Xrm.Utility.openEntityForm("north52_xcache", null, null);

},


openSchedule: function(scheduleType)
{ 

var param ="north52_scheduletype=" +  scheduleType;

var paramsLocal = {};
paramsLocal["north52_scheduletype"] = scheduleType;

Xrm.Utility.openEntityForm("north52_schedule", null, paramsLocal);

},

GetConfigurationId: function()
{
     ODataPath = N52.Helpers.GetServerUrl() + "/XRMServices/2011/OrganizationData.svc";

     var retrieveRecordsReq = new XMLHttpRequest();
     var configurationId = null;	

     retrieveRecordsReq.open('GET', ODataPath+"/north52_configurationSet",false);
     retrieveRecordsReq.setRequestHeader("Accept", "application/json");
     retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
     retrieveRecordsReq.send();

     var n52config =  JSON.parse(retrieveRecordsReq.responseText).d.results;
     
     if (n52config[0] == null) {
             alert("The North52 configuration record could not be found. This is probably because you have not yet accepted the license. Please navigate to the North52 Solution, click on the Information link & then accept the license which will create the configuration record. ");
      }
      else {
                    configurationId= n52config[0].north52_configurationId;
              }
   return configurationId;
},

CallCommandPublish: function ()
  {
            
  if ( navigator.userAgent.search('iPad') > 0)
       alert("North52 Formula Manager: Feature not supported on this device.");
   else
   {
      var recordid = Xrm.Page.data.entity.getId();
      var sourceentityname = Xrm.Page.getAttribute("north52_sourceentityname").getValue();
      var finalUrl = N52.Helpers.GetServerUrl() + '/WebResources/north52_html_publishformula?id=' +recordid + '&data=' + sourceentityname;

       if ( (navigator.userAgent.search('MSIE') > 0) || (navigator.userAgent.search('Trident/') > 0) )
             window.showModalDialog(finalUrl, self, 'dialogWidth: 400px;dialogHeight:200px');    
        else
               window.open(finalUrl, '_blank', 'top=300, left=300, width=400, height=200');     

       
    }
 },

CallCommandNewFormulaDetail: function ()
  {
    
     var formulaID = Xrm.Page.data.entity.getId();
     var formulaName = Xrm.Page.getAttribute("north52_name").getValue();

     var extraqs  = "north52_formula_north52_formuladetail_id=" + formulaID;
     extraqs  += "&north52_formula_north52_formuladetail_idname=" + formulaName ;
   
     var features = "location=no,menubar=no,status=no,toolbar=no";

     window.open("main.aspx?etn=north52_formuladetail&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);
 },

CallCommandTestFormula: function ()
  {

      var recordid = Xrm.Page.data.entity.getId();
      var formulaName = Xrm.Page.getAttribute("north52_name").getValue();
      var finalUrl = N52.Helpers.GetServerUrl() + '/WebResources/north52_html_formula_tester?id=' +recordid + '&data=' + formulaName;

          if ( (navigator.userAgent.search('MSIE') > 0) || (navigator.userAgent.search('Trident/') > 0) )
               window.showModalDialog(finalUrl, self, 'dialogWidth: 550px;dialogHeight:425px');
        else
               window.open(finalUrl, '_blank', 'top=300, left=300, width=550, height=425');     

     },

OpenConfiguration: function()
{
   var configurationId = N52.Helpers.GetConfigurationId();
      if (configurationId != null)            
      {
          var serverUrlFinal = N52.Helpers.GetServerUrl() + '/main.aspx?etn=north52_configuration&pagetype=entityrecord&id=' + '%7B'+ configurationId+'%7D'

          window.open(serverUrlFinal);
       }

},

OpenConfigurationUtility: function()
{
   var configurationId = N52.Helpers.GetConfigurationId();
      if (configurationId != null)            
      {
          Xrm.Utility.openEntityForm('north52_configuration', configurationId , null);
          
       }

},


CallSupport: function()
{
 
   if(window.UserVoice)
          return window.UserVoice.showPopupWidget();
    else
    { 

      var protocoltype = 'https:' == document.location.protocol ? 'https://' : 'http://';
      var scriptsrc = protocoltype  + 'widget.uservoice.com/VV5Js1PsQKFcgv9gm7hzg.js';
      var head = document.getElementsByTagName('head')[0];
      var script = document.createElement('script');
      script.type = "text/javascript";
      script.src = scriptsrc ;
      head.appendChild(script);

     window.UserVoice.showPopupWidget();
    }

},
  
CallCommandCloneFormula: function(command, recordid)
{

try{
        
    if ( navigator.userAgent.search('iPad') > 0)
       alert("North52 Formula Manager: Feature not supported on this device.");
    else if (recordid == null) {
           alert('North52 Formula Manager : Please select a Formula to clone.');
    }
    else
    {
       var finalUrl = N52.Helpers.GetServerUrl() + '/WebResources/north52_html_clone_formula?id=' +recordid + '&data=' + command;
    
          if ( (navigator.userAgent.search('MSIE') > 0) || (navigator.userAgent.search('Trident/') > 0) )
              window.showModalDialog(finalUrl, self, 'dialogWidth: 400px;dialogHeight:200px');
        else
               window.open(finalUrl, '_blank', 'top=300, left=300, width=400, height=200');
       
     }
    
 }
 catch (ex)
 {
   alert('North52 Formula Manager Error: ' + ex.message);
 }

},

PublishAll: function()
{

  try{
        
         var finalUrl = N52.Helpers.GetServerUrl() + '/WebResources/north52_html_deploy';

          if ( (navigator.userAgent.search('MSIE') > 0) || (navigator.userAgent.search('Trident/') > 0) )
               window.showModalDialog(finalUrl, self, 'dialogWidth: 400px;dialogHeight:200px');
        else
               window.open(finalUrl, '_blank', 'top=300, left=300, width=400, height=200');
       
     }
 catch (ex)
 {
   alert('North52 Formula Manager Error: ' + ex.message);
 }

},



 insertAtCaret: function (elementname,text)
 {                  
        var element = document.getElementById(elementname);
        if (document.selection) {
        element.focus();
        var sel = document.selection.createRange();
        sel.text = text;
        element.focus();
    } else if (element.selectionStart || element.selectionStart === 0) {
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        var scrollTop = element.scrollTop;
        element.value = element.value.substring(0, startPos) + text + element.value.substring(endPos, element.value.length);
        element.focus();
        element.selectionStart = startPos + text.length;
        element.selectionEnd = startPos + text.length;
        element.scrollTop = scrollTop;
    } else {
        element.value += text;
        element.focus();
    }
  },


 showHelp: function ()
 {                  
        alert('North52 Formula Manager: Online help coming soon...');
  }

}

if (!this.JSON) { this.JSON = {}; } (function () { function f(n) { return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, k, v, length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', { '': value }); }; } if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({ '': j }, '') : j; } throw new SyntaxError('JSON.parse'); }; } } ());