<commit_before>define(['underscore','jquery','events','toolbar','codemirror','alto','mybackbone','cmmode'],
    function (_,$,events,toolbar,CodeMirror,alto,mybackbone) {
    "use strict";

    var View = mybackbone.View.extend({

        initialize: function () {
            var that = this;
            this.cmConfig = {
                value: "",
                lineWrapping: true,
                mode: 'ocrui',
                changedSequence: [],
                changedSinceSaveSequence: [],
                languageSequence: [],
                highlight: {},
            };
            this.cMirror = new CodeMirror(this.$el.get(0), this.cmConfig);

            // suppress default codemirror bindings
            CodeMirror.commands.goPageUp = function () { };
            CodeMirror.commands.goPageDown = function () { };

            toolbar.registerButton({
                id:'highlight-editor-word',
                toggle:true,
                active:true,
                icon:'icon-star',
                title:'Highlight word in editor',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showHighlight',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});
            toolbar.registerButton({
                id:'show-saved-changes',
                toggle:true,
                icon:'icon-check',
                title:'Show unsaved changes',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showUnsavedChanges',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});
            toolbar.registerButton({
                id:'show-original-changes',
                toggle:true,
                active:true,
                icon:'icon-edit',
                title:'Show changes made to original',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showOriginalChanges',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});
            toolbar.registerButton({
                id:'show-language',
                toggle:true,
                active:true,
                icon:'icon-globe',
                title:'Show language of words',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showLanguage',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});

            this.cMirror.on('cursorActivity',function (instance) {
                events.delayOrIgnore('setupHighlightChange',undefined,100);
            });
            this.cMirror.on('change',function (instance) {
                if (that.suppressChanged) return ;
                that.changed(instance);
            });

        },
        el: '#editor',
        myEvents: {
            'virtualKeyboard':'virtualKeyboard',
            'cursorToCoordinate': 'moveCursorToWord',
            'refocus':'refocus',
            'changePage':'changePage',
            'requestLanguageChange':'requestLanguageChange',
            'setupHighlightChange':'setupHighlightChange',
            'pageDirtyStateChanged':'pageDirtyStateChanged'
        },
        virtualKeyboard: function(data) {
            this.cMirror.replaceSelection(data);
            this.cMirror.focus();
            var cursor = this.cMirror.getCursor();
            this.cMirror.setCursor(cursor);
        },
        requestLanguageChange: function(selected) {
            var wordIndexes = this.getCurrentWordIndexes();
            for (var wordIndexIndex in wordIndexes) {
                var i = wordIndexes[wordIndexIndex];
                this.alto.setNthWordLanguage(i,selected);
            }
            this.cMirror.replaceSelection(this.cMirror.getSelection());
            this.cMirror.focus();
        },
        refocus: function(ev) {
            this.cMirror.focus();
        },
        moveCursorToWord: function(coords) {
            var content = this.cMirror.getValue();
            var line = 0;
            var ch = 0;
            var inMiddleOfWord = false;
            if (!this.alto) { return; }
            var word = this.alto.getWordAt(coords.x,coords.y);
            if (word === undefined) {return;}
            var wordIndex = word.index;
            for (var i in content) {
                var c = content[i];
                if (c == '\n') {
                    line ++;
                    ch = 0;
                }
                if (c.match(/\S/)) {
                    if (inMiddleOfWord) wordIndex --;
                    if (wordIndex === 0) {break;}
                    inMiddleOfWord = false;
                } else {
                    inMiddleOfWord = true;
                }
                ch ++;
            }
            this.cMirror.setCursor(line,ch);
            this.cMirror.focus();
        },
        configureCMMode: function () {
            this.cmConfigchangedSinceSaveSequence =
                this.alto.getChangedSinceSaveSequence();
            this.cmConfig.changedSequence = this.alto.getChangedSequence();
            this.cmConfig.languageSequence = this.alto.getLanguageSequence();
        },
        changed: function (instance) {
            var content = instance.getValue();
            this.alto.updateStringContent(content);
            this.configureCMMode();
            this.setupHighlightChange();
        },
        getCurrentWordIndexes: function () {
            var wordIndexes = {};
            var wordIndex = 0;
            var content = this.cMirror.getValue();
            var start = this.cMirror.getCursor('start');
            var end = this.cMirror.getCursor('end');
            var s_line = start.line;
            var s_ch = start.ch;
            var e_line = end.line;
            var e_ch = end.ch;
            var inMiddleOfWord = false;
            var slice = "";
            for (var i in content) {
                var c = content[i];
                if (c.match(/\S/)) {
                    if (inMiddleOfWord) wordIndex ++;
                    inMiddleOfWord = false;
                } else {
                    inMiddleOfWord = true;
                }
                if (s_line <= 0) {

                    if (s_ch <= 0) {

                        wordIndexes[wordIndex] = true;
                        slice += c;
                    }
                    s_ch --;
                    if (e_line <=0) {
                        if (e_ch <= 0) {
                            var isEmpty = true;
                            for (var j in wordIndexes) {
                                isEmpty = false;
                                break;
                            }
                            if (isEmpty) {
                                slice += c;
                                wordIndexes[wordIndex] = true;
                            }
                            break;
                        }
                        e_ch --;
                    }
                }
                if (c == '\n') {
                    s_line --;
                    e_line --;
                }
            }
            this.words = wordIndexes;
            var wordIndexArray = _.map(wordIndexes,function (v,k) {
                return parseInt(k,10);
            });
            return wordIndexArray;
        },
        setupHighlightChange: function () {

            var wordIndexes = this.getCurrentWordIndexes();
            var that = this;
            var words = _.map(wordIndexes,function (v,k) {

                return that.alto.getNthWord(v);

            });

            that.cMirror.setOption('highlight',this.words);
            this.suppressChanged = true;
            this.cMirror.view.frontier = 0;
            this.cMirror.replaceSelection(this.cMirror.getSelection());
            this.suppressChanged = false;

            events.trigger('changeCoordinates',words);

        },
        changePage: function(attributes) {
            var that = this;
            this.attributes = attributes;
            alto.get(attributes).then(
                function(myAlto) {
                    /* if (this.attributes != attributes) return;*/
                    that.setAlto(myAlto);
                },
                function(msg) {
                    events.trigger('editorRenderError',{
                        error: 'editorRenderError',
                        message: msg
                    });
                }
            );
        },
        pageDirtyStateChanged: function() {
            if(this.alto.isDirty()) {
                this.$el.addClass('dirty');
            } else {
                this.$el.removeClass('dirty');
            }
        },
        setAlto: function(alto) {
            this.alto = alto;
            var s = alto.getString();
            this.cMirror.setValue(s);
            this.cMirror.clearHistory();
            var word = this.alto.getNthWord(0);
            this.cMirror.focus();
            events.trigger('editorRendered',this.attributes);
        },
        render: function() {
            return;     // Nothing to do, CodeMirror renders itself
        }
    });

    return {
        view: new View()
    };

});
<commit_msg>editor highlight off by default<commit_after>define(['underscore','jquery','events','toolbar','codemirror','alto','mybackbone','cmmode'],
    function (_,$,events,toolbar,CodeMirror,alto,mybackbone) {
    "use strict";

    var View = mybackbone.View.extend({

        initialize: function () {
            var that = this;
            this.cmConfig = {
                value: "",
                lineWrapping: true,
                mode: 'ocrui',
                changedSequence: [],
                changedSinceSaveSequence: [],
                languageSequence: [],
                highlight: {},
            };
            this.cMirror = new CodeMirror(this.$el.get(0), this.cmConfig);

            // suppress default codemirror bindings
            CodeMirror.commands.goPageUp = function () { };
            CodeMirror.commands.goPageDown = function () { };

            toolbar.registerButton({
                id:'highlight-editor-word',
                toggle:true,
                active:false,
                icon:'icon-star',
                title:'Highlight word under cursor in editor',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showHighlight',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});
            toolbar.registerButton({
                id:'show-saved-changes',
                toggle:true,
                icon:'icon-check',
                title:'Show unsaved changes',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showUnsavedChanges',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});
            toolbar.registerButton({
                id:'show-original-changes',
                toggle:true,
                active:true,
                icon:'icon-edit',
                title:'Show changes made to original',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showOriginalChanges',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});
            toolbar.registerButton({
                id:'show-language',
                toggle:true,
                active:true,
                icon:'icon-globe',
                title:'Show language of words',
                modes:['page'],
                toggleCB:function(newState) {
                    that.cMirror.setOption('showLanguage',newState);
                    that.cMirror.replaceSelection(that.cMirror.getSelection());
                }});

            this.cMirror.on('cursorActivity',function (instance) {
                events.delayOrIgnore('setupHighlightChange',undefined,100);
            });
            this.cMirror.on('change',function (instance) {
                if (that.suppressChanged) return ;
                that.changed(instance);
            });

        },
        el: '#editor',
        myEvents: {
            'virtualKeyboard':'virtualKeyboard',
            'cursorToCoordinate': 'moveCursorToWord',
            'refocus':'refocus',
            'changePage':'changePage',
            'requestLanguageChange':'requestLanguageChange',
            'setupHighlightChange':'setupHighlightChange',
            'pageDirtyStateChanged':'pageDirtyStateChanged'
        },
        virtualKeyboard: function(data) {
            this.cMirror.replaceSelection(data);
            this.cMirror.focus();
            var cursor = this.cMirror.getCursor();
            this.cMirror.setCursor(cursor);
        },
        requestLanguageChange: function(selected) {
            var wordIndexes = this.getCurrentWordIndexes();
            for (var wordIndexIndex in wordIndexes) {
                var i = wordIndexes[wordIndexIndex];
                this.alto.setNthWordLanguage(i,selected);
            }
            this.cMirror.replaceSelection(this.cMirror.getSelection());
            this.cMirror.focus();
        },
        refocus: function(ev) {
            this.cMirror.focus();
        },
        moveCursorToWord: function(coords) {
            var content = this.cMirror.getValue();
            var line = 0;
            var ch = 0;
            var inMiddleOfWord = false;
            if (!this.alto) { return; }
            var word = this.alto.getWordAt(coords.x,coords.y);
            if (word === undefined) {return;}
            var wordIndex = word.index;
            for (var i in content) {
                var c = content[i];
                if (c == '\n') {
                    line ++;
                    ch = 0;
                }
                if (c.match(/\S/)) {
                    if (inMiddleOfWord) wordIndex --;
                    if (wordIndex === 0) {break;}
                    inMiddleOfWord = false;
                } else {
                    inMiddleOfWord = true;
                }
                ch ++;
            }
            this.cMirror.setCursor(line,ch);
            this.cMirror.focus();
        },
        configureCMMode: function () {
            this.cmConfigchangedSinceSaveSequence =
                this.alto.getChangedSinceSaveSequence();
            this.cmConfig.changedSequence = this.alto.getChangedSequence();
            this.cmConfig.languageSequence = this.alto.getLanguageSequence();
        },
        changed: function (instance) {
            var content = instance.getValue();
            this.alto.updateStringContent(content);
            this.configureCMMode();
            this.setupHighlightChange();
        },
        getCurrentWordIndexes: function () {
            var wordIndexes = {};
            var wordIndex = 0;
            var content = this.cMirror.getValue();
            var start = this.cMirror.getCursor('start');
            var end = this.cMirror.getCursor('end');
            var s_line = start.line;
            var s_ch = start.ch;
            var e_line = end.line;
            var e_ch = end.ch;
            var inMiddleOfWord = false;
            var slice = "";
            for (var i in content) {
                var c = content[i];
                if (c.match(/\S/)) {
                    if (inMiddleOfWord) wordIndex ++;
                    inMiddleOfWord = false;
                } else {
                    inMiddleOfWord = true;
                }
                if (s_line <= 0) {

                    if (s_ch <= 0) {

                        wordIndexes[wordIndex] = true;
                        slice += c;
                    }
                    s_ch --;
                    if (e_line <=0) {
                        if (e_ch <= 0) {
                            var isEmpty = true;
                            for (var j in wordIndexes) {
                                isEmpty = false;
                                break;
                            }
                            if (isEmpty) {
                                slice += c;
                                wordIndexes[wordIndex] = true;
                            }
                            break;
                        }
                        e_ch --;
                    }
                }
                if (c == '\n') {
                    s_line --;
                    e_line --;
                }
            }
            this.words = wordIndexes;
            var wordIndexArray = _.map(wordIndexes,function (v,k) {
                return parseInt(k,10);
            });
            return wordIndexArray;
        },
        setupHighlightChange: function () {

            var wordIndexes = this.getCurrentWordIndexes();
            var that = this;
            var words = _.map(wordIndexes,function (v,k) {

                return that.alto.getNthWord(v);

            });

            that.cMirror.setOption('highlight',this.words);
            this.suppressChanged = true;
            this.cMirror.view.frontier = 0;
            this.cMirror.replaceSelection(this.cMirror.getSelection());
            this.suppressChanged = false;

            events.trigger('changeCoordinates',words);

        },
        changePage: function(attributes) {
            var that = this;
            this.attributes = attributes;
            alto.get(attributes).then(
                function(myAlto) {
                    /* if (this.attributes != attributes) return;*/
                    that.setAlto(myAlto);
                },
                function(msg) {
                    events.trigger('editorRenderError',{
                        error: 'editorRenderError',
                        message: msg
                    });
                }
            );
        },
        pageDirtyStateChanged: function() {
            if(this.alto.isDirty()) {
                this.$el.addClass('dirty');
            } else {
                this.$el.removeClass('dirty');
            }
        },
        setAlto: function(alto) {
            this.alto = alto;
            var s = alto.getString();
            this.cMirror.setValue(s);
            this.cMirror.clearHistory();
            var word = this.alto.getNthWord(0);
            this.cMirror.focus();
            events.trigger('editorRendered',this.attributes);
        },
        render: function() {
            return;     // Nothing to do, CodeMirror renders itself
        }
    });

    return {
        view: new View()
    };

});
<|endoftext|>


<commit_before>var sys     = require("sys");
var path    = require("path");
var fs      = require("fs");
var op      = require("./option_parser");
var results = require("./results");
var coll    = require("./collector")
var should  = require("./should");

var Runner = exports.Runner = function () {
  this.runnerData = {
    total: 0,
    failCount: 0,
    contexts: [],
    options: op.parse(process.ARGV)
  };
};

Runner.prototype = {

  fail: function (message) {
    var f = this.runnerData.options.verbose ? "Fail " : "F";
    sys.print("\033[31m" + f + "\033[37m");
  },

  pass: function () {
    var p = this.runnerData.options.verbose ? "Pass " : ".";
    sys.print("\033[32m" + p + "\033[37m");
  },

//  error: function (message) {
//    sys.print(this.options.verbose ? "Error (" + message + ") " : "E");
//    this.failures.push(this.specs.join(" ") + "\n" + message + "\n");
//  },
//
  dir: function () {
    return path.dirname(__filename).replace("lib", "") + "spec/";
  },

  initHooks: function (scope) {
    var hooks = ["before", "beforeEach", "afterEach", "after"];
    for (var i = 0, ii = hooks.length; i < ii; i++) {
      (function(name, internal) {
        scope[internal] = function () {}; // init to empty function
        scope[name] = function (func) { scope[internal] = func };
      })(hooks[i], ("_" + hooks[i]));
    }
  },

  readSpecs: function (paths, callback) {
    var _pending = 0,
        _interval,
        _specs = [];

    function initInterval() {
      if (_interval) return;

      _interval = setInterval(function () {
        if (_pending > 0) return;
        clearInterval(_interval);
        callback(null, _specs);
      }, 100);
    }

    for (var i = 0, ii = paths.length; i < ii; i++) {

      (function (path) {
        _pending++;
        fs.readFile(path, "utf8", function (err, spec) {
          if(err) {
            callback(err);
            return;
          }
          _specs.push({ path: path, spec: spec });
          _pending--;
        });
        initInterval();

      })(paths[i]);
    }
  },

  outputResults: function () {
    var data = this.runnerData;
    process.addListener("exit", function () {
      var r = results.format(data);
      sys.puts(r);
    });
  },

  run: function () {
    var _self = this;
    var value = require("./should").value;

    // =======================================
    // speks test structure
    // =======================================

    function describe(name, func) {
      this._sut = { name: name, specs: [] };
      _self.runnerData.contexts.push(this._sut);

      _self.initHooks(this);

      func();

      _after();

      if (_self.runnerData.options.verbose)
        sys.print("\n\n");
    }

    function it(desc, func) {
      var spec = { desc: desc };

      _self.runnerData.total++;
      _sut.specs.push(spec);

      if (_self.runnerData.options.verbose)
        sys.print("\n " + desc + " : ");

      if(_before) {
        _before();
        _before = null;
      }

      _beforeEach();

      try {
        func();
        _self.pass();
      } catch (e) {
        _self.runnerData.failCount++;
        _sut.hasFailures = true;
        _self.fail(e);
        spec.message = e;
      }

      _afterEach();
    }

    // =======================================
    // speks test structure
    // =======================================

    function __execute__(specs) {
      for (var i = 0, ii = specs.length; i < ii; i++) {
        if (_self.runnerData.options.verbose) {
          var num = parseInt(i) + 1;
          sys.puts(num + ". " + specs[i].path + ":\n");
        }
        eval(specs[i].spec);
      }

      sys.puts("\n");
      _self.outputResults();
    }

    coll.collect((this.runnerData.options.specdir || this.dir()), this.runnerData.options.filename,
        function (err, paths) {
          if(err) throw err;
          _self.readSpecs(paths, function(err, specs) {
            if(err) throw err;
            __execute__(specs);
          });
        });
  }

};
<commit_msg>still cleaning scope<commit_after>var sys     = require("sys");
var path    = require("path");
var fs      = require("fs");
var op      = require("./option_parser");
var results = require("./results");
var coll    = require("./collector");
var should  = require("./should");

var Runner = exports.Runner = function () {
  this.runnerData = {
    total: 0,
    failCount: 0,
    contexts: [],
    options: op.parse(process.ARGV)
  };
};

Runner.prototype = {

  fail: function (message) {
    var f = this.runnerData.options.verbose ? "Fail " : "F";
    sys.print("\033[31m" + f + "\033[37m");
  },

  pass: function () {
    var p = this.runnerData.options.verbose ? "Pass " : ".";
    sys.print("\033[32m" + p + "\033[37m");
  },

//  error: function (message) {
//    sys.print(this.options.verbose ? "Error (" + message + ") " : "E");
//    this.failures.push(this.specs.join(" ") + "\n" + message + "\n");
//  },
//
  dir: function () {
    return path.dirname(__filename).replace("lib", "") + "spec/";
  },

  initHooks: function (scope) {
    var hooks = ["before", "beforeEach", "afterEach", "after"];
    for (var i = 0, ii = hooks.length; i < ii; i++) {
      (function(name, internal) {
        scope[internal] = function () {}; // init to empty function
        scope[name] = function (func) { scope[internal] = func };
      })(hooks[i], ("_" + hooks[i]));
    }
  },

  readSpecs: function (paths, callback) {
    var _pending = 0,
        _interval,
        _specs = [];

    function initInterval() {
      if (_interval) return;

      _interval = setInterval(function () {
        if (_pending > 0) return;
        clearInterval(_interval);
        callback(null, _specs);
      }, 100);
    }

    for (var i = 0, ii = paths.length; i < ii; i++) {

      (function (path) {
        _pending++;
        fs.readFile(path, "utf8", function (err, spec) {
          if(err) {
            callback(err);
            return;
          }
          _specs.push({ path: path, spec: spec });
          _pending--;
        });
        initInterval();

      })(paths[i]);
    }
  },

  outputResults: function () {
    var data = this.runnerData;
    process.addListener("exit", function () {
      var r = results.format(data);
      sys.puts(r);
    });
  },

  run: function () {

    var __core = {
      runr: this,
      data: this.runnerData,
      start: function (callback) {
        var self = this;
        var runr = this.runr;
        coll.collect((this.data.options.specdir || runr.dir()), this.data.options.filename,
            function (err, paths) {
              if(err) throw err;
              runr.readSpecs(paths, function(err, specs) {
                if(err) throw err;
                self.evaluate(specs, callback);
              });
            });
      },
      evaluate: function (specs, evalCallback) {
        for (var i = 0, ii = specs.length; i < ii; i++) {
          if (__core.data.options.verbose) {
            var num = parseInt(i) + 1;
            sys.puts(num + ". " + specs[i].path + ":\n");
          }
          evalCallback(specs[i].spec);
        }

        sys.puts("\n");
        _self.outputResults();
      }
    };

    var _self = this;
    var value = require("./should").value; // include should api in scope

    // =======================================
    // speks test structure
    // =======================================

    function describe(name, func) {
      this.__context__ = { name: name, specs: [] };
      __core.data.contexts.push(this.__context__);

      _self.initHooks(this);

      func();

      _after();

      if (__core.data.options.verbose)
        sys.print("\n\n");
    }

    function it(desc, func) {
      var spec = { desc: desc };

      __core.data.total++;
      __context__.specs.push(spec);

      if (__core.data.options.verbose)
        sys.print("\n " + desc + " : ");

      if(_before) {
        _before();
        _before = null;
      }

      _beforeEach();

      try {
        func();
        _self.pass();
      } catch (e) {
        __context__.hasFailures = true;
        __core.data.failCount++;
        _self.fail(e);
        spec.message = e;
      }

      _afterEach();
    }

    // =======================================
    // speks test structure
    // =======================================

    function __eval__(spec) {
      eval(spec);
    }
    __core.start(__eval__);
  }
};
<|endoftext|>


<commit_before>/*global define*/
define([
    'underscore',
    'jquery',
    'marionette',
    'app',
    'helpers/uri',
    'enquire'
], function (_, $,  Marionette, App, URI, enquire) {
    'use strict';

    /**
     * Submodule which shows note content
     */
    var AppNote = App.module('AppNote', { startWithParent: false }),
        executeAction,
        API;

    AppNote.on('start', function () {
        App.mousetrap.API.restart();
        App.AppNavbar.start();

        App.log('AppNote is started');
    });

    AppNote.on('stop', function () {
        App.log('AppNote is stoped');
    });

    /**
     * The router
     */
    AppNote.Router = Marionette.AppRouter.extend({
        appRoutes: {
            'p/:profile'                    : 'showNotes',
            '(p/:profile/)notes/add'        : 'addNote',
            '(p/:profile/)notes/edit/:id'   : 'editNote',
            '(p/:profile/)notes/remove/:id' : 'removeNote',
            '(p/:profile/)notes(/f/:filter)(/q/:query)(/p:page)'   : 'showNotes',
            '(p/:profile/)notes(/f/:filter)(/q/:query)(/p:page)(/show/:id)'  : 'showNote',
        }
    });

    /**
     * Start application
     */
    executeAction = function (action, args) {
        App.startSubApp('AppNote');
        action(args);
    };

    /**
     * Controller
     */
    API = {
        getArgs: function (args) {
            var values = ['profile', 'filter', 'query', 'page', 'id'],
                argsObj = {};

            if (args.length === 1 && typeof args[0] === 'object') {
                return args[0];
            }

            _.each(values, function (value, index) {
                argsObj[value] = (args[index]) ? args[index] : null;
            });

            argsObj.page = Number(argsObj.page);
            return argsObj;
        },

        // Show list of notes
        showNotes: function () {
            var args = this.getArgs(arguments);

            require(['apps/notes/list/controller'], function (List) {
                App.notesArg = args;
                executeAction(new List().listNotes, args);
            });
        },

        // Show content of note
        showNote: function () {
            var args = this.getArgs(arguments);

            require(['apps/notes/show/showController'], function (Show) {
                App.trigger('notes:show', args);
                executeAction(new Show().showNote, args);
            });
        },

        // Add new note
        addNote: function (profile) {
            require(['apps/notes/form/controller'], function (Form) {
                executeAction(new Form().addForm, {profile: profile});
                App.trigger('notes:show', {profile: profile});
            });
        },

        // Edit an existing note
        editNote: function (profile, id) {
            require(['apps/notes/form/controller'], function (Form) {
                executeAction(new Form().editForm, {id : id, profile: profile});
                App.trigger('notes:show', {profile: profile});
            });
            App.log('edit note ' + id);
        },

        // Remove an existing note
        removeNote: function (profile, id) {
            require(['apps/notes/remove/removeController'], function (Controller) {
                executeAction(new Controller().remove, {id : id, profile: profile});
            });
        },

        // Re-render sidebar only if necessary
        checkShowSidebar: function (args) {
            var current = _.omit(App.notesArg || {}, 'id');

            if ( !_.isEqual(current,  _.omit(args, 'id')) ) {
                API.showNotes(args);
            }
        }
    };

    /**
     * Router events
     */
    App.on('notes:list', function () {
        App.navigate(URI.link('/notes'), { trigger : true });
    });

    // Show sidebar with notes list only on big screen
    App.on('notes:show', function (args) {
        $(App.content.el).addClass('active-row');
        enquire.register('screen and (min-width:768px)', {
            match: function () {
                API.checkShowSidebar(args);
            }
        });
    });

    // Toggle to sidebar
    App.on('notes:toggle', function (args) {
        $(App.content.el).removeClass('active-row');
        API.checkShowSidebar(args);
    });

    // Re render
    App.on('notes:rerender', function () {
        API.showNotes(API.notesArg || {});
    });

    // Re-render sidebar if new note has been added
    App.on('notes:added', function (model) {
        API.showNotes(_.extend(App.notesArg || {}, {id: model.get('id')}));
    });

    // Show form
    AppNote.on('showForm', function () {
        App.navigate(URI.link('/notes/add'), true);
    });

    // Re-render sidebar's and note's content after sync:after event
    App.on('sync:after', function (args) {
        if (args.objects.length === 0 || App.currentApp.moduleName !== 'AppNote') {
            return;
        }
        else if (args.collection === 'notes' || args.collection === 'files') {
            API.showNotes(API.notesArg || {});
            API.showNote(API.notesArg  || {});
        }
    });

    /**
     * Register the router
     */
    App.addInitializer(function(){
        new AppNote.Router({
            controller: API
        });
    });

    return AppNote;
});
<commit_msg>bug with sidebar<commit_after>/*global define*/
define([
    'underscore',
    'jquery',
    'marionette',
    'app',
    'helpers/uri',
    'enquire'
], function (_, $,  Marionette, App, URI, enquire) {
    'use strict';

    /**
     * Submodule which shows note content
     */
    var AppNote = App.module('AppNote', { startWithParent: false }),
        executeAction,
        API;

    AppNote.on('start', function () {
        App.mousetrap.API.restart();
        App.AppNavbar.start();

        App.log('AppNote is started');
    });

    AppNote.on('stop', function () {
        App.log('AppNote is stoped');
    });

    /**
     * The router
     */
    AppNote.Router = Marionette.AppRouter.extend({
        appRoutes: {
            'p/:profile'                    : 'showNotes',
            '(p/:profile/)notes/add'        : 'addNote',
            '(p/:profile/)notes/edit/:id'   : 'editNote',
            '(p/:profile/)notes/remove/:id' : 'removeNote',
            '(p/:profile/)notes(/f/:filter)(/q/:query)(/p:page)'   : 'showNotes',
            '(p/:profile/)notes(/f/:filter)(/q/:query)(/p:page)(/show/:id)'  : 'showNote',
        }
    });

    /**
     * Start application
     */
    executeAction = function (action, args) {
        App.startSubApp('AppNote');
        action(args);
    };

    /**
     * Controller
     */
    API = {
        getArgs: function (args) {
            var values = ['profile', 'filter', 'query', 'page', 'id'],
                argsObj = {};

            if (args.length === 1 && typeof args[0] === 'object') {
                return args[0];
            }

            _.each(values, function (value, index) {
                argsObj[value] = (args[index]) ? args[index] : null;
            });

            argsObj.page = Number(argsObj.page);
            argsObj.profile = argsObj.profile || URI.getProfile();
            return argsObj;
        },

        // Show list of notes
        showNotes: function () {
            var args = this.getArgs(arguments);

            require(['apps/notes/list/controller'], function (List) {
                App.notesArg = args;
                executeAction(new List().listNotes, args);
            });
        },

        // Show content of note
        showNote: function () {
            var args = this.getArgs(arguments);

            require(['apps/notes/show/showController'], function (Show) {
                App.trigger('notes:show', args);
                executeAction(new Show().showNote, args);
            });
        },

        // Add new note
        addNote: function (profile) {
            require(['apps/notes/form/controller'], function (Form) {
                executeAction(new Form().addForm, {profile: profile});
                App.trigger('notes:show', {profile: profile});
            });
        },

        // Edit an existing note
        editNote: function (profile, id) {
            require(['apps/notes/form/controller'], function (Form) {
                executeAction(new Form().editForm, {id : id, profile: profile});
                App.trigger('notes:show', {profile: profile});
            });
            App.log('edit note ' + id);
        },

        // Remove an existing note
        removeNote: function (profile, id) {
            require(['apps/notes/remove/removeController'], function (Controller) {
                executeAction(new Controller().remove, {id : id, profile: profile});
            });
        },

        // Re-render sidebar only if necessary
        checkShowSidebar: function (args) {
            var current = _.omit(App.notesArg || {}, 'id');

            if ( !_.isEqual(current,  _.omit(args, 'id')) ) {
                API.showNotes(args);
            }
        }
    };

    /**
     * Router events
     */
    App.on('notes:list', function () {
        App.navigate(URI.link('/notes'), { trigger : true });
    });

    // Show sidebar with notes list only on big screen
    App.on('notes:show', function (args) {
        $(App.content.el).addClass('active-row');
        enquire.register('screen and (min-width:768px)', {
            match: function () {
                API.checkShowSidebar(args);
            }
        });
    });

    // Toggle to sidebar
    App.on('notes:toggle', function (args) {
        $(App.content.el).removeClass('active-row');
        API.checkShowSidebar(args);
    });

    // Re render
    App.on('notes:rerender', function () {
        API.showNotes(API.notesArg || {});
    });

    // Re-render sidebar if new note has been added
    App.on('notes:added', function (model) {
        API.showNotes(_.extend(App.notesArg || {}, {id: model.get('id')}));
    });

    // Show form
    AppNote.on('showForm', function () {
        App.navigate(URI.link('/notes/add'), true);
    });

    // Re-render sidebar's and note's content after sync:after event
    App.on('sync:after', function (args) {
        if (args.objects.length === 0 || App.currentApp.moduleName !== 'AppNote') {
            return;
        }
        else if (args.collection === 'notes' || args.collection === 'files') {
            API.showNotes(API.notesArg || {});
            API.showNote(API.notesArg  || {});
        }
    });

    /**
     * Register the router
     */
    App.addInitializer(function(){
        new AppNote.Router({
            controller: API
        });
    });

    return AppNote;
});
<|endoftext|>


<commit_before>// ♻ LOOP THRU ALL THE FILES AND BUILD UP THE JSON
// Outputs a JSON document list for indexing by Lunr

console.log("🔍 Creating document data for Lunr...");

const yaml = require('js-yaml');
const fs = require('fs');
const path = require('path');
const remark = require('remark');
const strip = require('strip-markdown');

const rootdir = path.dirname(__dirname)+"/content/";
let pageid = 0;

/**
 * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
 *
 * @see http://stackoverflow.com/a/5827895/4241030
 * @see https://ourcodeworld.com/articles/read/420/how-to-read-recursively-a-directory-in-node-js
 * @param {String} dir
 * @param {Function} done
 */
function directoryWalker(dir, done) {
	let results = [];
	let documents = [];
	let pathmap = [];

	fs.readdir(dir, function(err, list) {
		if (err) return done(err);

		var pending = list.length;

		if (!pending) return done(null, results, documents, pathmap);

		list.forEach(function(file) {
			file = path.resolve(dir, file);

			fs.stat(file, function(err, stat) {
				// If directory, execute a recursive call
				if (stat && stat.isDirectory()) {
					// we are currently on a directory (file)

					const relativeUrl = file.replace(rootdir,"/");
					let document = new Object();
					let pathmapitem = new Object();

					// load the index.yml and get the data
					try {
					  const indexyaml = yaml.safeLoad(fs.readFileSync(file + "/index.yml", 'utf8'));

						// do not index hidden pages or the homepage
						if (indexyaml.hidden || relativeUrl == "/homepage") {
							throw("Not indexing hidden page: " + relativeUrl);
						}
						document.title = indexyaml.pagetitle;
						document.description = indexyaml.description;
						pathmapitem.description = indexyaml.description;
						pathmapitem.title = indexyaml.pagetitle;

						pageid = pageid + 1;

						document.id = pageid;
						pathmapitem.id = pageid;
						pathmapitem.path = relativeUrl;

						// open all the markdown files inside this directory AND
						// concat into the document.body
						fs.readdir(file, function(err, items) {
					    for (let i = 0; i < items.length; i++) {
								if (path.extname(items[i]) == '.md') {
									let file_absolute = rootdir + relativeUrl + "/" +items[i];
									file_absolute = path.normalize(file_absolute);
									let data = fs.readFileSync(file_absolute);

									// TODO strip crosslink content e.g. layout/cards, menu

									remark()
									  .use(strip)
									  .process(data, function (err, file) {
									    if (err) throw err;
									    document.body = document.body + String(file);
									  });

								}
					    }
						});

						// push to the arrays
						documents.push(document);
						pathmap.push(pathmapitem);
						results.push(file);

					} catch (e) {
					  console.log(e);
					}

					directoryWalker(file, function(err, res, docs, pthmp) {
						results = results.concat(res);
						documents = documents.concat(docs);
						pathmap = pathmap.concat(pthmp);
						if (!--pending) done(null, results, documents, pathmap);
					});
				} else {
					//results.push(file);

					if (!--pending) done(null, results, documents, pathmap);
				}
			});
		});
	});
};

////////////////////////

// 💾 WRITE THE FILE
function writeDocumentData(data) {
	fs.writeFile('site/documents.json', JSON.stringify(data), (err) => {
	  if (err) throw err;
	  console.log('💾 The Lunr document index has been created -> site/documents.json');
	});
}

function writePathmapData(data) {
	fs.writeFile('site/pathmap.json', JSON.stringify(data), (err) => {
	  if (err) throw err;
	  console.log('💾 The Lunr path map has been created -> site/pathmap.json');
	});
}

function addFederatedData(docsArray,pathsArray) {
	// Design System
	document = new Object();
	pathmapitem = new Object();
	document.title = "Design System";
	document.description = "UI UIkit component layout Front End Toolkit react patterns button accordion grid forms css javascript style guide";
	pathmapitem.title = "Design System";
	pageid = pageid + 1;
	document.id = pageid;
	pathmapitem.id = pageid;
	pathmapitem.path = "https://designsystem.gov.au/";
	docsArray.push(document);
	pathsArray.push(pathmapitem);

	// Content Guide
	document = new Object();
	pathmapitem = new Object();
	document.title = "GOV.AU Content Guide";
	document.description = "A guide to help Australian Government teams design simple, clear and fast content. Content structure, writing style, punctuation and grammar, terms phrases, numbers, measurements formatting accessibility";
	pathmapitem.title = "GOV.AU Content Guide";
	pageid = pageid + 1;
	document.id = pageid;
	pathmapitem.id = pageid;
	pathmapitem.path = "https://guides.service.gov.au/content-guide/";
	docsArray.push(document);
	pathsArray.push(pathmapitem);
}

directoryWalker("./content/", function(err, dirs, documents, pathmap) {
	if (err) {
		throw err;
	}

	//const util = require('util')
	//console.log(util.inspect(pathmap, { maxArrayLength: null }))
	addFederatedData(documents,pathmap);
	writeDocumentData(documents);
	writePathmapData(pathmap);
});
<commit_msg>Add descriptions to federated data<commit_after>// ♻ LOOP THRU ALL THE FILES AND BUILD UP THE JSON
// Outputs a JSON document list for indexing by Lunr

console.log("🔍 Creating document data for Lunr...");

const yaml = require('js-yaml');
const fs = require('fs');
const path = require('path');
const remark = require('remark');
const strip = require('strip-markdown');

const rootdir = path.dirname(__dirname)+"/content/";
let pageid = 0;

/**
 * Explores recursively a directory and returns all the filepaths and folderpaths in the callback.
 *
 * @see http://stackoverflow.com/a/5827895/4241030
 * @see https://ourcodeworld.com/articles/read/420/how-to-read-recursively-a-directory-in-node-js
 * @param {String} dir
 * @param {Function} done
 */
function directoryWalker(dir, done) {
	let results = [];
	let documents = [];
	let pathmap = [];

	fs.readdir(dir, function(err, list) {
		if (err) return done(err);

		var pending = list.length;

		if (!pending) return done(null, results, documents, pathmap);

		list.forEach(function(file) {
			file = path.resolve(dir, file);

			fs.stat(file, function(err, stat) {
				// If directory, execute a recursive call
				if (stat && stat.isDirectory()) {
					// we are currently on a directory (file)

					const relativeUrl = file.replace(rootdir,"/");
					let document = new Object();
					let pathmapitem = new Object();

					// load the index.yml and get the data
					try {
					  const indexyaml = yaml.safeLoad(fs.readFileSync(file + "/index.yml", 'utf8'));

						// do not index hidden pages or the homepage
						if (indexyaml.hidden || relativeUrl == "/homepage") {
							throw("Not indexing hidden page: " + relativeUrl);
						}
						document.title = indexyaml.pagetitle;
						document.description = indexyaml.description;
						pathmapitem.description = indexyaml.description;
						pathmapitem.title = indexyaml.pagetitle;

						pageid = pageid + 1;

						document.id = pageid;
						pathmapitem.id = pageid;
						pathmapitem.path = relativeUrl;

						// open all the markdown files inside this directory AND
						// concat into the document.body
						fs.readdir(file, function(err, items) {
					    for (let i = 0; i < items.length; i++) {
								if (path.extname(items[i]) == '.md') {
									let file_absolute = rootdir + relativeUrl + "/" +items[i];
									file_absolute = path.normalize(file_absolute);
									let data = fs.readFileSync(file_absolute);

									// TODO strip crosslink content e.g. layout/cards, menu

									remark()
									  .use(strip)
									  .process(data, function (err, file) {
									    if (err) throw err;
									    document.body = document.body + String(file);
									  });

								}
					    }
						});

						// push to the arrays
						documents.push(document);
						pathmap.push(pathmapitem);
						results.push(file);

					} catch (e) {
					  console.log(e);
					}

					directoryWalker(file, function(err, res, docs, pthmp) {
						results = results.concat(res);
						documents = documents.concat(docs);
						pathmap = pathmap.concat(pthmp);
						if (!--pending) done(null, results, documents, pathmap);
					});
				} else {
					//results.push(file);

					if (!--pending) done(null, results, documents, pathmap);
				}
			});
		});
	});
};

////////////////////////

// 💾 WRITE THE FILE
function writeDocumentData(data) {
	fs.writeFile('site/documents.json', JSON.stringify(data), (err) => {
	  if (err) throw err;
	  console.log('💾 The Lunr document index has been created -> site/documents.json');
	});
}

function writePathmapData(data) {
	fs.writeFile('site/pathmap.json', JSON.stringify(data), (err) => {
	  if (err) throw err;
	  console.log('💾 The Lunr path map has been created -> site/pathmap.json');
	});
}

function addFederatedData(docsArray,pathsArray) {
	// Design System
	document = new Object();
	pathmapitem = new Object();
	document.title = "Design System";
	document.description = "UI UIkit component layout Front End Toolkit react patterns button accordion grid forms css javascript style guide";
	pathmapitem.description = "The Australian Government Design System provides a framework and a set of tools to help designers and developers build government products and services more easily.";
	pathmapitem.title = "Design System";
	pageid = pageid + 1;
	document.id = pageid;
	pathmapitem.id = pageid;
	pathmapitem.path = "https://designsystem.gov.au/";
	docsArray.push(document);
	pathsArray.push(pathmapitem);

	// Content Guide
	document = new Object();
	pathmapitem = new Object();
	document.title = "GOV.AU Content Guide";
	document.description = "A guide to help Australian Government teams design simple, clear and fast content. Content structure, writing style, punctuation and grammar, terms phrases, numbers, measurements formatting accessibility";
	pathmapitem.description = "A guide to help Australian Government teams design simple, clear and fast content.";
	pathmapitem.title = "GOV.AU Content Guide";
	pageid = pageid + 1;
	document.id = pageid;
	pathmapitem.id = pageid;
	pathmapitem.path = "https://guides.service.gov.au/content-guide/";
	docsArray.push(document);
	pathsArray.push(pathmapitem);
}

directoryWalker("./content/", function(err, dirs, documents, pathmap) {
	if (err) {
		throw err;
	}

	//const util = require('util')
	//console.log(util.inspect(pathmap, { maxArrayLength: null }))
	addFederatedData(documents,pathmap);
	writeDocumentData(documents);
	writePathmapData(pathmap);
});
<|endoftext|>


<commit_before>'use strict';
/* global jQuery:false */
/* global moment:false */
/* global valueNotEmpty:false */

angular.module('openhimConsoleApp')
  .controller('AuditsCtrl', function ($scope, $modal, $location, Api, Alerting, AuditLookups) {

    /***************************************************/
    /**         Initial page load functions           **/
    /***************************************************/
    $scope.isCollapsed = true;

    Api.AuditsFilterOptions.get(function(auditsFilterOptions){
      $scope.auditsFilterOptions = auditsFilterOptions;
    }, function(err){
      console.log( err );
    });

    /* setup default filter options */
    var setupAuditFilters = function(){

      //return results for the first page (10 results)
      $scope.showpage = 0;
      $scope.showlimit = 10;

      // setup audit lookup objects
      $scope.eventActionMap = AuditLookups.eventActionMap();
      $scope.eventOutcomeMap = AuditLookups.eventOutcomeMap();

      // setup default audits settings
      $scope.settings = {};
      $scope.settings.filter = {};
      if ( $location.search().limit ){ $scope.settings.filter.limit = $location.search().limit; }else{ $scope.settings.filter.limit = 10; }
      if ( $location.search().dateStart ){ $scope.settings.filter.dateStart = $location.search().dateStart; }else{ $scope.settings.filter.dateStart = ''; }
      if ( $location.search().dateEnd ){ $scope.settings.filter.dateEnd = $location.search().dateEnd; }else{ $scope.settings.filter.dateEnd = ''; }
      $scope.settings.list = {};
      $scope.settings.list.tabview = 'same';

      $scope.filters = {};
      $scope.filters.eventIdentification = {};
      if ( $location.search().eventID ){ $scope.filters.eventIdentification.eventID = $location.search().eventID; }
      if ( $location.search().eventTypeCode ){ $scope.filters.eventIdentification.eventTypeCode = $location.search().eventTypeCode; }
      if ( $location.search().eventActionCode ){ $scope.filters.eventIdentification.eventActionCode = $location.search().eventActionCode; }
      if ( $location.search().eventOutcomeIndicator ){ $scope.filters.eventIdentification.eventOutcomeIndicator = $location.search().eventOutcomeIndicator; }

      $scope.filters.participantObjectIdentification = {};
      $scope.filters.participantObjectIdentification.patientID = {};
      if ( $location.search().patientID ){ $scope.filters.participantObjectIdentification.patientID.patientID = $location.search().patientID; }
      if ( $location.search().assigningAuth ){ $scope.filters.participantObjectIdentification.patientID.assigningAuth = $location.search().assigningAuth; }
      if ( $location.search().assigningAuthID ){ $scope.filters.participantObjectIdentification.patientID.assigningAuthID = $location.search().assigningAuthID; }

      if ( $location.search().participantObjectID ){ $scope.filters.participantObjectIdentification.participantObjectID = $location.search().participantObjectID; }
      if ( $location.search().participantObjectIDTypeCode ){ $scope.filters.participantObjectIdentification.participantObjectIDTypeCode = $location.search().participantObjectIDTypeCode; }
      $scope.filters.participantObjectIdentification.participantObjectDetail = {};
      if ( $location.search().participantObjectDetailType ){ $scope.filters.participantObjectIdentification.participantObjectDetail.type = $location.search().participantObjectDetailType; }
      if ( $location.search().participantObjectDetailValue ){ $scope.filters.participantObjectIdentification.participantObjectDetail.value = $location.search().participantObjectDetailValue; }

      $scope.filters.activeParticipant = {};
      if ( $location.search().userID ){ $scope.filters.activeParticipant.userID = $location.search().userID; }
      if ( $location.search().roleIDCode ){ $scope.filters.activeParticipant.roleIDCode = $location.search().roleIDCode; }
      if ( $location.search().alternativeUserID ){ $scope.filters.activeParticipant.alternativeUserID = $location.search().alternativeUserID; }
      if ( $location.search().networkAccessPointID ){ $scope.filters.activeParticipant.networkAccessPointID = $location.search().networkAccessPointID; }

      $scope.filters.auditSourceIdentification = {};
      if ( $location.search().auditSourceID ){ $scope.filters.auditSourceIdentification.auditSourceID = $location.search().auditSourceID; }

    };
    setupAuditFilters();

    var consoleSession = localStorage.getItem('consoleSession');
    consoleSession = JSON.parse(consoleSession);
    $scope.consoleSession = consoleSession;
    var userSettings = consoleSession.sessionUserSettings;

    if ( userSettings ){
      if ( userSettings.filter ){

        if ( userSettings.filter.limit && userSettings.filter.limit !== 0 && userSettings.filter.limit === ''){
          $scope.settings.filter.limit = userSettings.filter.limit;
        }
      }

      if ( userSettings.list ){
        $scope.settings.list.tabview = userSettings.list.tabview;
      }
    }

    /***************************************************/
    /**         Initial page load functions           **/
    /***************************************************/

    /*************************************************************/
    /**         Audits List and Detail view functions           **/
    /*************************************************************/

    //setup filter options
    $scope.returnFilters = function(type){
      var filtersObject = {};
      var filterUrlParams = '';
      var filterDateStart, filterDateEnd;

      filtersObject.filterPage = $scope.showpage;
      filtersObject.filterLimit = $scope.showlimit;
      filterUrlParams += '&limit='+$scope.settings.filter.limit;

      /* ##### construct filters ##### */
      filtersObject.filters = {};

      // date filter
      filterDateStart = $scope.settings.filter.dateStart;
      filterDateEnd = $scope.settings.filter.dateEnd;
      if(filterDateStart && filterDateEnd){
        var startDate = moment(filterDateStart).format();
        var endDate = moment(filterDateEnd).endOf('day').format();
        filtersObject.filters['eventIdentification.eventDateTime'] = JSON.stringify( { '$gte': startDate, '$lte': endDate } );
        filterUrlParams += '&dateStart='+startDate;
        filterUrlParams += '&dateEnd='+endDate;
      }

      /* ----- filter by Patient ----- */
      var patientID = $scope.filters.participantObjectIdentification.patientID.patientID;
      var assigningAuth = $scope.filters.participantObjectIdentification.patientID.assigningAuth;
      var assigningAuthID = $scope.filters.participantObjectIdentification.patientID.assigningAuthID;

      // if not defined then set wildcard
      if ( assigningAuth === null || assigningAuth === undefined || assigningAuth === '' ){
        assigningAuth = '.*';
      }
      // if not defined then set wildcard
      if ( assigningAuthID === null || assigningAuthID === undefined || assigningAuthID === '' ){
        assigningAuthID = '.*';
      }

      // add patientID filter
      var participantPatientID = patientID+'\\^\\^\\^'+assigningAuth+'&'+assigningAuthID+'&.*';
      if ( valueNotEmpty(patientID) === true ) {
        filtersObject.filters['participantObjectIdentification.participantObjectID'] = JSON.stringify( participantPatientID);
        filterUrlParams += '&patientID='+patientID;
      }
      /* ----- filter by Patient ----- */

      /* ----- filter by Event ----- */
      // add eventID filter
      var eventTypeCode = $scope.filters.eventIdentification.eventTypeCode;
      if ( valueNotEmpty(eventTypeCode) === true ) {
        // construct object to query in mongo
        var eventTypeArray = eventTypeCode.split('---');
        filtersObject.filters['eventIdentification.eventTypeCode.code'] = eventTypeArray[0];
        filtersObject.filters['eventIdentification.eventTypeCode.codeSystemName'] = eventTypeArray[1];
        filtersObject.filters['eventIdentification.eventTypeCode.displayName'] = eventTypeArray[2];
        filterUrlParams += '&eventTypeCode='+eventTypeCode;
      }

      // add eventID filter
      var eventID = $scope.filters.eventIdentification.eventID;
      if ( valueNotEmpty(eventID) === true ) {
        var eventIDArray = eventID.split('---');
        filtersObject.filters['eventIdentification.eventID.code'] = eventIDArray[0];
        filtersObject.filters['eventIdentification.eventID.codeSystemName'] = eventIDArray[1];
        filtersObject.filters['eventIdentification.eventID.displayName'] = eventIDArray[2];
        filterUrlParams += '&eventID='+eventID;
      }

      // add eventActionCode filter
      var eventActionCode = $scope.filters.eventIdentification.eventActionCode;
      if ( valueNotEmpty(eventActionCode) === true ) {
        filtersObject.filters['eventIdentification.eventActionCode'] = eventActionCode;
        filterUrlParams += '&eventActionCode='+eventActionCode;
      }

      // add eventOutcomeIndicator filter
      var eventOutcomeIndicator = $scope.filters.eventIdentification.eventOutcomeIndicator;
      if ( valueNotEmpty(eventOutcomeIndicator) === true ) {
        filtersObject.filters['eventIdentification.eventOutcomeIndicator'] = eventOutcomeIndicator;
        filterUrlParams += '&eventOutcomeIndicator='+eventOutcomeIndicator;
      }
      /* ----- filter by Event ----- */

      /* ----- filter by Active Participant ----- */
      // add userID filter
      var userID = $scope.filters.activeParticipant.userID;
      if ( valueNotEmpty(userID) === true ) {
        filtersObject.filters['activeParticipant.userID'] = userID;
        filterUrlParams += '&userID='+userID;
      }

      // add alternativeUserID filter
      var alternativeUserID = $scope.filters.activeParticipant.alternativeUserID;
      if ( valueNotEmpty(alternativeUserID) === true ) {
        filtersObject.filters['activeParticipant.alternativeUserID'] = alternativeUserID;
        filterUrlParams += '&alternativeUserID='+alternativeUserID;
      }

      // add networkAccessPointID filter
      var networkAccessPointID = $scope.filters.activeParticipant.networkAccessPointID;
      if ( valueNotEmpty(networkAccessPointID) === true ) {
        filtersObject.filters['activeParticipant.networkAccessPointID'] = networkAccessPointID;
        filterUrlParams += '&networkAccessPointID='+networkAccessPointID;
      }

      // add eventID filter
      var roleIDCode = $scope.filters.activeParticipant.roleIDCode;
      if ( valueNotEmpty(roleIDCode) === true ) {
        var roleIDCodeArray = roleIDCode.split('---');
        filtersObject.filters['activeParticipant.roleIDCode.code'] = roleIDCodeArray[0];
        filtersObject.filters['activeParticipant.roleIDCode.codeSystemName'] = roleIDCodeArray[1];
        filtersObject.filters['activeParticipant.roleIDCode.displayName'] = roleIDCodeArray[2];
        filterUrlParams += '&roleIDCode='+roleIDCode;
      }
      /* ----- filter by Active Participant ----- */

      /* ----- filter by Participant Object ----- */
      // add objectID filter
      var objectID = $scope.filters.participantObjectIdentification.participantObjectID;
      if ( valueNotEmpty(objectID) === true ) {
        filterUrlParams += '&participantObjectID='+objectID;

        // if patientID set then update query to include 'AND' operator
        if ( valueNotEmpty(patientID) === true ) {
          filtersObject.filters['participantObjectIdentification.participantObjectID'] = { type: 'AND', patientID: participantPatientID, objectID: objectID };
        }else{
          filtersObject.filters['participantObjectIdentification.participantObjectID'] = JSON.stringify( objectID );
        }

      }

      // add objectIDTypeCode filter
      var participantObjectIDTypeCode = $scope.filters.participantObjectIdentification.participantObjectIDTypeCode;
      if ( valueNotEmpty(participantObjectIDTypeCode) === true ) {
        var participantObjectIDTypeCodeArray = participantObjectIDTypeCode.split('---');
        filtersObject.filters['participantObjectIdentification.participantObjectIDTypeCode.code'] = participantObjectIDTypeCodeArray[0];
        filtersObject.filters['participantObjectIdentification.participantObjectIDTypeCode.codeSystemName'] = participantObjectIDTypeCodeArray[1];
        filtersObject.filters['participantObjectIdentification.participantObjectIDTypeCode.displayName'] = participantObjectIDTypeCodeArray[2];
        filterUrlParams += '&participantObjectIDTypeCode='+participantObjectIDTypeCode;
      }

      // add objectDetailType filter
      var objectDetailType = $scope.filters.participantObjectIdentification.participantObjectDetail.type;
      if ( valueNotEmpty(objectDetailType) === true ) {
        filtersObject.filters['participantObjectIdentification.participantObjectDetail.type'] = objectDetailType;
        filterUrlParams += '&participantObjectDetailType='+objectDetailType;
      }

      // add objectDetailValue filter
      var objectDetailValue = $scope.filters.participantObjectIdentification.participantObjectDetail.value;
      if ( valueNotEmpty(objectDetailValue) === true ) {
        filtersObject.filters['participantObjectIdentification.participantObjectDetail.value'] = objectDetailValue;
        filterUrlParams += '&participantObjectDetailValue='+objectDetailValue;
      }
      /* ----- filter by Participant Object ----- */

      /* ----- filter by Audit Source ----- */
      // add auditSource filter
      var auditSourceID = $scope.filters.auditSourceIdentification.auditSourceID;
      if ( valueNotEmpty(auditSourceID) === true ) {
        filtersObject.filters['auditSourceIdentification.auditSourceID'] = auditSourceID;
        filterUrlParams += '&auditSourceID='+auditSourceID;
      }
      /* ----- filter by Audit Source ----- */

      /* ##### construct filters ##### */

      if ( type === 'urlParams' ){
        return filterUrlParams;
      }else if (type === 'filtersObject'){
        return filtersObject;
      }

    };

    var refreshSuccess = function (audits){
      // on success
      $scope.audits = audits;

      if( audits.length < $scope.showlimit ){
        jQuery('#loadMoreBtn').hide();

        if( audits.length === 0 ){
          Alerting.AlertAddMsg('bottom', 'warning', 'There are no audits for the current filters');
        }

      }else{
        //Show the load more button
        jQuery('#loadMoreBtn').show();
      }
    };

    var refreshError = function(err){
      // on error - Hide load more button and show error message
      jQuery('#loadMoreBtn').hide();
      Alerting.AlertAddServerMsg(err.status);
    };

    $scope.applyFiltersToUrl = function(){
      var curHashParams = window.location.hash;
      var filters = $scope.returnFilters('urlParams');
      var newHash = '#/audits?'+filters.substring(1);

      // just refresh audits list - no new params
      if ( curHashParams ===  newHash ){
        $scope.refreshAuditsList();
      }else{
        var baseUrl = $location.protocol() + '://' + $location.host() + ':' + $location.port() + '/';
        window.location = baseUrl + newHash;
      }
    };

    //Refresh audits list
    $scope.refreshAuditsList = function () {

      $scope.audits = null;
      Alerting.AlertReset();

      //reset the showpage filter to start at 0
      $scope.showpage = 0;
      $scope.showlimit = $scope.settings.filter.limit;

      Api.Audits.query( $scope.returnFilters('filtersObject'), refreshSuccess, refreshError);
    };
    //run the audit list view for the first time
    $scope.refreshAuditsList();

    //Refresh audits list
    $scope.loadMoreAudits = function () {
      $scope.busyLoadingMore = true;
      Alerting.AlertReset();

      $scope.showpage++;
      Api.Audits.query( $scope.returnFilters('filtersObject'), loadMoreSuccess, loadMoreError);
    };

    var loadMoreSuccess = function (audits){
      //on success
      $scope.audits = $scope.audits.concat(audits);
      //remove any duplicates objects found in the audits scope
      $scope.audits = jQuery.unique($scope.audits);

      if( audits.length < $scope.showlimit ){
        jQuery('#loadMoreBtn').hide();
        Alerting.AlertAddMsg('bottom', 'warning', 'There are no more audits to retrieve');
      }

      $scope.busyLoadingMore = false;
    };

    var loadMoreError = function(err){
      // on error - Hide load more button and show error message
      jQuery('#loadMoreBtn').hide();
      Alerting.AlertAddServerMsg(err.status);
    };

    //location provider - load audit details
    $scope.viewAuditDetails = function (path, $event) {
      //do audits details redirection when clicked on TD
      if( $event.target.tagName === 'TD' ){
        var baseUrl = $location.protocol() + '://' + $location.host() + ':' + $location.port() + '/#/';
        var txUrl = baseUrl + path;
        if ( $scope.settings.list.tabview && $scope.settings.list.tabview === 'new' ){
          window.open(txUrl, '_blank');
        }else{
          $location.path(path);
        }
      }
    };

    //Clear filter data end refresh audits scope
    $scope.clearFilters = function () {
      $scope.settings.filter.limit = 10;
      $scope.settings.filter.dateStart = '';
      $scope.settings.filter.dateEnd = '';
      $scope.settings.list.tabview = 'same';

      // clear filters by loading audits page again with no filters
      var baseUrl = $location.protocol() + '://' + $location.host() + ':' + $location.port() + '/#/';
      var path = 'audits';
      window.location = baseUrl + path;
    };

    /*************************************************************/
    /**         Audits List and Detail view functions           **/
    /*************************************************************/

  });
<commit_msg>Issue #326 OHM-193: refresh on clear<commit_after>'use strict';
/* global jQuery:false */
/* global moment:false */
/* global valueNotEmpty:false */

angular.module('openhimConsoleApp')
  .controller('AuditsCtrl', function ($scope, $modal, $location, Api, Alerting, AuditLookups) {

    /***************************************************/
    /**         Initial page load functions           **/
    /***************************************************/
    $scope.isCollapsed = true;

    Api.AuditsFilterOptions.get(function(auditsFilterOptions){
      $scope.auditsFilterOptions = auditsFilterOptions;
    }, function(err){
      console.log( err );
    });

    /* setup default filter options */
    var setupAuditFilters = function(){

      //return results for the first page (10 results)
      $scope.showpage = 0;
      $scope.showlimit = 10;

      // setup audit lookup objects
      $scope.eventActionMap = AuditLookups.eventActionMap();
      $scope.eventOutcomeMap = AuditLookups.eventOutcomeMap();

      // setup default audits settings
      $scope.settings = {};
      $scope.settings.filter = {};
      if ( $location.search().limit ){ $scope.settings.filter.limit = $location.search().limit; }else{ $scope.settings.filter.limit = 10; }
      if ( $location.search().dateStart ){ $scope.settings.filter.dateStart = $location.search().dateStart; }else{ $scope.settings.filter.dateStart = ''; }
      if ( $location.search().dateEnd ){ $scope.settings.filter.dateEnd = $location.search().dateEnd; }else{ $scope.settings.filter.dateEnd = ''; }
      $scope.settings.list = {};
      $scope.settings.list.tabview = 'same';

      $scope.filters = {};
      $scope.filters.eventIdentification = {};
      if ( $location.search().eventID ){ $scope.filters.eventIdentification.eventID = $location.search().eventID; }
      if ( $location.search().eventTypeCode ){ $scope.filters.eventIdentification.eventTypeCode = $location.search().eventTypeCode; }
      if ( $location.search().eventActionCode ){ $scope.filters.eventIdentification.eventActionCode = $location.search().eventActionCode; }
      if ( $location.search().eventOutcomeIndicator ){ $scope.filters.eventIdentification.eventOutcomeIndicator = $location.search().eventOutcomeIndicator; }

      $scope.filters.participantObjectIdentification = {};
      $scope.filters.participantObjectIdentification.patientID = {};
      if ( $location.search().patientID ){ $scope.filters.participantObjectIdentification.patientID.patientID = $location.search().patientID; }
      if ( $location.search().assigningAuth ){ $scope.filters.participantObjectIdentification.patientID.assigningAuth = $location.search().assigningAuth; }
      if ( $location.search().assigningAuthID ){ $scope.filters.participantObjectIdentification.patientID.assigningAuthID = $location.search().assigningAuthID; }

      if ( $location.search().participantObjectID ){ $scope.filters.participantObjectIdentification.participantObjectID = $location.search().participantObjectID; }
      if ( $location.search().participantObjectIDTypeCode ){ $scope.filters.participantObjectIdentification.participantObjectIDTypeCode = $location.search().participantObjectIDTypeCode; }
      $scope.filters.participantObjectIdentification.participantObjectDetail = {};
      if ( $location.search().participantObjectDetailType ){ $scope.filters.participantObjectIdentification.participantObjectDetail.type = $location.search().participantObjectDetailType; }
      if ( $location.search().participantObjectDetailValue ){ $scope.filters.participantObjectIdentification.participantObjectDetail.value = $location.search().participantObjectDetailValue; }

      $scope.filters.activeParticipant = {};
      if ( $location.search().userID ){ $scope.filters.activeParticipant.userID = $location.search().userID; }
      if ( $location.search().roleIDCode ){ $scope.filters.activeParticipant.roleIDCode = $location.search().roleIDCode; }
      if ( $location.search().alternativeUserID ){ $scope.filters.activeParticipant.alternativeUserID = $location.search().alternativeUserID; }
      if ( $location.search().networkAccessPointID ){ $scope.filters.activeParticipant.networkAccessPointID = $location.search().networkAccessPointID; }

      $scope.filters.auditSourceIdentification = {};
      if ( $location.search().auditSourceID ){ $scope.filters.auditSourceIdentification.auditSourceID = $location.search().auditSourceID; }

    };
    setupAuditFilters();

    var consoleSession = localStorage.getItem('consoleSession');
    consoleSession = JSON.parse(consoleSession);
    $scope.consoleSession = consoleSession;
    var userSettings = consoleSession.sessionUserSettings;

    if ( userSettings ){
      if ( userSettings.filter ){

        if ( userSettings.filter.limit && userSettings.filter.limit !== 0 && userSettings.filter.limit === ''){
          $scope.settings.filter.limit = userSettings.filter.limit;
        }
      }

      if ( userSettings.list ){
        $scope.settings.list.tabview = userSettings.list.tabview;
      }
    }

    /***************************************************/
    /**         Initial page load functions           **/
    /***************************************************/

    /*************************************************************/
    /**         Audits List and Detail view functions           **/
    /*************************************************************/

    //setup filter options
    $scope.returnFilters = function(type){
      var filtersObject = {};
      var filterUrlParams = '';
      var filterDateStart, filterDateEnd;

      filtersObject.filterPage = $scope.showpage;
      filtersObject.filterLimit = $scope.showlimit;
      filterUrlParams += '&limit='+$scope.settings.filter.limit;

      /* ##### construct filters ##### */
      filtersObject.filters = {};

      // date filter
      filterDateStart = $scope.settings.filter.dateStart;
      filterDateEnd = $scope.settings.filter.dateEnd;
      if(filterDateStart && filterDateEnd){
        var startDate = moment(filterDateStart).format();
        var endDate = moment(filterDateEnd).endOf('day').format();
        filtersObject.filters['eventIdentification.eventDateTime'] = JSON.stringify( { '$gte': startDate, '$lte': endDate } );
        filterUrlParams += '&dateStart='+startDate;
        filterUrlParams += '&dateEnd='+endDate;
      }

      /* ----- filter by Patient ----- */
      var patientID = $scope.filters.participantObjectIdentification.patientID.patientID;
      var assigningAuth = $scope.filters.participantObjectIdentification.patientID.assigningAuth;
      var assigningAuthID = $scope.filters.participantObjectIdentification.patientID.assigningAuthID;

      // if not defined then set wildcard
      if ( assigningAuth === null || assigningAuth === undefined || assigningAuth === '' ){
        assigningAuth = '.*';
      }
      // if not defined then set wildcard
      if ( assigningAuthID === null || assigningAuthID === undefined || assigningAuthID === '' ){
        assigningAuthID = '.*';
      }

      // add patientID filter
      var participantPatientID = patientID+'\\^\\^\\^'+assigningAuth+'&'+assigningAuthID+'&.*';
      if ( valueNotEmpty(patientID) === true ) {
        filtersObject.filters['participantObjectIdentification.participantObjectID'] = JSON.stringify( participantPatientID);
        filterUrlParams += '&patientID='+patientID;
      }
      /* ----- filter by Patient ----- */

      /* ----- filter by Event ----- */
      // add eventID filter
      var eventTypeCode = $scope.filters.eventIdentification.eventTypeCode;
      if ( valueNotEmpty(eventTypeCode) === true ) {
        // construct object to query in mongo
        var eventTypeArray = eventTypeCode.split('---');
        filtersObject.filters['eventIdentification.eventTypeCode.code'] = eventTypeArray[0];
        filtersObject.filters['eventIdentification.eventTypeCode.codeSystemName'] = eventTypeArray[1];
        filtersObject.filters['eventIdentification.eventTypeCode.displayName'] = eventTypeArray[2];
        filterUrlParams += '&eventTypeCode='+eventTypeCode;
      }

      // add eventID filter
      var eventID = $scope.filters.eventIdentification.eventID;
      if ( valueNotEmpty(eventID) === true ) {
        var eventIDArray = eventID.split('---');
        filtersObject.filters['eventIdentification.eventID.code'] = eventIDArray[0];
        filtersObject.filters['eventIdentification.eventID.codeSystemName'] = eventIDArray[1];
        filtersObject.filters['eventIdentification.eventID.displayName'] = eventIDArray[2];
        filterUrlParams += '&eventID='+eventID;
      }

      // add eventActionCode filter
      var eventActionCode = $scope.filters.eventIdentification.eventActionCode;
      if ( valueNotEmpty(eventActionCode) === true ) {
        filtersObject.filters['eventIdentification.eventActionCode'] = eventActionCode;
        filterUrlParams += '&eventActionCode='+eventActionCode;
      }

      // add eventOutcomeIndicator filter
      var eventOutcomeIndicator = $scope.filters.eventIdentification.eventOutcomeIndicator;
      if ( valueNotEmpty(eventOutcomeIndicator) === true ) {
        filtersObject.filters['eventIdentification.eventOutcomeIndicator'] = eventOutcomeIndicator;
        filterUrlParams += '&eventOutcomeIndicator='+eventOutcomeIndicator;
      }
      /* ----- filter by Event ----- */

      /* ----- filter by Active Participant ----- */
      // add userID filter
      var userID = $scope.filters.activeParticipant.userID;
      if ( valueNotEmpty(userID) === true ) {
        filtersObject.filters['activeParticipant.userID'] = userID;
        filterUrlParams += '&userID='+userID;
      }

      // add alternativeUserID filter
      var alternativeUserID = $scope.filters.activeParticipant.alternativeUserID;
      if ( valueNotEmpty(alternativeUserID) === true ) {
        filtersObject.filters['activeParticipant.alternativeUserID'] = alternativeUserID;
        filterUrlParams += '&alternativeUserID='+alternativeUserID;
      }

      // add networkAccessPointID filter
      var networkAccessPointID = $scope.filters.activeParticipant.networkAccessPointID;
      if ( valueNotEmpty(networkAccessPointID) === true ) {
        filtersObject.filters['activeParticipant.networkAccessPointID'] = networkAccessPointID;
        filterUrlParams += '&networkAccessPointID='+networkAccessPointID;
      }

      // add eventID filter
      var roleIDCode = $scope.filters.activeParticipant.roleIDCode;
      if ( valueNotEmpty(roleIDCode) === true ) {
        var roleIDCodeArray = roleIDCode.split('---');
        filtersObject.filters['activeParticipant.roleIDCode.code'] = roleIDCodeArray[0];
        filtersObject.filters['activeParticipant.roleIDCode.codeSystemName'] = roleIDCodeArray[1];
        filtersObject.filters['activeParticipant.roleIDCode.displayName'] = roleIDCodeArray[2];
        filterUrlParams += '&roleIDCode='+roleIDCode;
      }
      /* ----- filter by Active Participant ----- */

      /* ----- filter by Participant Object ----- */
      // add objectID filter
      var objectID = $scope.filters.participantObjectIdentification.participantObjectID;
      if ( valueNotEmpty(objectID) === true ) {
        filterUrlParams += '&participantObjectID='+objectID;

        // if patientID set then update query to include 'AND' operator
        if ( valueNotEmpty(patientID) === true ) {
          filtersObject.filters['participantObjectIdentification.participantObjectID'] = { type: 'AND', patientID: participantPatientID, objectID: objectID };
        }else{
          filtersObject.filters['participantObjectIdentification.participantObjectID'] = JSON.stringify( objectID );
        }

      }

      // add objectIDTypeCode filter
      var participantObjectIDTypeCode = $scope.filters.participantObjectIdentification.participantObjectIDTypeCode;
      if ( valueNotEmpty(participantObjectIDTypeCode) === true ) {
        var participantObjectIDTypeCodeArray = participantObjectIDTypeCode.split('---');
        filtersObject.filters['participantObjectIdentification.participantObjectIDTypeCode.code'] = participantObjectIDTypeCodeArray[0];
        filtersObject.filters['participantObjectIdentification.participantObjectIDTypeCode.codeSystemName'] = participantObjectIDTypeCodeArray[1];
        filtersObject.filters['participantObjectIdentification.participantObjectIDTypeCode.displayName'] = participantObjectIDTypeCodeArray[2];
        filterUrlParams += '&participantObjectIDTypeCode='+participantObjectIDTypeCode;
      }

      // add objectDetailType filter
      var objectDetailType = $scope.filters.participantObjectIdentification.participantObjectDetail.type;
      if ( valueNotEmpty(objectDetailType) === true ) {
        filtersObject.filters['participantObjectIdentification.participantObjectDetail.type'] = objectDetailType;
        filterUrlParams += '&participantObjectDetailType='+objectDetailType;
      }

      // add objectDetailValue filter
      var objectDetailValue = $scope.filters.participantObjectIdentification.participantObjectDetail.value;
      if ( valueNotEmpty(objectDetailValue) === true ) {
        filtersObject.filters['participantObjectIdentification.participantObjectDetail.value'] = objectDetailValue;
        filterUrlParams += '&participantObjectDetailValue='+objectDetailValue;
      }
      /* ----- filter by Participant Object ----- */

      /* ----- filter by Audit Source ----- */
      // add auditSource filter
      var auditSourceID = $scope.filters.auditSourceIdentification.auditSourceID;
      if ( valueNotEmpty(auditSourceID) === true ) {
        filtersObject.filters['auditSourceIdentification.auditSourceID'] = auditSourceID;
        filterUrlParams += '&auditSourceID='+auditSourceID;
      }
      /* ----- filter by Audit Source ----- */

      /* ##### construct filters ##### */

      if ( type === 'urlParams' ){
        return filterUrlParams;
      }else if (type === 'filtersObject'){
        return filtersObject;
      }

    };

    var refreshSuccess = function (audits){
      // on success
      $scope.audits = audits;

      if( audits.length < $scope.showlimit ){
        jQuery('#loadMoreBtn').hide();

        if( audits.length === 0 ){
          Alerting.AlertAddMsg('bottom', 'warning', 'There are no audits for the current filters');
        }

      }else{
        //Show the load more button
        jQuery('#loadMoreBtn').show();
      }
    };

    var refreshError = function(err){
      // on error - Hide load more button and show error message
      jQuery('#loadMoreBtn').hide();
      Alerting.AlertAddServerMsg(err.status);
    };

    $scope.applyFiltersToUrl = function(){
      var curHashParams = window.location.hash;
      var filters = $scope.returnFilters('urlParams');
      var newHash = '#/audits?'+filters.substring(1);

      // just refresh audits list - no new params
      if ( curHashParams ===  newHash ){
        $scope.refreshAuditsList();
      }else{
        var baseUrl = $location.protocol() + '://' + $location.host() + ':' + $location.port() + '/';
        window.location = baseUrl + newHash;
      }
    };

    //Refresh audits list
    $scope.refreshAuditsList = function () {

      $scope.audits = null;
      Alerting.AlertReset();

      //reset the showpage filter to start at 0
      $scope.showpage = 0;
      $scope.showlimit = $scope.settings.filter.limit;

      Api.Audits.query( $scope.returnFilters('filtersObject'), refreshSuccess, refreshError);
    };
    //run the audit list view for the first time
    $scope.refreshAuditsList();

    //Refresh audits list
    $scope.loadMoreAudits = function () {
      $scope.busyLoadingMore = true;
      Alerting.AlertReset();

      $scope.showpage++;
      Api.Audits.query( $scope.returnFilters('filtersObject'), loadMoreSuccess, loadMoreError);
    };

    var loadMoreSuccess = function (audits){
      //on success
      $scope.audits = $scope.audits.concat(audits);
      //remove any duplicates objects found in the audits scope
      $scope.audits = jQuery.unique($scope.audits);

      if( audits.length < $scope.showlimit ){
        jQuery('#loadMoreBtn').hide();
        Alerting.AlertAddMsg('bottom', 'warning', 'There are no more audits to retrieve');
      }

      $scope.busyLoadingMore = false;
    };

    var loadMoreError = function(err){
      // on error - Hide load more button and show error message
      jQuery('#loadMoreBtn').hide();
      Alerting.AlertAddServerMsg(err.status);
    };

    //location provider - load audit details
    $scope.viewAuditDetails = function (path, $event) {
      //do audits details redirection when clicked on TD
      if( $event.target.tagName === 'TD' ){
        var baseUrl = $location.protocol() + '://' + $location.host() + ':' + $location.port() + '/#/';
        var txUrl = baseUrl + path;
        if ( $scope.settings.list.tabview && $scope.settings.list.tabview === 'new' ){
          window.open(txUrl, '_blank');
        }else{
          $location.path(path);
        }
      }
    };

    //Clear filter data end refresh audits scope
    $scope.clearFilters = function () {
      $scope.settings.filter.limit = 10;
      $scope.settings.filter.dateStart = '';
      $scope.settings.filter.dateEnd = '';
      $scope.settings.list.tabview = 'same';

      // clear filters by loading audits page again with no filters
      var baseUrl = $location.protocol() + '://' + $location.host() + ':' + $location.port() + '/#/';
      var path = 'audits';
      window.location = baseUrl + path;

      $scope.refreshAuditsList();
    };

    /*************************************************************/
    /**         Audits List and Detail view functions           **/
    /*************************************************************/

  });
<|endoftext|>