<commit_before>jQuery.noConflict();

(function($) {

  var $wall,
      $cont,
      contWidth = 0,
      hasPhoto = false,
      hasVis = false,
      graph;

  jQuery(document).ready( function($) {

    $cont = $('body > .container');
    contWidth = $cont.width();

    hasPhoto = $('#photo').length > 0;        // check if there is a photo entity
    hasVis = $('#viz-container').length > 0;  // check if there is a visualization

    /* -------------------- Setup home slider --------------------- */
    if ($('#home-slider-list').length) {

      $('#home-slider').carousel('pause');

      $('#home-slider-list .item a').click(function(e){
        e.preventDefault();
        if( $(this).hasClass('active') ) return true;
        $('#home-slider-list .active').removeClass('active');
        $(this).addClass('active');
        $('#home-slider').carousel( parseInt($(this).attr('href').substr(6), 0) );
      });
    }

    //$('#flex1').flexslider();

    /* -------------------- Setup layouts --------------------- */
    $wall = $('#wall, .extra-wall');
    $wall.imagesLoaded(function() {
      $wall.packery({
        itemSelector: '.item',
        columnWidth: $wall.width() / 12
      });
    });

    /* -------------------- Setup visualization --------------- */
    if (hasVis) {
      graph = new NetworkGraph("#viz-container", "#infobox");
      graph.loadRootNode( $('#viz-container').data('path') );
      $('#control-fullscreen, #control-fullscreen-exit').click(function() {
        $('#viz-container').toggleClass('fullscreen');
        graph.resize();
        return false;
      });
      $('#control-zoom-in').click(function() { graph.zoomIn(); return false; });
      $('#control-zoom-out').click(function() { graph.zoomOut(); return false; });
      $('#control-zoom-reset').click(function() { graph.zoomReset(); return false; });
      $('#control-help').click(function() { return false; });
      $('#visualization-controls a').tooltip();
    }

    /* -------------------- Setup photo --------------------- */
    if (hasPhoto) {
      anno.setProperties({ hi_stroke: '#6bb21b', });
      anno.addHandler('onMouseOverAnnotation', onAnnoHover);
      anno.addHandler('onEditorShown', onAnnoEditorShown);
      anno.addHandler('onAnnotationCreated', onAnnoReload);
      anno.addHandler('onAnnotationUpdated', onAnnoReload);
      anno.addHandler('onAnnotationRemoved', onAnnoReload);
      anno.addPlugin('RESTStorage', {
        base_url: '/photos/'+$('#photo').data('photoid')+'/annotations',
        read_only: $('#photo').data('readonly')
      });

      // Setup Embed Btn
      if ($('.embed-btn').length > 0) {
        var embedId = $('.embed-btn').attr('href').substring(1);
        $('.embed-code input').val('

');
        $('.embed-btn').click(function(e){
          e.preventDefault();
          $('.embed-code').toggle().focus();
          $('.embed-code input').select();
        });
      }
    }

    // On Annotorious Mouse Over Handler
    function onAnnoHover(e) {
      if (e.K === undefined) return true;

      var $annoPopup = $('.annotorious-popup');

      // Align title right if its placed at the right half of the picture
      if (e.K.shapes[0].geometry.x > 0.5) {
        $annoPopup.css('left', $annoPopup.position().left - $annoPopup.width() - 16 + (e.K.shapes[0].geometry.width*$('.annotorious-annotationlayer').width()) );
      }

      if ($('#photo').data('readonly')) {
        $('.annotorious-popup-buttons').remove(); // Hide edit buttons if is read only
      }
    }

    // On Annotorious Editor is Shown to create a new or edit an existing annotation
    function onAnnoEditorShown(e) {
      var people,
          $input = $('.annotorious-editor .annotorious-editor-text'),
          $results = $('

');

      // Get .json with all people list
      $.getJSON( '/entities.json', function(data) {
        people = data;
      });

      $('.annotorious-editor').append( $results );

      if (!e) {   // Create new Annotation
        $input.attr('placeholder', 'Añade una persona...');
      } else {    // Edit existing Annotation
        $input.val( e.name );
      }

      // Listen KeyUp Event
      $input.bind( 'keyup', function(e) {
        var index,
            code = e.keyCode;

        // code == Enter:  select highlighted item
        if (code == 13) {
          if ($results.children().size() > 0) {
            index = $results.children().index( $results.children('.hover') );
            index = (index > 0) ? index : 0;
            $results.children().eq(index).trigger('click');
          }
        }
        // code == up/down arrows: move along items
        else if (code == 40 || code == 38) {
          if ($results.children().size() > 0) {
            index = $results.children().index( $results.children('.hover') );
            $results.children().removeClass('hover');
            index = (code == 38) ? index-1 : index+1;
            if (index >= $results.children().size()) {
              index = 0;
            } else if (index < 0) {
              index = $results.children().size()-1;
            }
            $results.children().eq(index).addClass('hover');
          }
        }
        // code == a letter: do autocomplete
        else {
          var filter = $(this).val().toLowerCase();

          // Skip if there's no text
          if (filter.trim() === ''){
            $results.empty();
            return;
          }

          // Filter people
          if (people) {
            var peopleFiltered = people.filter( function (val,key) { return (val.name.toLowerCase().indexOf(filter) === 0); } );
            $results.empty();
            $.each( peopleFiltered, function( key,val ) {
              $results.append(''+val.name+'');
            });

            // Select suggested Person on click
            $results.find('a').click(function(e){
              e.preventDefault();
              $input.val( $(this).html() ).focus();
              $results.empty();
            });
          }
        }
      });
    }

    // On Annotation changes, reload the page to show the updated info
    function onAnnoReload(e) {
      window.location.reload();
    }

    /* -------------------- Setup Resize --------------------- */
    onResize();
    $(window).bind("resize", onResize);

    /* -------------------- Misc functions ------------------- */
    // Back to Top
    $('#under-footer-back-to-top a').click(function(){
      $('html, body').animate({scrollTop:0}, 300);
      return false;
    });

    // Related entities sidebar
    if ( $('.extra-related-entity').length > 0 ) {
      $('#related-entities-toggle').click(function(){
        $('.extra-related-entity').slideToggle();
        $('#related-entities-toggle').hide();
      });
    } else {
      $('#related-entities-toggle').hide();
    }

    // Label toggling on/off
    $('.label.toggable').click(function() {
      $(this).toggleClass('active, inactive');
    });

    // FooTable
    $('.footable').footable();

    // Newsletter subscription
    $('#mce-EMAIL, #mce-EMAIL-footer').click(function() {
      $(this).val('');
      $(this).css('border', 'none');
    });

  });

  /* -------------------- Resize --------------------- */
  function onResize(e) {

    if ($cont && contWidth !== $cont.width()) {

      contWidth = $cont.width();

      // Update packery column width
      $wall.packery({
        columnWidth: $wall.width() / 12
      });

      // Reset Annotorious
      if (hasPhoto) {
        anno.reset();
        anno.addPlugin('RESTStorage', {
          base_url: '/photos/'+$('#photo').data('photoid')+'/annotations',
          read_only: $('#photo').data('readonly')
        });
        $('.annotorious-es-plugin-load-outer').hide();
      }

      // Resize visualization
      if (hasVis) {
        graph.resize();
      }
    }
    else if (hasVis && $('#viz-container').hasClass('fullscreen')) {
      graph.resize();   // always resize when visualization is fullscreen
    }
  }

})(jQuery);<commit_msg>Improve autocomplete in Annotations<commit_after>jQuery.noConflict();

(function($) {

  var $wall,
      $cont,
      contWidth = 0,
      hasPhoto = false,
      hasVis = false,
      graph;

  jQuery(document).ready( function($) {

    $cont = $('body > .container');
    contWidth = $cont.width();

    hasPhoto = $('#photo').length > 0;        // check if there is a photo entity
    hasVis = $('#viz-container').length > 0;  // check if there is a visualization

    /* -------------------- Setup home slider --------------------- */
    if ($('#home-slider-list').length) {

      $('#home-slider').carousel('pause');

      $('#home-slider-list .item a').click(function(e){
        e.preventDefault();
        if( $(this).hasClass('active') ) return true;
        $('#home-slider-list .active').removeClass('active');
        $(this).addClass('active');
        $('#home-slider').carousel( parseInt($(this).attr('href').substr(6), 0) );
      });
    }

    //$('#flex1').flexslider();

    /* -------------------- Setup layouts --------------------- */
    $wall = $('#wall, .extra-wall');
    $wall.imagesLoaded(function() {
      $wall.packery({
        itemSelector: '.item',
        columnWidth: $wall.width() / 12
      });
    });

    /* -------------------- Setup visualization --------------- */
    if (hasVis) {
      graph = new NetworkGraph("#viz-container", "#infobox");
      graph.loadRootNode( $('#viz-container').data('path') );
      $('#control-fullscreen, #control-fullscreen-exit').click(function() {
        $('#viz-container').toggleClass('fullscreen');
        graph.resize();
        return false;
      });
      $('#control-zoom-in').click(function() { graph.zoomIn(); return false; });
      $('#control-zoom-out').click(function() { graph.zoomOut(); return false; });
      $('#control-zoom-reset').click(function() { graph.zoomReset(); return false; });
      $('#control-help').click(function() { return false; });
      $('#visualization-controls a').tooltip();
    }

    /* -------------------- Setup photo --------------------- */
    if (hasPhoto) {
      anno.setProperties({ hi_stroke: '#6bb21b', });
      anno.addHandler('onMouseOverAnnotation', onAnnoHover);
      anno.addHandler('onEditorShown', onAnnoEditorShown);
      anno.addHandler('onAnnotationCreated', onAnnoReload);
      anno.addHandler('onAnnotationUpdated', onAnnoReload);
      anno.addHandler('onAnnotationRemoved', onAnnoReload);
      anno.addPlugin('RESTStorage', {
        base_url: '/photos/'+$('#photo').data('photoid')+'/annotations',
        read_only: $('#photo').data('readonly')
      });

      // Setup Embed Btn
      if ($('.embed-btn').length > 0) {
        var embedId = $('.embed-btn').attr('href').substring(1);
        $('.embed-code input').val('

');
        $('.embed-btn').click(function(e){
          e.preventDefault();
          $('.embed-code').toggle().focus();
          $('.embed-code input').select();
        });
      }
    }

    // On Annotorious Mouse Over Handler
    function onAnnoHover(e) {
      if (e.K === undefined) return true;

      var $annoPopup = $('.annotorious-popup');

      // Align title right if its placed at the right half of the picture
      if (e.K.shapes[0].geometry.x > 0.5) {
        $annoPopup.css('left', $annoPopup.position().left - $annoPopup.width() - 16 + (e.K.shapes[0].geometry.width*$('.annotorious-annotationlayer').width()) );
      }

      if ($('#photo').data('readonly')) {
        $('.annotorious-popup-buttons').remove(); // Hide edit buttons if is read only
      }
    }

    // On Annotorious Editor is Shown to create a new or edit an existing annotation
    function onAnnoEditorShown(e) {
      var people = null,
          $input = $('.annotorious-editor .annotorious-editor-text'),
          $results = $('

');

      $('.annotorious-editor').append( $results );

      if (!e) {   // Create new Annotation
        $input.attr('placeholder', 'Añade una persona...');
      } else {    // Edit existing Annotation
        $input.val( e.name );
      }

      // Get .json with all people list
      $.getJSON( '/entities.json', function(data) {
        people = data;
        $input.trigger( 'keyup' );  // force keyup event when entities.json is loaded
      });

      // Listen KeyUp Event
      $input.bind( 'keyup', function(e) {
        var index,
            code = e.keyCode;

        // code == Enter:  select highlighted item
        if (code == 13) {
          if ($results.children().size() > 0) {
            index = $results.children().index( $results.children('.hover') );
            index = (index > 0) ? index : 0;
            $results.children().eq(index).trigger('click');
          }
        }
        // code == up/down arrows: move along items
        else if (code == 40 || code == 38) {
          if ($results.children().size() > 0) {
            index = $results.children().index( $results.children('.hover') );
            $results.children().removeClass('hover');
            index = (code == 38) ? index-1 : index+1;
            if (index >= $results.children().size()) {
              index = 0;
            } else if (index < 0) {
              index = $results.children().size()-1;
            }
            $results.children().eq(index).addClass('hover');
          }
        }
        // code == a letter: do autocomplete
        else {

          if( people === null ) return;

          var filter = $(this).val().toLowerCase();

          // Skip if there's no text
          if (filter.trim() === ''){
            $results.empty();
            return;
          }

          // Filter people
          var peopleFiltered = people.filter( function (val,key) { return (val.name.toLowerCase().indexOf(filter) !== -1 ); });
          $results.empty();
          $.each( peopleFiltered, function( key,val ) {
            $results.append(''+val.name+'');
          });

          // Select suggested Person on click
          $results.find('a').click(function(e){
            e.preventDefault();
            $input.val( $(this).html() ).focus();
            $results.empty();
          });
        }
      });
    }

    // On Annotation changes, reload the page to show the updated info
    function onAnnoReload(e) {
      window.location.reload();
    }

    /* -------------------- Setup Resize --------------------- */
    onResize();
    $(window).bind("resize", onResize);

    /* -------------------- Misc functions ------------------- */
    // Back to Top
    $('#under-footer-back-to-top a').click(function(){
      $('html, body').animate({scrollTop:0}, 300);
      return false;
    });

    // Related entities sidebar
    if ( $('.extra-related-entity').length > 0 ) {
      $('#related-entities-toggle').click(function(){
        $('.extra-related-entity').slideToggle();
        $('#related-entities-toggle').hide();
      });
    } else {
      $('#related-entities-toggle').hide();
    }

    // Label toggling on/off
    $('.label.toggable').click(function() {
      $(this).toggleClass('active, inactive');
    });

    // FooTable
    $('.footable').footable();

    // Newsletter subscription
    $('#mce-EMAIL, #mce-EMAIL-footer').click(function() {
      $(this).val('');
      $(this).css('border', 'none');
    });

  });

  /* -------------------- Resize --------------------- */
  function onResize(e) {

    if ($cont && contWidth !== $cont.width()) {

      contWidth = $cont.width();

      // Update packery column width
      $wall.packery({
        columnWidth: $wall.width() / 12
      });

      // Reset Annotorious
      if (hasPhoto) {
        anno.reset();
        anno.addPlugin('RESTStorage', {
          base_url: '/photos/'+$('#photo').data('photoid')+'/annotations',
          read_only: $('#photo').data('readonly')
        });
        $('.annotorious-es-plugin-load-outer').hide();
      }

      // Resize visualization
      if (hasVis) {
        graph.resize();
      }
    }
    else if (hasVis && $('#viz-container').hasClass('fullscreen')) {
      graph.resize();   // always resize when visualization is fullscreen
    }
  }

})(jQuery);<|endoftext|>


<commit_before>/* =========================================================
 * Extra scripts for beta designs
 * ========================================================= */

/*
 *= require dashboard
 *= require jquery.cookie
 *= require wysihtml5-0.3.0_rc2
 *= require bootstrap-wysihtml5-0.0.2
 *= require bootstrap-datepicker
 */

jQuery(function ($) {

  //render out templates function
  var renderExternalTmpl = function(item) {
    var file = '/design/templates/' + item.name;
    if ($(item.selector).length > 0) {
      $.when($.get(file)).done(function(tmplData) {
        $(item.selector).append(tmplData)
        //$.templates({ tmpl: tmplData });
        //$(item.selector).append($.render.tmpl(item.data));
      });
    }
  }

  //ACTUALLY renderout templates
  renderExternalTmpl({ name: 'help', selector: '#templates', data: {} });

  renderExternalTmpl({ name: 'confirm', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'comingsoon', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newasset', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newentity', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newfacility', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newsystem', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newcontrol', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'auditcycle', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'peopleselector', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'referenceselector', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newperson', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newreference', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newentity', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newproduct', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newsection', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'newthreat', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'mappedcontrols', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'mappedcontrolsfull', selector: '#templates', data: {} });

  // new modals START
  renderExternalTmpl({ name: 'redesignNewProgram', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'redesignSelectPerson', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'redesignNewControlWide', selector: '#templates', data: {} });
  renderExternalTmpl({ name: 'redesignNewSectionWide', selector: '#templates', data: {} });

  // new modals END
  renderExternalTmpl({ name: 'newpersonBasic', selector: '#templates', data: {} });

  renderExternalTmpl({ name: 'newtransaction', selector: '#templates', data: {} });

  renderExternalTmpl({ name: 'auditdefaultscope', selector: '#templates', data: {} });

  renderExternalTmpl({ name: 'sendauditorinvite', selector: '#templates', data: {} });

  renderExternalTmpl({ name: 'neauditscheduleitem', selector: '#templates', data: {} });

  renderExternalTmpl({ name: 'auditmeetingnotice', selector: '#templates', data: {} });

  //


<commit_before>'use strict';

/**
 * User and user-session specific configuration
 */
module.exports = {
  facebook: {
    client_id: '', // configure.py: facebook
    client_secret: '', // configure.py: facebook
    auth_callback_url: '/api/user/access/facebook/callback', // configure.py: facebook
    connect_callback_url: '/api/user/connect/facebook/callback' // configure.py: facebook
  },
  google: {
    client_id: '', // configure.py: google
    client_secret: '', // configure.py: google
    auth_callback_url: '/api/user/access/google/callback', // configure.py: google
    connect_callback_url: '/api/user/connect/google/callback' // configure.py: google
  },
  local: {
    username_field: 'local_email',
    username_max_length: 254, // ensure this agrees with value in client/js/apps/user/entities.js
    password_field: 'local_password',
    password_max_length: 256
  },
  twitter: {
    consumer_key: '', // configure.py: twitter
    consumer_secret: '', // configure.py: twitter
    auth_callback_url: '/api/user/access/twitter/callback', // configure.py: twitter
    connect_callback_url: '/api/user/connect/twitter/callback' // configure.py: twitter
  },
  logged_in_cookie_name: 'logged_in',
  session: {
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 7, // default to one week
      secure: true
    },
    resave: false, // to avoid race conditions, no need to be true so long as storage method supports save
    rolling: true, // force cookie to be set on every response, resetting the expiration date
    secret: 'default', // can not be randomly generated else sessions can't be shared across nodes in cluster
    store: {
      host: 'localhost', // configure.py: store
      port: 6379, // configure.py: store
      db: 3 // configure.py: store
    }
  },
  salt_rounds: 10
};
<commit_msg>server - user config - facebook and google scope back into config<commit_after>'use strict';

/**
 * User and user-session specific configuration
 */
module.exports = {
  facebook: {
    client_id: '', // configure.py: facebook
    client_secret: '', // configure.py: facebook
    auth_callback_url: '/api/user/access/facebook/callback', // configure.py: facebook
    connect_callback_url: '/api/user/connect/facebook/callback', // configure.py: facebook
    scope: ['public_profile', 'email']
  },
  google: {
    client_id: '', // configure.py: google
    client_secret: '', // configure.py: google
    auth_callback_url: '/api/user/access/google/callback', // configure.py: google
    connect_callback_url: '/api/user/connect/google/callback', // configure.py: google
    scope: ['profile', 'email']
  },
  local: {
    username_field: 'local_email',
    username_max_length: 254, // ensure this agrees with value in client/js/apps/user/entities.js
    password_field: 'local_password',
    password_max_length: 256
  },
  twitter: {
    consumer_key: '', // configure.py: twitter
    consumer_secret: '', // configure.py: twitter
    auth_callback_url: '/api/user/access/twitter/callback', // configure.py: twitter
    connect_callback_url: '/api/user/connect/twitter/callback' // configure.py: twitter
  },
  logged_in_cookie_name: 'logged_in',
  session: {
    cookie: {
      maxAge: 1000 * 60 * 60 * 24 * 7, // default to one week
      secure: true
    },
    resave: false, // to avoid race conditions, no need to be true so long as storage method supports save
    rolling: true, // force cookie to be set on every response, resetting the expiration date
    secret: 'default', // can not be randomly generated else sessions can't be shared across nodes in cluster
    store: {
      host: 'localhost', // configure.py: store
      port: 6379, // configure.py: store
      db: 3 // configure.py: store
    }
  },
  salt_rounds: 10
};
<|endoftext|>


<commit_before>//= require_self
//= require_tree ./editor
Mousetrap.stopCallback = function(e, element, combo) {
  // stop for input, select, and textarea
  return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA';
};

var Editor = function(options) {
  this.editable_selector = options.editable;
  this.editable = $(options.editable);

  this.selectEnd();
  this.sanitize = new Editor.Sanitize(this.editable);
  this.formator = new Editor.Formator(this);
  this.formator.exec('defaultParagraphSeparator', 'p');

  this.undoManager = new Editor.UndoManager(this.editable);

  if (options.toolbar) {
    this.toolbar = new Editor.Toolbar(this, options.toolbar);
    this.toolbar.detectState();
  }

  this.connectShortcuts();

  this.initParagraph();

  var _this = this;
  this.editable.on('keyup mouseup', function() {
    _this.storeRange();
  });

  this.editable.on({
    keyup: function(event) {
      _this.keyup(event);
    },
    keydown: function(event) {
      _this.keydown(event);
    },
    input: function(event) {
      _this.input(event);
    },
    paste: function(event) {
      _this.paste(event);
    }
  });

  this.is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
  this.is_safari = navigator.userAgent.indexOf("Safari") > -1 && !this.is_chrome;

  // In mac, chrome in safari trigger input event when typing pinyin,
  // so use textInput event.
  if (this.is_chrome || this.is_safari) {
    this.editable.on('textInput', function() {
      setTimeout(function() {
        _this.undoManager.save();
        _this.editable.trigger('editor:change');
      }, 0); // webkit don't get right range offset, so setTimout to fix
    });
  } else {
    this.editable.on('input', function() {
      setTimeout(function() {
        _this.undoManager.save();
        _this.editable.trigger('editor:change');
      }, 0); // webkit don't get right range offset, so setTimout to fix
    });
  }
};

Editor.prototype = {
  shortcuts: {
    'bold' : ['ctrl+b'],
    'italic' : ['ctrl+i'],
    'image' : ['ctrl+g'],
    'strikeThrough' : ['ctrl+d'],
    'underline' : ['ctrl+shift+l'],
    'link' : ['ctrl+l'],
    'unorderedList' : ['ctrl+u'],
    'orderedList' : ['ctrl+o'],
    'p' : ['ctrl+p'],
    'h1' : ['ctrl+1'],
    'h2' : ['ctrl+2'],
    'h3' : ['ctrl+3'],
    'h4' : ['ctrl+4'],
    'code' : ['ctrl+k'],
    'blockquote' : ['ctrl+q'],
    'undo' : ['ctrl+z'],
    'redo' : ['ctrl+y', 'ctrl+shift+z']
  },

  connectShortcuts: function() {
    var _this = this;
    $.each(this.shortcuts, function(method, key) {
      if (_this.formator[method]) {
        Mousetrap.bind(key, function(event) {
          event.preventDefault();
          if (!_this.hasRange()) {
            _this.restoreRange();
          }
          _this.formator[method]();
        });
      } else if (_this[method]) {
        Mousetrap.bind(key, function(event) {
          event.preventDefault();
          _this[method]();
        });
      }
    });
  },

  paste: function(event) {
    this.dirty = true;
  },

  input: function(event) {
    var _this = this;
    if (_this.dirty) {
      _this.sanitize.run();
      _this.dirty = false;
    }
  },

  selectContents: function(contents) {
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    var start = contents.first()[0];
    var end = contents.last()[0];
    range.setStart(start, 0);
    range.setEnd(end, end.childNodes.length || end.length); // text node don't have childNodes
    selection.removeAllRanges();
    selection.addRange(range);
  },

  keyup: function(event) {
    switch (event.keyCode) {
      case 8: // Backspace
      case 46: // Delete
        this.initParagraph();

        // bugfix https://github.com/writings-io/writings-io/issues/3#issuecomment-14832829
        if (!this.is_safari) {
          this.undoManager.save();
          this.editable.trigger('editor:change');
        }
        break;
    }
  },

  keydown: function(event) {
    switch (event.keyCode) {
      case 8: // Backspace
        this.backspcae(event);
        break;
      case 9: // Tab
        event.preventDefault();
        this.formator.exec('insertText', '  ');
        this.editable.trigger('editor:change');
        break;
      case 13: // Enter
        this.enter(event);
        break;
    }
  },

  backspcae: function(event) {
    // Stop Backspace when empty, avoid cursor flash
    if (this.editable.html() === '

') {
      event.preventDefault();
    }
  },

  enter: function(event) {
    // If in pre code, insert \n

    if (document.queryCommandValue('formatBlock') === 'pre') {
      event.preventDefault();
      var selection = window.getSelection();
      var range = selection.getRangeAt(0);
      var rangeAncestor = range.commonAncestorContainer;
      var $pre = $(rangeAncestor).closest('pre');

      range.deleteContents();
      var isLastLine = ($pre.find('code').contents().last()[0] === range.endContainer);
      var isEnd = (range.endContainer.length === range.endOffset);
      var node = document.createTextNode("\n");
      range.insertNode(node);
      // keep two \n at the end, fix webkit eat \n issues.
      if (isLastLine && isEnd) {
        $pre.find('code').append(document.createTextNode("\n"));
      }
      range.setStartAfter(node);
      range.setEndAfter(node);
      selection.removeAllRanges();
      selection.addRange(range);
      this.editable.trigger('editor:change');
    }
  },

  undo: function() {
    this.undoManager.undo();
  },

  redo: function() {
    this.undoManager.redo();
  },

  initParagraph: function() {
    // chrome is empty and firefox is

    if (this.editable.html() === '' || this.editable.html() === '
') {
      this.formator.p();
    }
  },

  selectEnd: function() {
    var selection = document.getSelection();
    selection.selectAllChildren(this.editable[0]);
    selection.collapseToEnd();
  },

  storeRange: function() {
    var selection = document.getSelection();
    var range = selection.getRangeAt(0);
    this.storedRange = {
      startContainer: range.startContainer,
      startOffset: range.startOffset,
      endContainer: range.endContainer,
      endOffset: range.endOffset
    };
  },

  restoreRange: function() {
    var selection = document.getSelection();
    var range = document.createRange();
    if (this.storedRange) {
      range.setStart(this.storedRange.startContainer, this.storedRange.startOffset);
      range.setEnd(this.storedRange.endContainer, this.storedRange.endOffset);
      selection.removeAllRanges();
      selection.addRange(range);
    } else {
      this.selectEnd();
    }
  },

  hasRange: function() {
    var selection = document.getSelection();

    return selection.rangeCount && $(selection.getRangeAt(0).commonAncestorContainer).closest(this.editable_selector).length;
  }
};
<commit_msg>fix trigger input.<commit_after>//= require_self
//= require_tree ./editor
Mousetrap.stopCallback = function(e, element, combo) {
  // stop for input, select, and textarea
  return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA';
};

var Editor = function(options) {
  this.editable_selector = options.editable;
  this.editable = $(options.editable);

  this.selectEnd();
  this.sanitize = new Editor.Sanitize(this.editable);
  this.formator = new Editor.Formator(this);
  this.formator.exec('defaultParagraphSeparator', 'p');

  this.undoManager = new Editor.UndoManager(this.editable);

  if (options.toolbar) {
    this.toolbar = new Editor.Toolbar(this, options.toolbar);
    this.toolbar.detectState();
  }

  this.connectShortcuts();

  this.initParagraph();

  var _this = this;
  this.editable.on('keyup mouseup', function() {
    _this.storeRange();
  });

  this.editable.on({
    keyup: function(event) {
      _this.keyup(event);
    },
    keydown: function(event) {
      _this.keydown(event);
    },
    input: function(event) {
      _this.input(event);
    },
    paste: function(event) {
      _this.paste(event);
    }
  });

  this.is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
  this.is_safari = navigator.userAgent.indexOf("Safari") > -1 && !this.is_chrome;

  // In mac, chrome in safari trigger input event when typing pinyin,
  // so use textInput event.
  if (this.is_chrome || this.is_safari) {
    this.editable.on('textInput', function() {
      setTimeout(function() {
        _this.undoManager.save();
        _this.editable.trigger('editor:change');
      }, 0); // webkit don't get right range offset, so setTimout to fix
    });
  } else {
    this.editable.on('input', function() {
      setTimeout(function() {
        _this.undoManager.save();
        _this.editable.trigger('editor:change');
      }, 0); // webkit don't get right range offset, so setTimout to fix
    });
  }
};

Editor.prototype = {
  shortcuts: {
    'bold' : ['ctrl+b'],
    'italic' : ['ctrl+i'],
    'image' : ['ctrl+g'],
    'strikeThrough' : ['ctrl+d'],
    'underline' : ['ctrl+shift+l'],
    'link' : ['ctrl+l'],
    'unorderedList' : ['ctrl+u'],
    'orderedList' : ['ctrl+o'],
    'p' : ['ctrl+p'],
    'h1' : ['ctrl+1'],
    'h2' : ['ctrl+2'],
    'h3' : ['ctrl+3'],
    'h4' : ['ctrl+4'],
    'code' : ['ctrl+k'],
    'blockquote' : ['ctrl+q'],
    'undo' : ['ctrl+z'],
    'redo' : ['ctrl+y', 'ctrl+shift+z']
  },

  connectShortcuts: function() {
    var _this = this;
    $.each(this.shortcuts, function(method, key) {
      if (_this.formator[method]) {
        Mousetrap.bind(key, function(event) {
          event.preventDefault();
          if (!_this.hasRange()) {
            _this.restoreRange();
          }
          _this.formator[method]();
        });
      } else if (_this[method]) {
        Mousetrap.bind(key, function(event) {
          event.preventDefault();
          _this[method]();
        });
      }
    });
  },

  paste: function(event) {
    this.dirty = true;
  },

  input: function(event) {
    var _this = this;
    if (_this.dirty) {
      _this.sanitize.run();
      _this.dirty = false;
    }
  },

  selectContents: function(contents) {
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    var start = contents.first()[0];
    var end = contents.last()[0];
    range.setStart(start, 0);
    range.setEnd(end, end.childNodes.length || end.length); // text node don't have childNodes
    selection.removeAllRanges();
    selection.addRange(range);
  },

  keyup: function(event) {
    switch (event.keyCode) {
      case 8: // Backspace
      case 46: // Delete
        this.initParagraph();

        // bugfix https://github.com/writings-io/writings-io/issues/3#issuecomment-14832829
        if (!this.is_safari) {
          this.undoManager.save();
          this.editable.trigger('editor:change');
        }
        break;
    }
  },

  triggerInput: function() {
    if (this.is_chrome || this.is_safari) {
      this.editable.trigger('textInput');
    } else {
      this.editable.trigger('input');
    }
  },

  keydown: function(event) {
    switch (event.keyCode) {
      case 8: // Backspace
        this.backspcae(event);
        break;
      case 9: // Tab
        event.preventDefault();
        this.formator.exec('insertText', '  ');
        this.triggerInput();
        break;
      case 13: // Enter
        this.enter(event);
        break;
    }
  },

  backspcae: function(event) {
    // Stop Backspace when empty, avoid cursor flash
    if (this.editable.html() === '

') {
      event.preventDefault();
    }
  },

  enter: function(event) {
    // If in pre code, insert \n

    if (document.queryCommandValue('formatBlock') === 'pre') {
      event.preventDefault();
      var selection = window.getSelection();
      var range = selection.getRangeAt(0);
      var rangeAncestor = range.commonAncestorContainer;
      var $pre = $(rangeAncestor).closest('pre');

      range.deleteContents();
      var isLastLine = ($pre.find('code').contents().last()[0] === range.endContainer);
      var isEnd = (range.endContainer.length === range.endOffset);
      var node = document.createTextNode("\n");
      range.insertNode(node);
      // keep two \n at the end, fix webkit eat \n issues.
      if (isLastLine && isEnd) {
        $pre.find('code').append(document.createTextNode("\n"));
      }
      range.setStartAfter(node);
      range.setEndAfter(node);
      selection.removeAllRanges();
      selection.addRange(range);
      this.triggerInput();
    }
  },

  undo: function() {
    this.undoManager.undo();
  },

  redo: function() {
    this.undoManager.redo();
  },

  initParagraph: function() {
    // chrome is empty and firefox is

    if (this.editable.html() === '' || this.editable.html() === '
') {
      this.formator.p();
    }
  },

  selectEnd: function() {
    var selection = document.getSelection();
    selection.selectAllChildren(this.editable[0]);
    selection.collapseToEnd();
  },

  storeRange: function() {
    var selection = document.getSelection();
    var range = selection.getRangeAt(0);
    this.storedRange = {
      startContainer: range.startContainer,
      startOffset: range.startOffset,
      endContainer: range.endContainer,
      endOffset: range.endOffset
    };
  },

  restoreRange: function() {
    var selection = document.getSelection();
    var range = document.createRange();
    if (this.storedRange) {
      range.setStart(this.storedRange.startContainer, this.storedRange.startOffset);
      range.setEnd(this.storedRange.endContainer, this.storedRange.endOffset);
      selection.removeAllRanges();
      selection.addRange(range);
    } else {
      this.selectEnd();
    }
  },

  hasRange: function() {
    var selection = document.getSelection();

    return selection.rangeCount && $(selection.getRangeAt(0).commonAncestorContainer).closest(this.editable_selector).length;
  }
};
<|endoftext|>


<commit_before>const process = require('process');
const _ = require('lodash');

let defaults = {
  databaseName:  'metadataTestMk2',
  ip:  '127.0.0.1',
  tables:  ['version', 'graph', 'layout'],
  port: '28015'
};

let envVars = _.pick( process.env, Object.keys( defaults ) );

let conf = Object.assign( {}, defaults, envVars );

Object.freeze( conf );

module.exports = conf;

module.exports = conf;<commit_msg>Changed database ip<commit_after>const process = require('process');
const _ = require('lodash');

let defaults = {
  databaseName:  'metadataTestMk2',
  ip:  '192.168.81.233',
  tables:  ['version', 'graph', 'layout'],
  port: '28015'
};

let envVars = _.pick( process.env, Object.keys( defaults ) );

let conf = Object.assign( {}, defaults, envVars );

Object.freeze( conf );

module.exports = conf;

module.exports = conf;<|endoftext|>


<commit_before>$(document).on('ready page:load', function (event) {
  $('#calendar').fullCalendar({
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'month,agendaWeek,agendaDay'
    },
    events: '/events/',
    timezone: 'local',
    aspectRatio: 2.5
  });

  $(".quick-datetime-select").quickDatetimeSelector();
});

$.fn.quickDatetimeSelector = function(options) {

  var settings = $.extend({
    dateButtonClass: 'quick-datetime-select-date-button',
    weekButtonClass: 'quick-datetime-select-week-button',
    dayButtonClass: 'quick-datetime-select-day-button',
    activeDayClass: 'btn-success',
    buttonFormatter: button,
    template: null,
    onClickDateButton: clickDateButton,
    onClickWeekButton: clickWeekButton,
    onClickDayButton: clickDayButton,
    onChangeDate: changeDate,
    onChangeDay: displayDay,
    changeDateTrigger: fillDateFromParent
  }, options);

  settings.template = settings.template || template();

  function button(className, name, value, active) {
    active = active === false ? false : true;
    return '<button type="button" ' + (!active ? 'disabled ' : '') + 'value="' + value + '" class="' + className + ' btn btn-sm btn-default">' + name + '</button> ';
  }

  function dateButton(name, value, active) {
    return settings.buttonFormatter(settings.dateButtonClass, name, value, active);
  }

  function weekButton(name, value, active) {
    return settings.buttonFormatter(settings.weekButtonClass, name, value, active);
  }

  function dayButton(name, value, active) {
    return settings.buttonFormatter(settings.dayButtonClass, name, value, active);
  }

  function template() {
    return [
      '
',
        '
',
          dateButton('Today', 0),
          dateButton('Tomorrow', 1),
        '
',
        '
',
          weekButton('This Week', 0),
          weekButton('Next Week', 1),
        '
',
        '
',
          dayButton('Sunday', 0, false),
          dayButton('Monday', 1, false),
          dayButton('Tuesday', 2, false),
          dayButton('Wednesday', 3, false),
          dayButton('Thursday', 4, false),
          dayButton('Friday', 5, false),
          dayButton('Saturday', 6, false),
        '
',
      '
',
    ].join("");
  }

  function clickDateButton() {
    var value = parseInt($(this).val());
    var $selector = $(this).prop('selector');

    if(!$selector) throw new Error('Selector Prop required');

    var date = new Date();
    var week = 0;
    date.setDate(date.getDate() + value);

    $selector.prop('date', date);
    $selector.prop('selectedDay', date.getDay());
    $selector.prop('week', week);
    $selector.prop('selectedWeek', week);
    $selector.trigger('change.date');
    $selector.trigger('change.day');
  }

  function clickWeekButton() {
    var value = parseInt($(this).val());
    var $selector = $(this).prop('selector');

    if(!$selector) throw new Error('Selector Prop required');

    $selector.prop('week', value);
    $selector.trigger('change.day');
  }

  function clickDayButton() {
    var day = parseInt($(this).val());
    var $selector = $(this).prop('selector');

    if(!$selector) throw new Error('Selector Prop required');

    var date = new Date();
    var week = parseInt($selector.prop('week'));

    var firstDayOfTheWeek = week * 7 + date.getDate() - date.getDay();
    date.setDate(firstDayOfTheWeek + day);

    $selector.prop('date', date);
    $selector.prop('selectedWeek', week);
    $selector.prop('selectedDay', day);
    $selector.trigger('change.date');
    $selector.trigger('change.day');
  }

  function displayDay() {
    var $selector = $(this);
    var $buttons = $selector.find('.' + settings.dayButtonClass);

    var week = $selector.prop('week');
    var date = $selector.prop('date');
    var currentDate = new Date();

    var selectedWeek = $selector.prop('selectedWeek');
    var selectedDay = $selector.prop('selectedDay');

    $buttons.prop('disabled', week === null);

    if(week === 0) {
      var today = currentDate.getDay();
      $buttons.each(function() {
        $(this).prop('disabled', parseInt($(this).val()) < today);
      });
    }

    $buttons.removeClass(settings.activeDayClass);

    if(week === selectedWeek) {
      $buttons.each(function() {
        if($(this).val() == selectedDay) {
          $(this).addClass(settings.activeDayClass);
          return false;
        }
      })
    }
  }

  function changeDate() {
    $(this).prop('start').trigger('change.date');
    $(this).prop('end').trigger('change.date');
  }

  function fillDateFromParent() {
    var $selector = $(this);
    var $selects = $selector.find('select');
    var $parent = $(this).prop('parent');
    var date = $parent.prop('date');

    var values = [
      date.getFullYear(),
      date.getMonth() + 1,
      date.getDate()
    ];

    $selects.each(function(i) {
      if(values[i]) $(this).val(values[i]);
    });
  }

  function getYMDDate(date) {
    return [
      date.getFullYear(),
      date.getMonth() + 1,
      date.getDate()
    ].join("/");
  }

  function init(ele) {
    ele.each(function() {
      var $target = $(this);
      var $start = $($target.data('startDatetime'));
      var $end = $($target.data('endDatetime'));

      $target.html(settings.template);
      $target.on('change.date', settings.onChangeDate);
      $target.on('change.day', settings.onChangeDay);
      $target.find('button').prop('selector', $target);

      $target.on('click', '.' + settings.dateButtonClass, settings.onClickDateButton);
      $target.on('click', '.' + settings.weekButtonClass, settings.onClickWeekButton);
      $target.on('click', '.' + settings.dayButtonClass, settings.onClickDayButton);

      $target.prop('start', $start).prop('end', $end);
      $start.prop('parent', $target).on('change.date', settings.changeDateTrigger);
      $end.prop('parent', $target).on('change.date', settings.changeDateTrigger);

      $target.prop('date', new Date());
      $target.prop('week', 0);
      $target.trigger('change.date');
      $target.trigger('change.day');
    });
  }

  init(this);
  return this;
};
<commit_msg>update trigger name of quick datetime selector<commit_after>$(document).on('ready page:load', function (event) {
  $('#calendar').fullCalendar({
    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'month,agendaWeek,agendaDay'
    },
    events: '/events/',
    timezone: 'local',
    aspectRatio: 2.5
  });

  $(".quick-datetime-select").quickDatetimeSelector();
});

$.fn.quickDatetimeSelector = function(options) {

  var settings = $.extend({
    dateButtonClass: 'quick-datetime-select-date-button',
    weekButtonClass: 'quick-datetime-select-week-button',
    dayButtonClass: 'quick-datetime-select-day-button',
    activeDayClass: 'btn-success',
    buttonFormatter: button,
    template: null,
    onClickDateButton: clickDateButton,
    onClickWeekButton: clickWeekButton,
    onClickDayButton: clickDayButton,
    onChangeDate: changeDate,
    onChangeDay: displayDay,
    changeDateTrigger: fillDateFromParent
  }, options);

  settings.template = settings.template || template();

  function button(className, name, value, active) {
    active = active === false ? false : true;
    return '<button type="button" ' + (!active ? 'disabled ' : '') + 'value="' + value + '" class="' + className + ' btn btn-sm btn-default">' + name + '</button> ';
  }

  function dateButton(name, value, active) {
    return settings.buttonFormatter(settings.dateButtonClass, name, value, active);
  }

  function weekButton(name, value, active) {
    return settings.buttonFormatter(settings.weekButtonClass, name, value, active);
  }

  function dayButton(name, value, active) {
    return settings.buttonFormatter(settings.dayButtonClass, name, value, active);
  }

  function template() {
    return [
      '
',
        '
',
          dateButton('Today', 0),
          dateButton('Tomorrow', 1),
        '
',
        '
',
          weekButton('This Week', 0),
          weekButton('Next Week', 1),
        '
',
        '
',
          dayButton('Sunday', 0, false),
          dayButton('Monday', 1, false),
          dayButton('Tuesday', 2, false),
          dayButton('Wednesday', 3, false),
          dayButton('Thursday', 4, false),
          dayButton('Friday', 5, false),
          dayButton('Saturday', 6, false),
        '
',
      '
',
    ].join("");
  }

  function clickDateButton() {
    var value = parseInt($(this).val());
    var $selector = $(this).prop('selector');

    if(!$selector) throw new Error('Selector Prop required');

    var date = new Date();
    var week = 0;
    date.setDate(date.getDate() + value);

    $selector.prop('date', date);
    $selector.prop('selectedDay', date.getDay());
    $selector.prop('week', week);
    $selector.prop('selectedWeek', week);
    $selector.trigger('quickdatetime:change:date');
    $selector.trigger('quickdatetime:change:day');
  }

  function clickWeekButton() {
    var value = parseInt($(this).val());
    var $selector = $(this).prop('selector');

    if(!$selector) throw new Error('Selector Prop required');

    $selector.prop('week', value);
    $selector.trigger('quickdatetime:change:day');
  }

  function clickDayButton() {
    var day = parseInt($(this).val());
    var $selector = $(this).prop('selector');

    if(!$selector) throw new Error('Selector Prop required');

    var date = new Date();
    var week = parseInt($selector.prop('week'));

    var firstDayOfTheWeek = week * 7 + date.getDate() - date.getDay();
    date.setDate(firstDayOfTheWeek + day);

    $selector.prop('date', date);
    $selector.prop('selectedWeek', week);
    $selector.prop('selectedDay', day);
    $selector.trigger('quickdatetime:change:date');
    $selector.trigger('quickdatetime:change:day');
  }

  function displayDay() {
    var $selector = $(this);
    var $buttons = $selector.find('.' + settings.dayButtonClass);

    var week = $selector.prop('week');
    var date = $selector.prop('date');
    var currentDate = new Date();

    var selectedWeek = $selector.prop('selectedWeek');
    var selectedDay = $selector.prop('selectedDay');

    $buttons.prop('disabled', week === null);

    if(week === 0) {
      var today = currentDate.getDay();
      $buttons.each(function() {
        $(this).prop('disabled', parseInt($(this).val()) < today);
      });
    }

    $buttons.removeClass(settings.activeDayClass);

    if(week === selectedWeek) {
      $buttons.each(function() {
        if($(this).val() == selectedDay) {
          $(this).addClass(settings.activeDayClass);
          return false;
        }
      })
    }
  }

  function changeDate() {
    $(this).prop('start').trigger('quickdatetime:change:date');
    $(this).prop('end').trigger('quickdatetime:change:date');
  }

  function fillDateFromParent() {
    var $selector = $(this);
    var $selects = $selector.find('select');
    var $parent = $(this).prop('parent');
    var date = $parent.prop('date');

    var values = [
      date.getFullYear(),
      date.getMonth() + 1,
      date.getDate()
    ];

    $selects.each(function(i) {
      if(values[i]) $(this).val(values[i]);
    });
  }

  function getYMDDate(date) {
    return [
      date.getFullYear(),
      date.getMonth() + 1,
      date.getDate()
    ].join("/");
  }

  function init(ele) {
    ele.each(function() {
      var $target = $(this);
      var $start = $($target.data('startDatetime'));
      var $end = $($target.data('endDatetime'));

      $target.html(settings.template);
      $target.on('quickdatetime:change:date', settings.onChangeDate);
      $target.on('quickdatetime:change:day', settings.onChangeDay);
      $target.find('button').prop('selector', $target);

      $target.on('click', '.' + settings.dateButtonClass, settings.onClickDateButton);
      $target.on('click', '.' + settings.weekButtonClass, settings.onClickWeekButton);
      $target.on('click', '.' + settings.dayButtonClass, settings.onClickDayButton);

      $target.prop('start', $start).prop('end', $end);
      $start.prop('parent', $target).on('quickdatetime:change:date', settings.changeDateTrigger);
      $end.prop('parent', $target).on('quickdatetime:change:date', settings.changeDateTrigger);

      $target.prop('date', new Date());
      $target.prop('week', 0);
      $target.trigger('quickdatetime:change:date');
      $target.trigger('quickdatetime:change:day');
    });
  }

  init(this);
  return this;
};
<|endoftext|>


<commit_before>// File:   StanbolService.js
// Author: Sebastian Germesin
// Author: Szaby Gruenwald
//
(function(){
VIE.prototype.StanbolService = function(options) {
    var defaults = {
        name : 'stanbol',
        url: 'http://dev.iks-project.eu:8080/',
        defaultProxyUrl : "../utils/proxy/proxy.php",
        namespaces : {
            semdeski : "http://www.semanticdesktop.org/ontologies/2007/01/19/nie#",
            semdeskf : "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#",
            skos: "http://www.w3.org/2004/02/skos/core#",
            foaf: "http://xmlns.com/foaf/0.1/",
            opengis: "http://www.opengis.net/gml/",
            dbpedia: "http://dbpedia.org/ontology/",
            owl : "http://www.w3.org/2002/07/owl#",
            geonames : "http://www.geonames.org/ontology#",
            enhancer : "http://fise.iks-project.eu/ontology/",
            entityhub: "http://www.iks-project.eu/ontology/rick/model/",
            entityhub2: "http://www.iks-project.eu/ontology/rick/query/",
            rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
            rdfs: "http://www.w3.org/2000/01/rdf-schema#",
            dc  : 'http://purl.org/dc/terms/',
            foaf: 'http://xmlns.com/foaf/0.1/',
            schema: 'http://schema.org/',
            geo: 'http://www.w3.org/2003/01/geo/wgs84_pos#'
        }
    };
    this.options = jQuery.extend(true, defaults, options ? options : {});

    this.vie = null; // will be set via VIE.use();
    this.name = this.options.name;
    this.connector = new StanbolConnector(this.options);

    jQuery.ajaxSetup({
        converters: {"text application/rdf+json": function(s){return JSON.parse(s);}}
    });

};

VIE.prototype.StanbolService.prototype = {
    init: function(){

        for (var key in this.options.namespaces) {
            try {
                var val = this.options.namespaces[key];
                this.vie.namespaces.add(key, val);
            } catch (e) {
                //this means that the namespace is already in the VIE.namespace
                //ignore for now!
            }
        }
        this.namespaces = new this.vie.Namespaces(this.vie.namespaces.base(), this.options.namespaces);

        this.rules = [
            //rule to add backwards-relations to the triples
            //this makes querying for entities a lot easier!
            {'left' : [
                '?subject a <http://fise.iks-project.eu/ontology/EntityAnnotation>',
                '?subject enhancer:entity-type ?type',
                '?subject enhancer:confidence ?confidence',
                '?subject enhancer:entity-reference ?entity',
                '?subject dc:relation ?relation',
                '?relation a <http://fise.iks-project.eu/ontology/TextAnnotation>',
                '?relation enhancer:selected-text ?selected-text',
                '?relation enhancer:selection-context ?selection-context',
                '?relation enhancer:start ?start',
                '?relation enhancer:end ?end'
            ],
             'right' : [
                 '?entity a ?type',
                 '?entity enhancer:hasTextAnnotation ?relation',
                 '?entity enhancer:hasEntityAnnotation ?subject'
             ]
             },
             //rule(s) to transform a Stanbol person into a VIE person
             {
                'left' : [
                    '?subject a dbpedia:Person',
                    '?subject rdfs:label ?label'
                 ],
                 'right': function(ns){
                     return function(){
                         return [
                             jQuery.rdf.triple(this.subject.toString(),
                                 'a',
                                 '<' + ns.base() + 'Person>', {
                                     namespaces: ns.toObj()
                                 }),
                             jQuery.rdf.triple(this.subject.toString(),
                                 '<' + ns.base() + 'name>',
                                 this.label, {
                                     namespaces: ns.toObj()
                                 })
                             ];
                     };
                 }(this.namespaces)
             },
             {
                 'left' : [
                     '?subject a dbpedia:Place',
                     '?subject rdfs:label ?label'
                  ],
                  'right': function(ns) {
                      return function() {
                          return [
                          jQuery.rdf.triple(this.subject.toString(),
                              'a',
                              '<' + ns.base() + 'Place>', {
                                  namespaces: ns.toObj()
                              }),
                          jQuery.rdf.triple(this.subject.toString(),
                                  '<' + ns.base() + 'name>',
                              this.label.toString(), {
                                  namespaces: ns.toObj()
                              })
                          ];
                      };
                  }(this.namespaces)
              },
        ];

        this.vie.types.addOrOverwrite('enhancer:EntityAnnotation', [
            //TODO: add attributes
        ]).inherit("Thing");
        this.vie.types.addOrOverwrite('enhancer:TextAnnotation', [
            //TODO: add attributes
        ]).inherit("Thing");
        this.vie.types.addOrOverwrite('enhancer:Enhancement', [
            //TODO: add attributes
        ]).inherit("Thing");
    },
    // VIE API analyze implementation
    analyze: function(analyzable) {
        var service = this;

        var correct = analyzable instanceof this.vie.Analyzable;
        if (!correct) {throw "Invalid Analyzable passed";}

        var element = analyzable.options.element ? analyzable.options.element : jQuery('body');

        var text = service._extractText(element);

        if (text.length > 0) {
            var service = this;
            //query enhancer with extracted text
            var success = function (results) {
                var entities = service._enhancer2Entities(service, results);
                analyzable.resolve(entities);
            };
            var error = function (e) {
                analyzable.reject(e);
            };

            this.connector.analyze(text, success, error);

        } else {
            console.warn("No text found in element.");
            analyzable.resolve([]);
        }

    },

    // VIE API load implementation
    // Runs a Stanbol entityhub find
    find: function(findable){
        var correct = findable instanceof this.vie.Findable;
        if (!correct) {throw "Invalid Findable passed";}
        var service = this;
        // The term to find, * as wildcard allowed
        var term = escape(findable.options.term);
        if(!term){
            console.warn("StanbolConnector: No term to look for!");
            findable.resolve([]);
        };
        var limit = (typeof findable.options.limit === "undefined") ? 20 : findable.options.limit;
        var offset = (typeof findable.options.offset === "undefined") ? 0 : findable.options.offset;
        var success = function (results) {
            // TODO: Return an array of vie entities
            var resultArray = _(results).map(
                function(v,k){
                    v.id=k;
                    return v;
                }
            );
            findable.resolve(resultArray);
        };
        var error = function (e) {
            findable.reject(e);
        };
        this.connector.find(term, limit, offset, success, error);
    },

    // VIE API load implementation
    // Runs a Stanbol entityhub find
    load: function(loadable){
        var correct = loadable instanceof this.vie.Loadable;
        if (!correct) {throw "Invalid Loadable passed";}
        var service = this;

        var entity = loadable.options.entity;
        if(!entity){
            console.warn("StanbolConnector: No entity to look for!");
            loadable.resolve([]);
        };
        var success = function (results) {
            var entities = service._enhancer2Entities(service, results);
            loadable.resolve(entities);
        };
        var error = function (e) {
            loadable.reject(e);
        };
        this.connector.load(entity, success, error);
    },

    _extractText: function (element) {
        if (element.get(0) &&
            element.get(0).tagName &&
            (element.get(0).tagName == 'TEXTAREA' ||
            element.get(0).tagName == 'INPUT' && element.attr('type', 'text'))) {
            return element.get(0).val();
        }
        else {
            return element
                .text()    //get the text of element
                .replace(/\s+/g, ' ') //collapse multiple whitespaces
                .replace(/\0\b\n\r\f\t/g, '').trim(); // remove non-letter symbols
        }
    },

    _enhancer2Entities: function (service, results) {
        //transform data from Stanbol into VIE.Entities

        if (typeof jQuery.rdf !== 'function') {
            return this._enhancer2EntitiesNoRdfQuery(service, results);
        }
        var rdf = jQuery.rdf().load(results, {});

        //execute rules here!
        if (service.rules) {
            var rules = jQuery.rdf.ruleset();
            for (var prefix in service.namespaces.toObj()) {
                if (prefix !== "") {
                	rules.prefix(prefix, service.namespaces.get(prefix));
                }
            }
            for (var i = 0; i < service.rules.length; i++) {
                rules.add(service.rules[i]['left'], service.rules[i]['right']);
            }
            rdf = rdf.reason(rules, 10); // execute the rules only 10 times to avoid looping
        }
        var entities = {};
        rdf.where('?subject ?property ?object').each(function() {
            var subject = this.subject.toString();
            if (!entities[subject]) {
                entities[subject] = {
                    '@subject': subject,
                    '@context': service.namespaces.toObj(),
                    '@type': []
                };
            }
            var propertyUri = this.property.toString();
            var propertyCurie;

            propertyUri = propertyUri.substring(1, propertyUri.length - 1);
            try {
                property = jQuery.createCurie(propertyUri, {namespaces: service.namespaces.toObj()});
            } catch (e) {
                property = propertyUri;
                console.warn(propertyUri + " doesn't have a namespace definition in '", service.namespaces.toObj());
            }
            entities[subject][property] = entities[subject][property] || [];

            function getValue(rdfQueryLiteral){
                if(typeof rdfQueryLiteral.value === "string"){
                    if (rdfQueryLiteral.lang)
                        return rdfQueryLiteral.toString();
                    else
                        return rdfQueryLiteral.value;
                    return rdfQueryLiteral.value.toString();
                } else if (rdfQueryLiteral.type === "uri"){
                    return rdfQueryLiteral.toString();
                } else {
                    return rdfQueryLiteral.value;
                }
            }
            entities[subject][property].push(getValue(this.object));
        });

        _(entities).each(function(ent){
            ent["@type"] = ent["@type"].concat(ent["rdf:type"]);
            delete ent["rdf:type"];
            _(ent).each(function(value, property){
                if(value.length === 1){
                    ent[property] = value[0];
                }
            });
        });

        var vieEntities = [];
        jQuery.each(entities, function() {
            var entityInstance = new service.vie.Entity(this);
            entityInstance = service.vie.entities.addOrUpdate(entityInstance);
            vieEntities.push(entityInstance);
        });
        return vieEntities;
    },

    _enhancer2EntitiesNoRdfQuery: function (service, results) {
        jsonLD = [];
        _.forEach(results.results, function(value, key) {
            var entity = {};
            entity['@subject'] = '<' + key + '>';
            _.forEach(value, function(triples, predicate) {
                predicate = '<' + predicate + '>';
                _.forEach(triples, function(triple) {
                    if (triple.type === 'uri') {
                        triple.value = '<' + triple.value + '>';
                    }

                    if (entity[predicate] && !_.isArray(entity[predicate])) {
                        entity[predicate] = [entity[predicate]];
                    }

                    if (_.isArray(entity[predicate])) {
                        entity[predicate].push(triple.value);
                        return;
                    }
                    entity[predicate] = triple.value;
                });
            });
            jsonLD.push(entity);
        });
        return jsonLD;
    }
};

var StanbolConnector = function(options){
    this.options = options;
    this.baseUrl = options.url.replace(/\/$/, '');
    this.enhancerUrlPrefix = "/engines";
    this.entityhubUrlPrefix = "/entityhub";
    //TODO: this.ontonetUrlPrefix = "/ontonet";
    //TODO: this.rulesUrlPrefix = "/rules";
    //TODO: this.factstoreUrlPrefix = "/factstore";
};
StanbolConnector.prototype = {

    analyze: function(text, success, error, options) {
        if (!options) { options = {}; }
        var enhancerUrl = this.baseUrl + this.enhancerUrlPrefix;
        var proxyUrl = this._proxyUrl();
        var format = options.format || "application/rdf+json";

        if (typeof exports !== "undefined" && typeof process !== "undefined") {
            // We're on Node.js, don't use jQuery.ajax
            return this.analyzeNode(enhancerUrl, text, success, error, options, format);
        }

        jQuery.ajax({
            success: function(response){
                success(response);
            },
            error: error,
            type: "POST",
            url: proxyUrl || enhancerUrl,
            data: (proxyUrl) ? {
                    proxy_url: enhancerUrl,
                    content: text,
                    verb: "POST",
                    format: format
                } : text,
            dataType: format,
            contentType: proxyUrl ? undefined : "text/plain",
            accepts: {"application/rdf+json": "application/rdf+json"}

        });
    },

    analyzeNode: function(url, text, success, error, options, format) {
        var request = require('request');
        var r = request({
            method: "POST",
            uri: url,
            body: text,
            headers: {
                Accept: format
            }
        }, function(error, response, body) {
            success({results: JSON.parse(body)});
        });
        r.end();
    },

    load: function (uri, success, error, options) {
        if (!options) { options = {}; }
        uri = uri.replace(/^</, '').replace(/>$/, '');
        var url = this.baseUrl + this.entityhubUrlPrefix + "/sites/entity?id=" + uri;
        var proxyUrl = this._proxyUrl();
        var format = options.format || "application/rdf+json";

        jQuery.ajax({
            success: function(response){
                success(response);
            },
            error: error,
            type: (proxyUrl) ? "POST" : "GET",
            url: proxyUrl || url,
            data: (proxyUrl) ? {
                    proxy_url: url,
                    content: "",
                    verb: "GET",
                    format: format
                } : null,
            dataType: format,
            contentType: proxyUrl ? undefined : "text/plain",
            accepts: {"application/rdf+json": "application/rdf+json"}
        });
    },

    find: function (term, limit, offset, success, error, options) {
        // curl -X POST -d "name=Bishofsh&limit=10&offset=0" http://localhost:8080/entityhub/sites/find
        if (!options) { options = {}; }
        if (offset == null) {
            offset = 0;
        }
        if (limit == null) {
            limit = 10;
        }

        var url = this.baseUrl + this.entityhubUrlPrefix + "/sites/find";
        var proxyUrl = this._proxyUrl();
        var format = options.format || "application/rdf+json";

        jQuery.ajax({
            success: function(response){
                success(response);
            },
            error: error,
            type: "POST",
            url: proxyUrl || url,
            data: (proxyUrl) ? {
                    proxy_url: url,
                    content: {
                        name : term,
                        limit : limit,
                        offset: offset
                    },
                    verb: "POST",
                    format: format,
                    type: "text/plain"
                } : "name=" + term + "&limit=" + limit + "&offset=" + offset,
            dataType: format,
            accepts: {"application/rdf+json": "application/rdf+json"}
        });
    },

    _proxyUrl: function(){
        this.proxyUrl = "";
        if(this.baseUrl.indexOf(":") !== -1 && !this.options.proxyDisabled){
            return this.options.proxyUrl || this.options.defaultProxyUrl;
        } else {
            return '';
        }
    }
};
})();

<commit_msg>stanbolService: escape uri in the load method<commit_after>// File:   StanbolService.js
// Author: Sebastian Germesin
// Author: Szaby Gruenwald
//
(function(){
VIE.prototype.StanbolService = function(options) {
    var defaults = {
        name : 'stanbol',
        url: 'http://dev.iks-project.eu:8080/',
        defaultProxyUrl : "../utils/proxy/proxy.php",
        namespaces : {
            semdeski : "http://www.semanticdesktop.org/ontologies/2007/01/19/nie#",
            semdeskf : "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#",
            skos: "http://www.w3.org/2004/02/skos/core#",
            foaf: "http://xmlns.com/foaf/0.1/",
            opengis: "http://www.opengis.net/gml/",
            dbpedia: "http://dbpedia.org/ontology/",
            owl : "http://www.w3.org/2002/07/owl#",
            geonames : "http://www.geonames.org/ontology#",
            enhancer : "http://fise.iks-project.eu/ontology/",
            entityhub: "http://www.iks-project.eu/ontology/rick/model/",
            entityhub2: "http://www.iks-project.eu/ontology/rick/query/",
            rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
            rdfs: "http://www.w3.org/2000/01/rdf-schema#",
            dc  : 'http://purl.org/dc/terms/',
            foaf: 'http://xmlns.com/foaf/0.1/',
            schema: 'http://schema.org/',
            geo: 'http://www.w3.org/2003/01/geo/wgs84_pos#'
        }
    };
    this.options = jQuery.extend(true, defaults, options ? options : {});

    this.vie = null; // will be set via VIE.use();
    this.name = this.options.name;
    this.connector = new StanbolConnector(this.options);

    jQuery.ajaxSetup({
        converters: {"text application/rdf+json": function(s){return JSON.parse(s);}}
    });

};

VIE.prototype.StanbolService.prototype = {
    init: function(){

        for (var key in this.options.namespaces) {
            try {
                var val = this.options.namespaces[key];
                this.vie.namespaces.add(key, val);
            } catch (e) {
                //this means that the namespace is already in the VIE.namespace
                //ignore for now!
            }
        }
        this.namespaces = new this.vie.Namespaces(this.vie.namespaces.base(), this.options.namespaces);

        this.rules = [
            //rule to add backwards-relations to the triples
            //this makes querying for entities a lot easier!
            {'left' : [
                '?subject a <http://fise.iks-project.eu/ontology/EntityAnnotation>',
                '?subject enhancer:entity-type ?type',
                '?subject enhancer:confidence ?confidence',
                '?subject enhancer:entity-reference ?entity',
                '?subject dc:relation ?relation',
                '?relation a <http://fise.iks-project.eu/ontology/TextAnnotation>',
                '?relation enhancer:selected-text ?selected-text',
                '?relation enhancer:selection-context ?selection-context',
                '?relation enhancer:start ?start',
                '?relation enhancer:end ?end'
            ],
             'right' : [
                 '?entity a ?type',
                 '?entity enhancer:hasTextAnnotation ?relation',
                 '?entity enhancer:hasEntityAnnotation ?subject'
             ]
             },
             //rule(s) to transform a Stanbol person into a VIE person
             {
                'left' : [
                    '?subject a dbpedia:Person',
                    '?subject rdfs:label ?label'
                 ],
                 'right': function(ns){
                     return function(){
                         return [
                             jQuery.rdf.triple(this.subject.toString(),
                                 'a',
                                 '<' + ns.base() + 'Person>', {
                                     namespaces: ns.toObj()
                                 }),
                             jQuery.rdf.triple(this.subject.toString(),
                                 '<' + ns.base() + 'name>',
                                 this.label, {
                                     namespaces: ns.toObj()
                                 })
                             ];
                     };
                 }(this.namespaces)
             },
             {
                 'left' : [
                     '?subject a dbpedia:Place',
                     '?subject rdfs:label ?label'
                  ],
                  'right': function(ns) {
                      return function() {
                          return [
                          jQuery.rdf.triple(this.subject.toString(),
                              'a',
                              '<' + ns.base() + 'Place>', {
                                  namespaces: ns.toObj()
                              }),
                          jQuery.rdf.triple(this.subject.toString(),
                                  '<' + ns.base() + 'name>',
                              this.label.toString(), {
                                  namespaces: ns.toObj()
                              })
                          ];
                      };
                  }(this.namespaces)
              },
        ];

        this.vie.types.addOrOverwrite('enhancer:EntityAnnotation', [
            //TODO: add attributes
        ]).inherit("Thing");
        this.vie.types.addOrOverwrite('enhancer:TextAnnotation', [
            //TODO: add attributes
        ]).inherit("Thing");
        this.vie.types.addOrOverwrite('enhancer:Enhancement', [
            //TODO: add attributes
        ]).inherit("Thing");
    },
    // VIE API analyze implementation
    analyze: function(analyzable) {
        var service = this;

        var correct = analyzable instanceof this.vie.Analyzable;
        if (!correct) {throw "Invalid Analyzable passed";}

        var element = analyzable.options.element ? analyzable.options.element : jQuery('body');

        var text = service._extractText(element);

        if (text.length > 0) {
            var service = this;
            //query enhancer with extracted text
            var success = function (results) {
                var entities = service._enhancer2Entities(service, results);
                analyzable.resolve(entities);
            };
            var error = function (e) {
                analyzable.reject(e);
            };

            this.connector.analyze(text, success, error);

        } else {
            console.warn("No text found in element.");
            analyzable.resolve([]);
        }

    },

    // VIE API load implementation
    // Runs a Stanbol entityhub find
    find: function(findable){
        var correct = findable instanceof this.vie.Findable;
        if (!correct) {throw "Invalid Findable passed";}
        var service = this;
        // The term to find, * as wildcard allowed
        var term = escape(findable.options.term);
        if(!term){
            console.warn("StanbolConnector: No term to look for!");
            findable.resolve([]);
        };
        var limit = (typeof findable.options.limit === "undefined") ? 20 : findable.options.limit;
        var offset = (typeof findable.options.offset === "undefined") ? 0 : findable.options.offset;
        var success = function (results) {
            // TODO: Return an array of vie entities
            var resultArray = _(results).map(
                function(v,k){
                    v.id=k;
                    return v;
                }
            );
            findable.resolve(resultArray);
        };
        var error = function (e) {
            findable.reject(e);
        };
        this.connector.find(term, limit, offset, success, error);
    },

    // VIE API load implementation
    // Runs a Stanbol entityhub find
    load: function(loadable){
        var correct = loadable instanceof this.vie.Loadable;
        if (!correct) {throw "Invalid Loadable passed";}
        var service = this;

        var entity = loadable.options.entity;
        if(!entity){
            console.warn("StanbolConnector: No entity to look for!");
            loadable.resolve([]);
        };
        var success = function (results) {
            var entities = service._enhancer2Entities(service, results);
            loadable.resolve(entities);
        };
        var error = function (e) {
            loadable.reject(e);
        };
        this.connector.load(entity, success, error);
    },

    _extractText: function (element) {
        if (element.get(0) &&
            element.get(0).tagName &&
            (element.get(0).tagName == 'TEXTAREA' ||
            element.get(0).tagName == 'INPUT' && element.attr('type', 'text'))) {
            return element.get(0).val();
        }
        else {
            return element
                .text()    //get the text of element
                .replace(/\s+/g, ' ') //collapse multiple whitespaces
                .replace(/\0\b\n\r\f\t/g, '').trim(); // remove non-letter symbols
        }
    },

    _enhancer2Entities: function (service, results) {
        //transform data from Stanbol into VIE.Entities

        if (typeof jQuery.rdf !== 'function') {
            return this._enhancer2EntitiesNoRdfQuery(service, results);
        }
        var rdf = jQuery.rdf().load(results, {});

        //execute rules here!
        if (service.rules) {
            var rules = jQuery.rdf.ruleset();
            for (var prefix in service.namespaces.toObj()) {
                if (prefix !== "") {
                	rules.prefix(prefix, service.namespaces.get(prefix));
                }
            }
            for (var i = 0; i < service.rules.length; i++) {
                rules.add(service.rules[i]['left'], service.rules[i]['right']);
            }
            rdf = rdf.reason(rules, 10); // execute the rules only 10 times to avoid looping
        }
        var entities = {};
        rdf.where('?subject ?property ?object').each(function() {
            var subject = this.subject.toString();
            if (!entities[subject]) {
                entities[subject] = {
                    '@subject': subject,
                    '@context': service.namespaces.toObj(),
                    '@type': []
                };
            }
            var propertyUri = this.property.toString();
            var propertyCurie;

            propertyUri = propertyUri.substring(1, propertyUri.length - 1);
            try {
                property = jQuery.createCurie(propertyUri, {namespaces: service.namespaces.toObj()});
            } catch (e) {
                property = propertyUri;
                console.warn(propertyUri + " doesn't have a namespace definition in '", service.namespaces.toObj());
            }
            entities[subject][property] = entities[subject][property] || [];

            function getValue(rdfQueryLiteral){
                if(typeof rdfQueryLiteral.value === "string"){
                    if (rdfQueryLiteral.lang)
                        return rdfQueryLiteral.toString();
                    else
                        return rdfQueryLiteral.value;
                    return rdfQueryLiteral.value.toString();
                } else if (rdfQueryLiteral.type === "uri"){
                    return rdfQueryLiteral.toString();
                } else {
                    return rdfQueryLiteral.value;
                }
            }
            entities[subject][property].push(getValue(this.object));
        });

        _(entities).each(function(ent){
            ent["@type"] = ent["@type"].concat(ent["rdf:type"]);
            delete ent["rdf:type"];
            _(ent).each(function(value, property){
                if(value.length === 1){
                    ent[property] = value[0];
                }
            });
        });

        var vieEntities = [];
        jQuery.each(entities, function() {
            var entityInstance = new service.vie.Entity(this);
            entityInstance = service.vie.entities.addOrUpdate(entityInstance);
            vieEntities.push(entityInstance);
        });
        return vieEntities;
    },

    _enhancer2EntitiesNoRdfQuery: function (service, results) {
        jsonLD = [];
        _.forEach(results.results, function(value, key) {
            var entity = {};
            entity['@subject'] = '<' + key + '>';
            _.forEach(value, function(triples, predicate) {
                predicate = '<' + predicate + '>';
                _.forEach(triples, function(triple) {
                    if (triple.type === 'uri') {
                        triple.value = '<' + triple.value + '>';
                    }

                    if (entity[predicate] && !_.isArray(entity[predicate])) {
                        entity[predicate] = [entity[predicate]];
                    }

                    if (_.isArray(entity[predicate])) {
                        entity[predicate].push(triple.value);
                        return;
                    }
                    entity[predicate] = triple.value;
                });
            });
            jsonLD.push(entity);
        });
        return jsonLD;
    }
};

var StanbolConnector = function(options){
    this.options = options;
    this.baseUrl = options.url.replace(/\/$/, '');
    this.enhancerUrlPrefix = "/engines";
    this.entityhubUrlPrefix = "/entityhub";
    //TODO: this.ontonetUrlPrefix = "/ontonet";
    //TODO: this.rulesUrlPrefix = "/rules";
    //TODO: this.factstoreUrlPrefix = "/factstore";
};
StanbolConnector.prototype = {

    analyze: function(text, success, error, options) {
        if (!options) { options = {}; }
        var enhancerUrl = this.baseUrl + this.enhancerUrlPrefix;
        var proxyUrl = this._proxyUrl();
        var format = options.format || "application/rdf+json";

        if (typeof exports !== "undefined" && typeof process !== "undefined") {
            // We're on Node.js, don't use jQuery.ajax
            return this.analyzeNode(enhancerUrl, text, success, error, options, format);
        }

        jQuery.ajax({
            success: function(response){
                success(response);
            },
            error: error,
            type: "POST",
            url: proxyUrl || enhancerUrl,
            data: (proxyUrl) ? {
                    proxy_url: enhancerUrl,
                    content: text,
                    verb: "POST",
                    format: format
                } : text,
            dataType: format,
            contentType: proxyUrl ? undefined : "text/plain",
            accepts: {"application/rdf+json": "application/rdf+json"}

        });
    },

    analyzeNode: function(url, text, success, error, options, format) {
        var request = require('request');
        var r = request({
            method: "POST",
            uri: url,
            body: text,
            headers: {
                Accept: format
            }
        }, function(error, response, body) {
            success({results: JSON.parse(body)});
        });
        r.end();
    },

    load: function (uri, success, error, options) {
        if (!options) { options = {}; }
        uri = uri.replace(/^</, '').replace(/>$/, '');
        var url = this.baseUrl + this.entityhubUrlPrefix + "/sites/entity?id=" + escape(uri);
        var proxyUrl = this._proxyUrl();
        var format = options.format || "application/rdf+json";

        jQuery.ajax({
            success: function(response){
                success(response);
            },
            error: error,
            type: (proxyUrl) ? "POST" : "GET",
            url: proxyUrl || url,
            data: (proxyUrl) ? {
                    proxy_url: url,
                    content: "",
                    verb: "GET",
                    format: format
                } : null,
            dataType: format,
            contentType: proxyUrl ? undefined : "text/plain",
            accepts: {"application/rdf+json": "application/rdf+json"}
        });
    },

    find: function (term, limit, offset, success, error, options) {
        // curl -X POST -d "name=Bishofsh&limit=10&offset=0" http://localhost:8080/entityhub/sites/find
        if (!options) { options = {}; }
        if (offset == null) {
            offset = 0;
        }
        if (limit == null) {
            limit = 10;
        }

        var url = this.baseUrl + this.entityhubUrlPrefix + "/sites/find";
        var proxyUrl = this._proxyUrl();
        var format = options.format || "application/rdf+json";

        jQuery.ajax({
            success: function(response){
                success(response);
            },
            error: error,
            type: "POST",
            url: proxyUrl || url,
            data: (proxyUrl) ? {
                    proxy_url: url,
                    content: {
                        name : term,
                        limit : limit,
                        offset: offset
                    },
                    verb: "POST",
                    format: format,
                    type: "text/plain"
                } : "name=" + term + "&limit=" + limit + "&offset=" + offset,
            dataType: format,
            accepts: {"application/rdf+json": "application/rdf+json"}
        });
    },

    _proxyUrl: function(){
        this.proxyUrl = "";
        if(this.baseUrl.indexOf(":") !== -1 && !this.options.proxyDisabled){
            return this.options.proxyUrl || this.options.defaultProxyUrl;
        } else {
            return '';
        }
    }
};
})();

<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');

var ObjectId = require('mongoose').Schema.Types.ObjectId;

function UiFormOptions(opts) {
  var options = _.cloneDeep(opts);
  // todo: add support of html 5 input types
  //email//tel//number//search//range//url//color//date//datetime//time//month//week
  // todo: check enum
  // todo: check email
  if (options.type === String){
    // todo: use options.uiForm.type
    // todo: check default type for String
    options.type = 'text' || 'textarea';
  }

  if (options.type === Number){
    // todo: use options.uiForm.type
    // todo: check default type for Number
    options.type = 'number';
  }

  if (options.type === Boolean){
    // todo: use options.uiForm.type
    // todo: check default type for Boolean
    options.type = 'checkbox';
  }

  if (options.type === Date){
    // todo: use options.uiForm.type
    // todo: check default type for Date
    options.type = 'date';
  }

  // this is direct reference type
  if (options.type === ObjectId && options.ref){
    // todo: use options.uiForm.type
    // todo: check default type for ObjectId||ref field
    options.type = 'select' || 'typeahead';
  }

  // _id - field
  if (options.type === ObjectId && !options.ref){
    options.type = 'text';
    options.editable = false;
    options.visible = false;
  }

  // array of refs
  if (Array.isArray(options.type) && options.type[0] && !!options.type[0].ref){
    options.type = 'arrayRef';
  }

  // array
  if (Array.isArray(options.type)){
    options.type = 'array';
    options.hideLabels = true;
  }

  if (options.ref && !options.uiForm){
    console.warn('add uiForm to path: %s', options.ref);
  }

  if (this.auto === true){
    this.visible = this.visible || false;
    delete this.auto;
  }

  options.visible = (options.visible === false) ? false : true;
  _.merge(this, options, options.uiForm);
}

function MongooseUtils() {
}

function toUiGridColumnDef(paths, parent) {
  if (parent && !Array.isArray(parent)) {
    parent = [parent];
  }

  var mix = _.map(paths, function (uiFormOptions, path) {
    if (uiFormOptions instanceof UiFormOptions) {
//      if (uiFormOptions.ref){
//        uiFormOptions.field = [path, uiFormOptions.field].join('.')
//        return uiFormOptions;
//      }

      if (parent && parent.length) {
        return _.merge(uiFormOptions, {field: [parent.join('.'), path].join('.')});
      }

      return _.merge(uiFormOptions, {field: path});
    }

    return toUiGridColumnDef(uiFormOptions, path);
  });

  if (parent) {
    return mix;
  }

  return _.flatten(mix);
}

/**
 * Returns an array with ui grid column options
 * @param schema - mongoose schema for collection
 * @param options - call options
 * @returns {*}
 */
MongooseUtils.prototype.getPaths = function getPaths(schema, options) {
  var self = this;
  var paths = _.reduce(schema.paths, function (result, pathSchema, path) {

    //// Nested schema OR Array can no be a column
    //if ((pathSchema.schema && self.include(pathSchema.schema)) ||
    //  ( Array.isArray(pathSchema.options.type) &&
    //  (!!pathSchema.options.type[0] && self.include({options: pathSchema.options.type[0]})))) {
    //  var msg = 'Nested schema or Array can not be a column in ui-grid! Path: ' + path;
    //  throw new Error(msg);
    //}

    var valIncl = self.include(pathSchema);

    // Array
    if (Array.isArray(pathSchema.options.type)){
      result[path] = valIncl;
      var array = null;

      // ignore mixed array {type: []} for now: !pathSchema.options.type[0]
      if (!array && !pathSchema.options.type[0]){
        array = [];
      }

      // Array of ref
      if (!array && pathSchema.options.type[0].ref){
        array = [new UiFormOptions(pathSchema.options.type[0])];
      }

      result[path].array = array || self.getPaths(pathSchema.options.type[0]);
    }

    if (!result[path] && valIncl) {
      result[path] = valIncl;
    }

    return result;
  }, {});

  return toUiGridColumnDef(paths);
};

/**
 * Returns true for private fields
 * @param pathSchema - mongoose schema for path
 * @param path - path name
 * @param options - call options
 * @returns {Object}
 */
MongooseUtils.prototype.include = function include(pathSchema) {
  return new UiFormOptions(pathSchema.options);
  //return !!pathSchema.options.uiForm ? new UiFormOptions(pathSchema.options.uiGrid) : null;
};

module.exports = new MongooseUtils();<commit_msg>referenced types<commit_after>'use strict';
var _ = require('lodash');

var ObjectId = require('mongoose').Schema.Types.ObjectId;

function UiFormOptions(opts) {
  var options = _.cloneDeep(opts);
  Object.defineProperty(options, '_type', { value:options.type});
  // todo: add support of html 5 input types
  //email//tel//number//search//range//url//color//date//datetime//time//month//week
  // todo: check enum
  // todo: check email
  if (options.type === String){
    // todo: use options.uiForm.type
    // todo: check default type for String
    options.type = 'text' || 'textarea';
  }

  if (options.type === Number){
    // todo: use options.uiForm.type
    // todo: check default type for Number
    options.type = 'number';
  }

  if (options.type === Boolean){
    // todo: use options.uiForm.type
    // todo: check default type for Boolean
    options.type = 'checkbox';
  }

  if (options.type === Date){
    // todo: use options.uiForm.type
    // todo: check default type for Date
    options.type = 'date';
  }

  // _id - field
  if (options.type === ObjectId && !options.ref){
    options.type = 'text';
    options.editable = false;
    options.visible = false;
  }

  // this is direct reference type
  if (options.type === ObjectId && options.ref){
    // todo: use options.uiForm.type
    // todo: check default type for ObjectId||ref field
    options.type = 'select' || 'typeahead';
  }

  // array of refs
  if (Array.isArray(options.type) && options.type[0] && !!options.type[0].ref){
    options.ref = options.type[0].ref;
    options.type = 'arrayRef';
  }

  // array
  if (Array.isArray(options.type)){
    options.type = 'array';
    options.hideLabels = true;
  }

  if (options.ref && !options.uiForm){
    console.warn('add uiForm to path: %s', options.ref);
  }

  if (this.auto === true){
    this.visible = this.visible || false;
    delete this.auto;
  }

  options.visible = (options.visible === false) ? false : true;
  _.merge(this, options, options.uiForm);
}

function MongooseUtils() {
}

function toUiGridColumnDef(paths, parent) {
  if (parent && !Array.isArray(parent)) {
    parent = [parent];
  }

  var mix = _.map(paths, function (uiFormOptions, path) {
    if (uiFormOptions instanceof UiFormOptions) {
//      if (uiFormOptions.ref){
//        uiFormOptions.field = [path, uiFormOptions.field].join('.')
//        return uiFormOptions;
//      }

      if (parent && parent.length) {
        return _.merge(uiFormOptions, {field: [parent.join('.'), path].join('.')});
      }

      return _.merge(uiFormOptions, {field: path});
    }

    return toUiGridColumnDef(uiFormOptions, path);
  });

  if (parent) {
    return mix;
  }

  return _.flatten(mix);
}

/**
 * Returns an array with ui grid column options
 * @param schema - mongoose schema for collection
 * @param options - call options
 * @returns {*}
 */
MongooseUtils.prototype.getPaths = function getPaths(schema, options) {
  var self = this;
  var paths = _.reduce(schema.paths, function (result, pathSchema, path) {

    //// Nested schema OR Array can no be a column
    //if ((pathSchema.schema && self.include(pathSchema.schema)) ||
    //  ( Array.isArray(pathSchema.options.type) &&
    //  (!!pathSchema.options.type[0] && self.include({options: pathSchema.options.type[0]})))) {
    //  var msg = 'Nested schema or Array can not be a column in ui-grid! Path: ' + path;
    //  throw new Error(msg);
    //}

    var valIncl = self.include(pathSchema);

    // Array
    if (Array.isArray(pathSchema.options.type)){
      result[path] = valIncl;
      var array = null;

      // ignore mixed array {type: []} for now: !pathSchema.options.type[0]
      if (!array && !pathSchema.options.type[0]){
        array = [];
      }

      // Array of ref
      if (!array && pathSchema.options.type[0].ref){
        array = [new UiFormOptions(pathSchema.options.type[0])];
      }

      result[path].array = array || self.getPaths(pathSchema.options.type[0]);
    }

    if (!result[path] && valIncl) {
      result[path] = valIncl;
    }

    return result;
  }, {});

  return toUiGridColumnDef(paths);
};

/**
 * Returns true for private fields
 * @param pathSchema - mongoose schema for path
 * @param path - path name
 * @param options - call options
 * @returns {Object}
 */
MongooseUtils.prototype.include = function include(pathSchema) {
  return new UiFormOptions(pathSchema.options);
  //return !!pathSchema.options.uiForm ? new UiFormOptions(pathSchema.options.uiGrid) : null;
};

module.exports = new MongooseUtils();<|endoftext|>