<commit_before>//     keymaster.js
//     (c) 2011 Thomas Fuchs
//     keymaster.js may be freely distributed under the MIT license.

;(function(global){
  var k,
    _handlers = {},
    _mods = { 16: false, 18: false, 17: false, 91: false },
    _scope = 'all',
    // modifier keys
    _MODIFIERS = {
      '⇧': 16, shift: 16,
      option: 18, '⌥': 18, alt: 18,
      ctrl: 17, control: 17,
      command: 91, '⌘': 91
    },
    // special keys
    _MAP = {
      backspace: 8, tab: 9, clear: 12,
      enter: 13, 'return': 13,
      esc: 27, escape: 27, space: 32,
      left: 37, up: 38,
      right: 39, down: 40,
      del: 46, 'delete': 46,
      home: 36, end: 35,
      pageup: 33, pagedown: 34,
      ',': 188, '.': 190, '/': 191,
      '`': 192, '-': 189, '=': 187,
      ';': 186, '\'': 222,
      '[': 219, ']': 221, '\\': 220
    };

  for(k=1;k<20;k++) _MODIFIERS['f'+k] = 111+k;

  // IE doesn't support Array#indexOf, so have a simple replacement
  function index(array, item){
    var i = array.length;
    while(i--) if(array[i]===item) return i;
    return -1;
  }

  // handle keydown event
  function dispatch(event){
    var key, tagName, handler, k, i, modifiersMatch;
    tagName = (event.target || event.srcElement).tagName;
    key = event.keyCode;

    // if a modifier key, set the key.<modifierkeyname> property to true and return
    if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
    if(key in _mods) {
      _mods[key] = true;
      // 'assignKey' from inside this closure is exported to window.key
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
      return;
    }

    // ignore keypressed in any elements that support keyboard data input
    if (tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA') return;

    // abort if no potentially matching shortcuts found
    if (!(key in _handlers)) return;

    // for each potential shortcut
    for (i = 0; i < _handlers[key].length; i++) {
      handler = _handlers[key][i];

      // see if it's in the current scope
      if(handler.scope == _scope || handler.scope == 'all'){
        // check if modifiers match if any
        modifiersMatch = handler.mods.length > 0;
        for(k in _mods)
          if((!_mods[k] && index(handler.mods, +k) > -1) ||
            (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
        // call the handler and stop the event if neccessary
        if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
          if(handler.method(event, handler)===false){
            if(event.preventDefault) event.preventDefault();
              else event.returnValue = false;
            if(event.stopPropagation) event.stopPropagation();
            if(event.cancelBubble) event.cancelBubble = true;
          }
        }
      }
	}
  };

  // unset modifier keys on keyup
  function clearModifier(event){
    var key = event.keyCode, k;
    if(key == 93 || key == 224) key = 91;
    if(key in _mods) {
      _mods[key] = false;
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = false;
    }
  };

  // parse and assign shortcut
  function assignKey(key, scope, method){
    var keys, mods, i, mi;
    if (method === undefined) {
      method = scope;
      scope = 'all';
    }
    key = key.replace(/\s/g,'');
    keys = key.split(',');

    if((keys[keys.length-1])=='')
      keys[keys.length-2] += ',';
    // for each shortcut
    for (i = 0; i < keys.length; i++) {
      // set modifier keys if any
      mods = [];
      key = keys[i].split('+');
      if(key.length > 1){
        mods = key.slice(0,key.length-1);
        for (mi = 0; mi < mods.length; mi++)
          mods[mi] = _MODIFIERS[mods[mi]];
        key = [key[key.length-1]];
      }
      // convert to keycode and...
      key = key[0]
      key = _MAP[key] || key.toUpperCase().charCodeAt(0);
      // ...store handler
      if (!(key in _handlers)) _handlers[key] = [];
      _handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
    }
  };

  // initialize key.<modifier> to false
  for(k in _MODIFIERS) assignKey[k] = false;

  // set current scope (default 'all')
  function setScope(scope){ _scope = scope || 'all' };
  function getScope(){ return scope || 'all' };

  // cross-browser events
  function addEvent(object, event, method) {
    if (object.addEventListener)
      object.addEventListener(event, method, false);
    else if(object.attachEvent)
      object.attachEvent('on'+event, function(){ method(window.event) });
  };

  // set the handlers globally on document
  addEvent(document, 'keydown', dispatch);
  addEvent(document, 'keyup', clearModifier);

  // set window.key and window.key.setScope
  global.key = assignKey;
  global.key.setScope = setScope;
  global.key.getScope = getScope;

  if(typeof module !== 'undefined') module.exports = key;

})(this);
<commit_msg>Fixed the getScope method to use _scope instead of undefined scope variable.<commit_after>//     keymaster.js
//     (c) 2011 Thomas Fuchs
//     keymaster.js may be freely distributed under the MIT license.

;(function(global){
  var k,
    _handlers = {},
    _mods = { 16: false, 18: false, 17: false, 91: false },
    _scope = 'all',
    // modifier keys
    _MODIFIERS = {
      '⇧': 16, shift: 16,
      option: 18, '⌥': 18, alt: 18,
      ctrl: 17, control: 17,
      command: 91, '⌘': 91
    },
    // special keys
    _MAP = {
      backspace: 8, tab: 9, clear: 12,
      enter: 13, 'return': 13,
      esc: 27, escape: 27, space: 32,
      left: 37, up: 38,
      right: 39, down: 40,
      del: 46, 'delete': 46,
      home: 36, end: 35,
      pageup: 33, pagedown: 34,
      ',': 188, '.': 190, '/': 191,
      '`': 192, '-': 189, '=': 187,
      ';': 186, '\'': 222,
      '[': 219, ']': 221, '\\': 220
    };

  for(k=1;k<20;k++) _MODIFIERS['f'+k] = 111+k;

  // IE doesn't support Array#indexOf, so have a simple replacement
  function index(array, item){
    var i = array.length;
    while(i--) if(array[i]===item) return i;
    return -1;
  }

  // handle keydown event
  function dispatch(event){
    var key, tagName, handler, k, i, modifiersMatch;
    tagName = (event.target || event.srcElement).tagName;
    key = event.keyCode;

    // if a modifier key, set the key.<modifierkeyname> property to true and return
    if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
    if(key in _mods) {
      _mods[key] = true;
      // 'assignKey' from inside this closure is exported to window.key
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
      return;
    }

    // ignore keypressed in any elements that support keyboard data input
    if (tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA') return;

    // abort if no potentially matching shortcuts found
    if (!(key in _handlers)) return;

    // for each potential shortcut
    for (i = 0; i < _handlers[key].length; i++) {
      handler = _handlers[key][i];

      // see if it's in the current scope
      if(handler.scope == _scope || handler.scope == 'all'){
        // check if modifiers match if any
        modifiersMatch = handler.mods.length > 0;
        for(k in _mods)
          if((!_mods[k] && index(handler.mods, +k) > -1) ||
            (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
        // call the handler and stop the event if neccessary
        if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
          if(handler.method(event, handler)===false){
            if(event.preventDefault) event.preventDefault();
              else event.returnValue = false;
            if(event.stopPropagation) event.stopPropagation();
            if(event.cancelBubble) event.cancelBubble = true;
          }
        }
      }
	}
  };

  // unset modifier keys on keyup
  function clearModifier(event){
    var key = event.keyCode, k;
    if(key == 93 || key == 224) key = 91;
    if(key in _mods) {
      _mods[key] = false;
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = false;
    }
  };

  // parse and assign shortcut
  function assignKey(key, scope, method){
    var keys, mods, i, mi;
    if (method === undefined) {
      method = scope;
      scope = 'all';
    }
    key = key.replace(/\s/g,'');
    keys = key.split(',');

    if((keys[keys.length-1])=='')
      keys[keys.length-2] += ',';
    // for each shortcut
    for (i = 0; i < keys.length; i++) {
      // set modifier keys if any
      mods = [];
      key = keys[i].split('+');
      if(key.length > 1){
        mods = key.slice(0,key.length-1);
        for (mi = 0; mi < mods.length; mi++)
          mods[mi] = _MODIFIERS[mods[mi]];
        key = [key[key.length-1]];
      }
      // convert to keycode and...
      key = key[0]
      key = _MAP[key] || key.toUpperCase().charCodeAt(0);
      // ...store handler
      if (!(key in _handlers)) _handlers[key] = [];
      _handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
    }
  };

  // initialize key.<modifier> to false
  for(k in _MODIFIERS) assignKey[k] = false;

  // set current scope (default 'all')
  function setScope(scope){ _scope = scope || 'all' };
  function getScope(){ return _scope || 'all' };

  // cross-browser events
  function addEvent(object, event, method) {
    if (object.addEventListener)
      object.addEventListener(event, method, false);
    else if(object.attachEvent)
      object.attachEvent('on'+event, function(){ method(window.event) });
  };

  // set the handlers globally on document
  addEvent(document, 'keydown', dispatch);
  addEvent(document, 'keyup', clearModifier);

  // set window.key and window.key.setScope
  global.key = assignKey;
  global.key.setScope = setScope;
  global.key.getScope = getScope;

  if(typeof module !== 'undefined') module.exports = key;

})(this);
<|endoftext|>


<commit_before>elation.elements.define('janus.ui.inventory', class extends elation.elements.base {
  create() {
    //this.innerHTML = elation.template.get('janus.ui.inventory');
    let elements = elation.elements.fromTemplate('janus.ui.inventory', this);

    console.log('INVENTORY ELEMENTS', elements);
    if (elements.primitives) {
      elation.events.add(elements.primitives, 'select', (ev) => this.handlePrimitiveSelect(ev));
      elation.events.add(elements.polyobjects, 'select', (ev) => this.handleAssetSelect(ev));
    }
  }
  addSource(name, collection) {
  }
  handlePrimitiveSelect(ev) {
    let item = ev.data;
    elation.events.fire({type: 'assetselect', data: item.url, element: this});
    ev.preventDefault();
    ev.stopPropagation();
  }
  handleAssetSelect(ev) {
    let item = ev.data;
    elation.events.fire({type: 'assetselect', data: item.url, element: this});
    ev.preventDefault();
    ev.stopPropagation();
  }
});
elation.elements.define('janus.ui.inventory.item.poly', class extends elation.elements.ui.item {
  create() {
    let item = this.value;

    for (let i = 0; i < item.formats.length; i++) {
      if (item.formats[i].formatType == 'GLTF2') {
        this.model = item.formats[i];
      }
    }
    if (!this.model) {
      this.model = item.formats[0];
    }

    let elements = elation.elements.fromTemplate('janus.ui.inventory.item.poly', this);
    elation.events.add(this, 'click', (ev) => this.click(ev));
  }
});
<commit_msg>Pass item URL through when inventory item is selected<commit_after>elation.elements.define('janus.ui.inventory', class extends elation.elements.base {
  create() {
    //this.innerHTML = elation.template.get('janus.ui.inventory');
    let elements = elation.elements.fromTemplate('janus.ui.inventory', this);

    console.log('INVENTORY ELEMENTS', elements);
    if (elements.primitives) {
      elation.events.add(elements.primitives, 'select', (ev) => this.handlePrimitiveSelect(ev));
      elation.events.add(elements.polyobjects, 'select', (ev) => this.handleAssetSelect(ev));
    }
  }
  addSource(name, collection) {
  }
  handlePrimitiveSelect(ev) {
    let item = ev.target;
    elation.events.fire({type: 'assetselect', data: item.value.href, element: this});
    ev.preventDefault();
    ev.stopPropagation();
  }
  handleAssetSelect(ev) {
    let item = ev.target;
    elation.events.fire({type: 'assetselect', data: item.model.root.url, element: this});
    ev.preventDefault();
    ev.stopPropagation();
  }
});
elation.elements.define('janus.ui.inventory.item.poly', class extends elation.elements.ui.item {
  create() {
    let item = this.value;

    for (let i = 0; i < item.formats.length; i++) {
      if (item.formats[i].formatType == 'GLTF2') {
        this.model = item.formats[i];
      }
    }
    if (!this.model) {
      this.model = item.formats[0];
    }

    let elements = elation.elements.fromTemplate('janus.ui.inventory.item.poly', this);
    elation.events.add(this, 'click', (ev) => this.click(ev));
  }
});
<|endoftext|>


<commit_before>(function() {

  'use strict';

  function KibiUtils () {}

  KibiUtils.prototype = (function(){

    //
    // PRIVATE methods
    //

    var _goToElement0 = function (json, path, ind, cb) {
      // the path is created from splitting a string on PATH_SEPARATOR.
      // If that string is empty, then the element in the array
      // is an empty string.
      if (path.length === ind || path[ind].length === 0) {
        cb(json);
      } else {
        // Walk down the path
        if (json.constructor === Object) {
          if (!json.hasOwnProperty(path[ind])) {
            throw new Error('No property=[' + path[ind] + '] in ' + JSON.stringify(json, null, ' '));
          }
          _goToElement0(json[path[ind]], path, ind + 1, cb);
        } else if (json.constructor === Array) {
          var arrayInd = parseInt(path[ind], 10);
          _goToElement0(json[arrayInd], path, ind + 1, cb);
        } else {
          throw new Error('Unexpected JSON type: ' + JSON.stringify(json, null, ' '));
        }
      }
    };

    var slugifyId = function (id) {
      if (id == null) return;

      var trans = {
        '/' : '-slash-',
        '\\?' : '-questionmark-',
        '\\&' : '-ampersand-',
        '=' : '-equal-',
        '#' : '-hash-'
      };
      for (var key in trans) {
        var regex = new RegExp(key, 'g');
        id = id.replace(regex, trans[key]);
      }
      id = id.replace(/[\s]+/g, '-');
      id = id.replace(/[\-]+/g, '-');
      return id;
    };

    //
    // PUBLIC METHODS
    //

    return {
      /**
      * Goto goes to the element located at path, and calls the callback
      * cb once there with that element as argument.
      * The path is an array.
      */
      goToElement: function (json, path, cb) {
        _goToElement0.call(this, json, path, 0, cb);
      },

      getUuid4: function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = Math.random() * 16 | 0;
          var v = c === 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      },

      slugifyId: slugifyId
    }

  })();

  // Make it to work in node and browser and AMD style
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = new KibiUtils();
  } else {
    if (typeof define === 'function' && define.amd) {
      define([], function () {
        return new KibiUtils();
      });
    } else {
      window.jsonUtils = new KibiUtils();
    }
  }

})();
<commit_msg>added datasource types helper methods<commit_after>(function() {

  'use strict';

  function KibiUtils () {}

  KibiUtils.prototype = (function(){

    //
    // PRIVATE methods
    //

    var _goToElement0 = function (json, path, ind, cb) {
      // the path is created from splitting a string on PATH_SEPARATOR.
      // If that string is empty, then the element in the array
      // is an empty string.
      if (path.length === ind || path[ind].length === 0) {
        cb(json);
      } else {
        // Walk down the path
        if (json.constructor === Object) {
          if (!json.hasOwnProperty(path[ind])) {
            throw new Error('No property=[' + path[ind] + '] in ' + JSON.stringify(json, null, ' '));
          }
          _goToElement0(json[path[ind]], path, ind + 1, cb);
        } else if (json.constructor === Array) {
          var arrayInd = parseInt(path[ind], 10);
          _goToElement0(json[arrayInd], path, ind + 1, cb);
        } else {
          throw new Error('Unexpected JSON type: ' + JSON.stringify(json, null, ' '));
        }
      }
    };

    var slugifyId = function (id) {
      if (id == null) return;

      var trans = {
        '/' : '-slash-',
        '\\?' : '-questionmark-',
        '\\&' : '-ampersand-',
        '=' : '-equal-',
        '#' : '-hash-'
      };
      for (var key in trans) {
        var regex = new RegExp(key, 'g');
        id = id.replace(regex, trans[key]);
      }
      id = id.replace(/[\s]+/g, '-');
      id = id.replace(/[\-]+/g, '-');
      return id;
    };

    //
    // Datasource type helpers
    //

    var DatasourceTypes = {
      sqlite: 'sqlite',
      rest: 'rest',
      postgresql: 'postgresql',
      mysql: 'mysql',
      sparql_http: 'sparql_http',
      sql_jdbc: 'sql_jdbc',
      sparql_jdbc: 'sparql_jdbc',
      tinkerpop3: 'tinkerpop3'
    };

    var isJDBC = function (type) {
      switch (type) {
        case DatasourceTypes.sql_jdbc:
        case DatasourceTypes.sparql_jdbc:
          return true;
        default:
          return false;
      }
    };

    var isSPARQL = function (type) {
      switch (type) {
        case DatasourceTypes.sparql_http:
        case DatasourceTypes.sparql_jdbc:
          return true;
        default:
          return false;
      }
    };

    var isSQL = function (type) {
      switch (type) {
        case DatasourceTypes.mysql:
        case DatasourceTypes.sqlite:
        case DatasourceTypes.postgresql:
        case DatasourceTypes.sql_jdbc:
          return true;
        default:
          return false;
      }
    };

    //
    // PUBLIC METHODS
    //

    return {
      /**
      * Goto goes to the element located at path, and calls the callback
      * cb once there with that element as argument.
      * The path is an array.
      */
      goToElement: function (json, path, cb) {
        _goToElement0.call(this, json, path, 0, cb);
      },

      getUuid4: function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = Math.random() * 16 | 0;
          var v = c === 'x' ? r : (r & 0x3 | 0x8);
          return v.toString(16);
        });
      },

      slugifyId: slugifyId,

      isSQL: isSQL,
      isJDBC: isJDBC,
      isSPARQL: isSPARQL,
      DatasourceTypes: DatasourceTypes
    }

  })();

  // Make it to work in node and browser and AMD style
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = new KibiUtils();
  } else {
    if (typeof define === 'function' && define.amd) {
      define([], function () {
        return new KibiUtils();
      });
    } else {
      window.jsonUtils = new KibiUtils();
    }
  }

})();
<|endoftext|>


<commit_before>/*
 * Extension of Bootstrap Modal
 * Allows reloading of modal content.
 *
 * To activate you need to pass the "reloadable" option which expects following values:
 * - true: enable reloading. Upon each toggle the toggle's href will replace the entire modal content.
 * - [title|header|body|footer]: enable reloading.
 *
 * 			     Upon each toggle the toggle's href will be fetched and the response html is searched for
 *               divs with the classes .modal-title, .modal-header, .modal-body, .modal-footer
 *               Each found class will replace (or inserting) the modal's div with that class.
 *
 *               If no class is found within the response html, the div class with the value of the option
 *               will be replaced.
 *
 * @copyright 2014 Cross Solution
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 */
;(function($) {

	/* Bootstrap modal */
	var Modal = $.fn.modal.Constructor;

	/* Constructor of the reloadable modal */
	var ReloadableModal = function (element, options) {
		this.cache     = {};
	    this.options   = options;
	    this.$element  = $(element);
	    this.$backdrop =
	    this.isShown   = null;
	    this.origHtml  = this.$element.html();

	    this.load = function(href)
	    {
	    	if (!this.cache[href]) {
	    		this.$element.html(this.origHtml);
	    		if (true === this.options.reloadable) {
	    			var $this = this;
	    			this.$element.load(href, function() {
	    				$this.cache[href] = $this.$element.html();
	    			});
	    			return;
	    		}

	    		var $this = this;
	    		$.get(href)
	    		 .done(function(html) {
	    			 var $html = $(html);
	    			 var $element = $this.$element;
	    			 var found = false;
	    			 $.each(['header', 'title', 'body', 'footer'], function(i, name) {
	    				 var className = '.modal-' + name;
	    				 var $elem = $html.find(className);
	    				 if ($elem.length) {
	    					 found = true;
	    					 var $orig = $element.find(className);
	    					 if ($orig.length) {
	    						 $orig.html($elem.html());
	    					 }
	    				 }
	    			 });

	    			 if (!found && $element.find('.modal-' + $this.options.reloadable).length) {
	    				 $element.find('.modal-' + $this.options.reloadable).html(html);
	    			 }
	    			 $this.cache[href] = $this.$element.html();
	    		 })
	    		 .fail(function() {
	    			 var title = $this.$element.data('error-title');
	    			 var body  = $this.$element.data('error-message');

	    			 if (!title) {
	    				 title = 'Error loading content.';
	    			 }
	    			 if (!body) {
	    				 body = '
An error occured while fetching the content of this modal box.
';
	    			 }

	    			 $this.$element.find('.modal-title').html(title);
	    			 $this.$element.find('.modal-body').html(body);

	    		 });

	    	} else {
	    		this.$element.html(this.cache[href]);
	    	}
	    };

	    this.load(this.options.remote);
	};

	ReloadableModal.prototype = $.fn.modal.Constructor.prototype;

	$.fn.modal = function (option, _relatedTarget)
	{

	    return this.each(function () {
	      var $this   = $(this);
	      var data    = $this.data('bs.modal');
	      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option);
	      if (options['reloadable']) {
	    	  if (!data) {
	    		  data = new ReloadableModal(this, options);
	    	  } else {
	    		  data.load(options.remote);
	    	  }
	      } else {
	    	  data = new Modal(this, options);
	      }
    	$this.data('bs.modal', data);
    	if (typeof option == 'string') data[option](_relatedTarget)
    	else if (options.show) data.show(_relatedTarget)
	  });
	};

})(jQuery);<commit_msg>[Core] Fixes: reloadable modal does not work if response html is not wrapped in a container<commit_after>/*
 * Extension of Bootstrap Modal
 * Allows reloading of modal content.
 *
 * To activate you need to pass the "reloadable" option which expects following values:
 * - true: enable reloading. Upon each toggle the toggle's href will replace the entire modal content.
 * - [title|header|body|footer]: enable reloading.
 *
 * 			     Upon each toggle the toggle's href will be fetched and the response html is searched for
 *               divs with the classes .modal-title, .modal-header, .modal-body, .modal-footer
 *               Each found class will replace (or inserting) the modal's div with that class.
 *
 *               If no class is found within the response html, the div class with the value of the option
 *               will be replaced.
 *
 * @copyright 2014 Cross Solution
 * @author Mathias Gelhausen <gelhausen@cross-solution.de>
 */
;(function($) {

	/* Bootstrap modal */
	var Modal = $.fn.modal.Constructor;

	/* Constructor of the reloadable modal */
	var ReloadableModal = function (element, options) {
		this.cache     = {};
	    this.options   = options;
	    this.$element  = $(element);
	    this.$backdrop =
	    this.isShown   = null;
	    this.origHtml  = this.$element.html();

	    this.load = function(href)
	    {
	    	if (!this.cache[href]) {
	    		this.$element.html(this.origHtml);
	    		if (true === this.options.reloadable) {
	    			var $this = this;
	    			this.$element.load(href, function() {
	    				$this.cache[href] = $this.$element.html();
	    			});
	    			return;
	    		}

	    		var $this = this;
	    		$.get(href)
	    		 .done(function(html) {
	    			 var $html = $(html);
	    			 var $element = $this.$element;
	    			 var found = false;
	    			 $html.each(function() {
	    				 var $htmlElement = $(this);
	    				 $.each(['header', 'title', 'body', 'footer'], function(i, name) {
	    					 var className = '.modal-' + name;
	    					 var $elem = $htmlElement.hasClass(className.substr(1))
	    					           ? $htmlElement
	    					           : $htmlElement.find(className);

	    					 if ($elem.length) {
	    						 found = true;
	    						 var $orig = $element.find(className);
	    						 if ($orig.length) {
	    							 $orig.html($elem.html());
	    						 }
	    					 }
	    				 });
	    			 });

	    			 if (!found && $element.find('.modal-' + $this.options.reloadable).length) {
	    				 $element.find('.modal-' + $this.options.reloadable).html(html);
	    			 }
	    			 $this.cache[href] = $this.$element.html();
	    		 })
	    		 .fail(function() {
	    			 var title = $this.$element.data('error-title');
	    			 var body  = $this.$element.data('error-message');

	    			 if (!title) {
	    				 title = 'Error loading content.';
	    			 }
	    			 if (!body) {
	    				 body = '
An error occured while fetching the content of this modal box.
';
	    			 }

	    			 $this.$element.find('.modal-title').html(title);
	    			 $this.$element.find('.modal-body').html(body);

	    		 });

	    	} else {
	    		this.$element.html(this.cache[href]);
	    	}
	    };

	    this.load(this.options.remote);
	};

	ReloadableModal.prototype = $.fn.modal.Constructor.prototype;

	$.fn.modal = function (option, _relatedTarget)
	{

	    return this.each(function () {
	      var $this   = $(this);
	      var data    = $this.data('bs.modal');
	      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option);
	      if (options['reloadable']) {
	    	  if (!data) {
	    		  data = new ReloadableModal(this, options);
	    	  } else {
	    		  data.load(options.remote);
	    	  }
	      } else {
	    	  data = new Modal(this, options);
	      }
    	$this.data('bs.modal', data);
    	if (typeof option == 'string') data[option](_relatedTarget)
    	else if (options.show) data.show(_relatedTarget)
	  });
	};

})(jQuery);<|endoftext|>


<commit_before>//   (c) 2007-2015 by Kajona, www.kajona.de
//       Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt
//       $Id$

$(function () {

    $.widget('custom.catcomplete', $.ui.autocomplete, {
        _renderMenu: function(ul, items) {
            var self = this;
            var currentCategory = '';

            $.each(items, function(index, item) {
                if (item.module != currentCategory) {
                    ul.append('

' + item.module + '

');
                    currentCategory = item.module;
                }
                self._renderItemData(ul, item);
            });

            ul.append('
'+searchExtendText+'
');
            ul.addClass('dropdown-menu');
            ul.addClass('search-dropdown-menu');

            ul.find('.detailedResults a').click(function () {
                $('.navbar-search').submit();
            });
        },
        _renderItemData: function (ul, item) {
            return $('

')
                .data('ui-autocomplete-item', item)
                .append('' + item.icon + item.description + '')
                .appendTo(ul);
        }
    });

    $('#globalSearchInput').catcomplete({
        //source: '_skinwebpath_/search.json',
        source: function(request, response) {
            $.ajax({
                url: KAJONA_WEBPATH+'/xml.php?admin=1',
                type: 'POST',
                dataType: 'json',
                data: {
                    search_query: request.term,
                    module: 'search',
                    action: 'searchXml',
                    asJson: '1'
                },
                success: response
            });
        },
        select: function (event, ui) {
            if(ui.item) {
                document.location = ui.item.link;
            }
        },
        messages: {
            noResults: '',
            results: function() {}
        },
        search: function(event, ui) {
            $(this).css("background-image", "url("+KAJONA_WEBPATH+"/core/module_v4skin/admin/skins/kajona_v4/img/loading-small.gif)").css("background-repeat", "no-repeat").
            css("background-position", "right center");
        },
        response: function(event, ui) {
            $(this).css("background-image", "none");
        }
    });

    // init popovers & tooltips
    $('#content a[rel=popover]').popover();
    KAJONA.admin.tooltip.initTooltip();

    KAJONA.admin.statusDisplay.classOfMessageBox = "alert alert-info";
    KAJONA.admin.statusDisplay.classOfErrorBox = "alert alert-error";

    KAJONA.admin.scroll = null;
    $(window).scroll(function() {
        var scroll = $(this).scrollTop();
        if(scroll > 10 && KAJONA.admin.scroll != 'top') {
            $("ul.breadcrumb").addClass("breadcrumbTop");
            KAJONA.admin.scroll = "top";
        }
        else if(scroll <= 10 && KAJONA.admin.scroll != 'margin') {
            $("ul.breadcrumb").removeClass("breadcrumbTop");
            KAJONA.admin.scroll = "fixed";
        }

    });

    KAJONA.v4skin.breadcrumb.updatePathNavigationEllipsis();
    $(window).on("resize", function() {
        KAJONA.v4skin.breadcrumb.updatePathNavigationEllipsis();

    });

    //register desktop notifications for messaging
    KAJONA.util.desktopNotification.grantPermissions();

    //init offacnvas menu
    $('[data-toggle="offcanvas"]').click(function () {
        $('.row-offcanvas').toggleClass('active')
    });

});

if (typeof KAJONA == "undefined") {
    alert('load kajona.js before!');
}

KAJONA.v4skin = {

    properties : {
        messaging : {},
        tags : {}
    },

    defaultAutoComplete : function() {

        this.minLength = 2;

        this.delay = KAJONA.util.isTouchDevice() ? 500 : 0;

        this.messages = {
            noResults: '',
            results: function() {return ''}
        };

        this.search = function(event, ui) {
            var $objCur = $(this);
            $objCur.css('background-image', 'url('+KAJONA_WEBPATH+'/core/module_v4skin/admin/skins/kajona_v4/img/loading-small.gif)');
            if(!$objCur.is('[readonly]')) {
                if($('#'+$objCur.attr('id')+'_id')) {
                    $( '#'+$objCur.attr('id')+'_id' ).val( "" );
                }
            }
        };

        this.response = function(event, ui) {
            $(this).css('background-image', 'none');
        };

        this.focus = function() {
            return false;
        };

        this.select = function( event, ui ) {
            if(ui.item) {
                var $objCur = $(this);
                $objCur.val( ui.item.title );
                if($('#'+$objCur.attr('id')+'_id')) {
                    $( '#'+$objCur.attr('id')+'_id' ).val( ui.item.systemid);
                }
            }

        };

        this.create = function( event, ui ) {
            var $objCur = $(this);
            $objCur.css('background-image', 'url('+KAJONA_WEBPATH+'/core/module_v4skin/admin/skins/kajona_v4/img/loading-small-still.gif)').css('background-repeat', 'no-repeat').css('background-position', 'right center');
        }
    },

    messaging : {

        bitFirstLoad : true,

        pollMessages : function() {
            KAJONA.admin.messaging.getRecentMessages(function (objResponse) {
                var $userNotificationsCount = $('#userNotificationsCount');
                var oldCount = $userNotificationsCount.text();
                $userNotificationsCount.text(objResponse.messageCount);
                if (objResponse.messageCount > 0) {
                    $userNotificationsCount.show();
                    if (oldCount != objResponse.messageCount) {
                        var strTitle = document.title.replace("(" + oldCount + ")", "");
                        document.title = "(" + objResponse.messageCount + ") " + strTitle;

                        if (!KAJONA.v4skin.messaging.bitFirstLoad && oldCount < objResponse.messageCount) {
                            KAJONA.util.desktopNotification.showMessage(KAJONA.v4skin.properties.messaging.notification_title, KAJONA.v4skin.properties.messaging.notification_body, function () {
                                document.location.href = KAJONA_WEBPATH+'/index.php?admin=1&module=messaging';
                            });
                        }
                    }

                } else {
                    $userNotificationsCount.hide();
                }

                $('#messagingShortlist').empty();
                $.each(objResponse.messages, function (index, item) {
                    if (item.unread == 0)
                        $('#messagingShortlist').append("
 " + item.title + "
");
                    else
                        $('#messagingShortlist').append("
 " + item.title + "
");
                });
                $('#messagingShortlist').append("

 " + KAJONA.v4skin.properties.messaging.show_all + "
");

                window.setTimeout("KAJONA.v4skin.messaging.pollMessages()", 20000);
                KAJONA.v4skin.messaging.bitFirstLoad = false;
            });
        }
    }
};

KAJONA.v4skin.breadcrumb = {
    updatePathNavigationEllipsis : function() {

        var $arrPathLIs = $(".pathNaviContainer  .breadcrumb  li.pathentry");
        var $objBreadcrumb = $(".pathNaviContainer  .breadcrumb");

        //first run: get the number of entries and a first styling
        var intEntries = ($arrPathLIs.length);
        var intWidth = $objBreadcrumb.width();
        var intMaxWidth = Math.ceil(intWidth/intEntries);

        $arrPathLIs.css("max-width", intMaxWidth);

        //second run: calc the remaining x-space
        var intTotalUnused = KAJONA.v4skin.breadcrumb.getUnusedSpace(intMaxWidth);

        if(intTotalUnused > intMaxWidth) {
            intMaxWidth = Math.ceil(intWidth/ (intEntries - (Math.floor(intTotalUnused / intMaxWidth)) ));
            $arrPathLIs.css("max-width", intMaxWidth);
        }

    },

    getUnusedSpace : function(intMaxWidth) {
        var intTotalUnused = 0;
        $(".pathNaviContainer  .breadcrumb  li.pathentry").each(function() {
            var $li = $(this);
            if($li.width() < intMaxWidth) {
                intTotalUnused += (intMaxWidth - $li.width());
            }
        });

        return intTotalUnused;
    },

    appendLinkToPathNavigation : function(strLinkContent) {
        var link = $("

").append(strLinkContent+" ");
        $("div.pathNaviContainer  ul.breadcrumb").append(link);
        KAJONA.v4skin.breadcrumb.updatePathNavigationEllipsis();
    }

};

KAJONA.v4skin.initTagMenu = function() {
    KAJONA.admin.ajax.genericAjaxCall("tags", "getFavoriteTags", "", function(data, status, jqXHR) {
        if(status == 'success') {
            $.each($.parseJSON(data), function(index, item) {
                $('#tagsSubemenu').append("
 "+item.name+"
");
            });
            $('#tagsSubemenu').append("

 "+KAJONA.v4skin.properties.tags.show_all+"
")
        }
    });
};

KAJONA.v4skin.removeObjectListItem = function(el){
    // remove all active tooltips
    $(el).children().qtip("hide");

    // remove element
    $(el).parent().parent().fadeOut(400, function(){
        $(this).remove();
    });
};

KAJONA.v4skin.setObjectListItems = function(strElementName, arrItems, arrAvailableIds){
    var table = $('#' + strElementName);
    var tbody = table.find('tbody');
    if(tbody.length > 0) {
        // remove only elements which are in the arrAvailableIds array
        tbody.children().each(function(){
            if($.inArray($(this).find('input[type="hidden"]').val(), arrAvailableIds) !== -1) {
                $(this).remove();
            }
        });

        // add new elements
        for(var i = 0; i < arrItems.length; i++) {
            var strEscapedTitle = $('

').text(arrItems[i].strDisplayName).html();
            var html = '';
            html+= '
';
            html+= '

	';
            html+= '    ' + strEscapedTitle + ' <input type="hidden" name="' + strElementName + '[]" value="' + arrItems[i].strSystemId + '" />	';
            html+= '    ';
            html+= '        ';
            html+= '            ';
            html+= '

';
            html+= '            ';
            html+= '        ';
            html+= '    	';
            html+= '
';

            tbody.append(html);
        }
    }
};

KAJONA.v4skin.sendCheckboxTreeSelection = function(el){
    if($('.jstree').length > 0) {
        // the query parameter contains the name of the form element where we insert the selected elements
        var strElementName = KAJONA.v4skin.getQueryParameter("element_name");

        // we modify only the ids which are visible for the user all other ids stay untouched
        var arrAvailableIds = [];
        $('.jstree').find('li').each(function(){
            arrAvailableIds.push($(this).attr('systemid'));
        });

        var arrEls = $('.jstree').jstree('get_checked');
        var arrItems = [];
        for(var i = 0; i < arrEls.length; i++) {
            var el = $(arrEls[i]);
            var strSystemId = el.attr('id');
            var strDisplayName = el.text().trim();
            var strIcon = el.find('div').data('kajona-icon');

            arrItems.push({
                strSystemId: strSystemId,
                strDisplayName: strDisplayName,
                strIcon: strIcon
            });
        }

        parent.KAJONA.v4skin.setObjectListItems(strElementName, arrItems, arrAvailableIds);

        parent.$('#folderviewDialog').modal('hide');
    }
};

KAJONA.v4skin.getCheckboxTreeSelectionFromParent = function(){
    if($('.jstree').length > 0) {
        // the query parameter contains the name of the form element where we insert the selected elements
        var strElementName = KAJONA.v4skin.getQueryParameter("element_name");
        var table = parent.$('#' + strElementName);
        var arrSystemIds = [];
        if(table.length > 0) {
            table.find('input[type="hidden"]').each(function(){
                arrSystemIds.push($(this).val());
            });
        }

        return arrSystemIds;
    }
};

/**
 * Extracts an query parameter from the location query string
 *
 * @param string name
 * @returns string
 */
KAJONA.v4skin.getQueryParameter = function(name) {
    var pos = location.search.indexOf("&" + name + "=");
    if(pos != -1) {
        var endPos = location.search.indexOf("&", pos + 1);
        if(endPos == -1) {
            return location.search.substr(pos + name.length + 2);
        }
        else {
            return location.search.substr(pos + name.length + 2, endPos - (pos + name.length + 2));
        }
    }
    return null;
};
<commit_msg>UPDATE: module_v4skin | v4skin.js > add docblocks to javascript methods and modify sendCheckboxTreeSelection method since we use jsdialog 1 the button is now outside of the iframe<commit_after>//   (c) 2007-2015 by Kajona, www.kajona.de
//       Published under the GNU LGPL v2.1, see /system/licence_lgpl.txt
//       $Id$

$(function () {

    $.widget('custom.catcomplete', $.ui.autocomplete, {
        _renderMenu: function(ul, items) {
            var self = this;
            var currentCategory = '';

            $.each(items, function(index, item) {
                if (item.module != currentCategory) {
                    ul.append('

' + item.module + '

');
                    currentCategory = item.module;
                }
                self._renderItemData(ul, item);
            });

            ul.append('
'+searchExtendText+'
');
            ul.addClass('dropdown-menu');
            ul.addClass('search-dropdown-menu');

            ul.find('.detailedResults a').click(function () {
                $('.navbar-search').submit();
            });
        },
        _renderItemData: function (ul, item) {
            return $('

')
                .data('ui-autocomplete-item', item)
                .append('' + item.icon + item.description + '')
                .appendTo(ul);
        }
    });

    $('#globalSearchInput').catcomplete({
        //source: '_skinwebpath_/search.json',
        source: function(request, response) {
            $.ajax({
                url: KAJONA_WEBPATH+'/xml.php?admin=1',
                type: 'POST',
                dataType: 'json',
                data: {
                    search_query: request.term,
                    module: 'search',
                    action: 'searchXml',
                    asJson: '1'
                },
                success: response
            });
        },
        select: function (event, ui) {
            if(ui.item) {
                document.location = ui.item.link;
            }
        },
        messages: {
            noResults: '',
            results: function() {}
        },
        search: function(event, ui) {
            $(this).css("background-image", "url("+KAJONA_WEBPATH+"/core/module_v4skin/admin/skins/kajona_v4/img/loading-small.gif)").css("background-repeat", "no-repeat").
            css("background-position", "right center");
        },
        response: function(event, ui) {
            $(this).css("background-image", "none");
        }
    });

    // init popovers & tooltips
    $('#content a[rel=popover]').popover();
    KAJONA.admin.tooltip.initTooltip();

    KAJONA.admin.statusDisplay.classOfMessageBox = "alert alert-info";
    KAJONA.admin.statusDisplay.classOfErrorBox = "alert alert-error";

    KAJONA.admin.scroll = null;
    $(window).scroll(function() {
        var scroll = $(this).scrollTop();
        if(scroll > 10 && KAJONA.admin.scroll != 'top') {
            $("ul.breadcrumb").addClass("breadcrumbTop");
            KAJONA.admin.scroll = "top";
        }
        else if(scroll <= 10 && KAJONA.admin.scroll != 'margin') {
            $("ul.breadcrumb").removeClass("breadcrumbTop");
            KAJONA.admin.scroll = "fixed";
        }

    });

    KAJONA.v4skin.breadcrumb.updatePathNavigationEllipsis();
    $(window).on("resize", function() {
        KAJONA.v4skin.breadcrumb.updatePathNavigationEllipsis();

    });

    //register desktop notifications for messaging
    KAJONA.util.desktopNotification.grantPermissions();

    //init offacnvas menu
    $('[data-toggle="offcanvas"]').click(function () {
        $('.row-offcanvas').toggleClass('active')
    });

});

if (typeof KAJONA == "undefined") {
    alert('load kajona.js before!');
}

KAJONA.v4skin = {

    properties : {
        messaging : {},
        tags : {}
    },

    defaultAutoComplete : function() {

        this.minLength = 2;

        this.delay = KAJONA.util.isTouchDevice() ? 500 : 0;

        this.messages = {
            noResults: '',
            results: function() {return ''}
        };

        this.search = function(event, ui) {
            var $objCur = $(this);
            $objCur.css('background-image', 'url('+KAJONA_WEBPATH+'/core/module_v4skin/admin/skins/kajona_v4/img/loading-small.gif)');
            if(!$objCur.is('[readonly]')) {
                if($('#'+$objCur.attr('id')+'_id')) {
                    $( '#'+$objCur.attr('id')+'_id' ).val( "" );
                }
            }
        };

        this.response = function(event, ui) {
            $(this).css('background-image', 'none');
        };

        this.focus = function() {
            return false;
        };

        this.select = function( event, ui ) {
            if(ui.item) {
                var $objCur = $(this);
                $objCur.val( ui.item.title );
                if($('#'+$objCur.attr('id')+'_id')) {
                    $( '#'+$objCur.attr('id')+'_id' ).val( ui.item.systemid);
                }
            }

        };

        this.create = function( event, ui ) {
            var $objCur = $(this);
            $objCur.css('background-image', 'url('+KAJONA_WEBPATH+'/core/module_v4skin/admin/skins/kajona_v4/img/loading-small-still.gif)').css('background-repeat', 'no-repeat').css('background-position', 'right center');
        }
    },

    messaging : {

        bitFirstLoad : true,

        pollMessages : function() {
            KAJONA.admin.messaging.getRecentMessages(function (objResponse) {
                var $userNotificationsCount = $('#userNotificationsCount');
                var oldCount = $userNotificationsCount.text();
                $userNotificationsCount.text(objResponse.messageCount);
                if (objResponse.messageCount > 0) {
                    $userNotificationsCount.show();
                    if (oldCount != objResponse.messageCount) {
                        var strTitle = document.title.replace("(" + oldCount + ")", "");
                        document.title = "(" + objResponse.messageCount + ") " + strTitle;

                        if (!KAJONA.v4skin.messaging.bitFirstLoad && oldCount < objResponse.messageCount) {
                            KAJONA.util.desktopNotification.showMessage(KAJONA.v4skin.properties.messaging.notification_title, KAJONA.v4skin.properties.messaging.notification_body, function () {
                                document.location.href = KAJONA_WEBPATH+'/index.php?admin=1&module=messaging';
                            });
                        }
                    }

                } else {
                    $userNotificationsCount.hide();
                }

                $('#messagingShortlist').empty();
                $.each(objResponse.messages, function (index, item) {
                    if (item.unread == 0)
                        $('#messagingShortlist').append("
 " + item.title + "
");
                    else
                        $('#messagingShortlist').append("
 " + item.title + "
");
                });
                $('#messagingShortlist').append("

 " + KAJONA.v4skin.properties.messaging.show_all + "
");

                window.setTimeout("KAJONA.v4skin.messaging.pollMessages()", 20000);
                KAJONA.v4skin.messaging.bitFirstLoad = false;
            });
        }
    }
};

KAJONA.v4skin.breadcrumb = {
    updatePathNavigationEllipsis : function() {

        var $arrPathLIs = $(".pathNaviContainer  .breadcrumb  li.pathentry");
        var $objBreadcrumb = $(".pathNaviContainer  .breadcrumb");

        //first run: get the number of entries and a first styling
        var intEntries = ($arrPathLIs.length);
        var intWidth = $objBreadcrumb.width();
        var intMaxWidth = Math.ceil(intWidth/intEntries);

        $arrPathLIs.css("max-width", intMaxWidth);

        //second run: calc the remaining x-space
        var intTotalUnused = KAJONA.v4skin.breadcrumb.getUnusedSpace(intMaxWidth);

        if(intTotalUnused > intMaxWidth) {
            intMaxWidth = Math.ceil(intWidth/ (intEntries - (Math.floor(intTotalUnused / intMaxWidth)) ));
            $arrPathLIs.css("max-width", intMaxWidth);
        }

    },

    getUnusedSpace : function(intMaxWidth) {
        var intTotalUnused = 0;
        $(".pathNaviContainer  .breadcrumb  li.pathentry").each(function() {
            var $li = $(this);
            if($li.width() < intMaxWidth) {
                intTotalUnused += (intMaxWidth - $li.width());
            }
        });

        return intTotalUnused;
    },

    appendLinkToPathNavigation : function(strLinkContent) {
        var link = $("

").append(strLinkContent+" ");
        $("div.pathNaviContainer  ul.breadcrumb").append(link);
        KAJONA.v4skin.breadcrumb.updatePathNavigationEllipsis();
    }

};

KAJONA.v4skin.initTagMenu = function() {
    KAJONA.admin.ajax.genericAjaxCall("tags", "getFavoriteTags", "", function(data, status, jqXHR) {
        if(status == 'success') {
            $.each($.parseJSON(data), function(index, item) {
                $('#tagsSubemenu').append("
 "+item.name+"
");
            });
            $('#tagsSubemenu').append("

 "+KAJONA.v4skin.properties.tags.show_all+"
")
        }
    });
};

/**
 * Removes an object list row from the list
 *
 * @param el
 */
KAJONA.v4skin.removeObjectListItem = function(el){
    // remove all active tooltips
    $(el).children().qtip("hide");

    // remove element
    $(el).parent().parent().fadeOut(400, function(){
        $(this).remove();
    });
};

/**
 * Sets an array of items to an object list. We remove only elements which are available in the arrAvailableIds array
 *
 * @param strElementName
 * @param arrItems
 * @param arrAvailableIds
 */
KAJONA.v4skin.setObjectListItems = function(strElementName, arrItems, arrAvailableIds){
    var table = $('#' + strElementName);
    var tbody = table.find('tbody');
    if(tbody.length > 0) {
        // remove only elements which are in the arrAvailableIds array
        tbody.children().each(function(){
            if($.inArray($(this).find('input[type="hidden"]').val(), arrAvailableIds) !== -1) {
                $(this).remove();
            }
        });

        // add new elements
        for(var i = 0; i < arrItems.length; i++) {
            var strEscapedTitle = $('

').text(arrItems[i].strDisplayName).html();
            var html = '';
            html+= '
';
            html+= '

	';
            html+= '    ' + strEscapedTitle + ' <input type="hidden" name="' + strElementName + '[]" value="' + arrItems[i].strSystemId + '" />	';
            html+= '    ';
            html+= '        ';
            html+= '            ';
            html+= '

';
            html+= '            ';
            html+= '        ';
            html+= '    	';
            html+= '
';

            tbody.append(html);
        }
    }
};

/**
 * We get the current tree selection from the iframe element and set the selection in the object list
 *
 * @param objIframeEl
 * @param strElementName
 */
KAJONA.v4skin.updateCheckboxTreeSelection = function(objIframeEl, strElementName){
    if(objIframeEl && objIframeEl.contentWindow) {
        var jstree = objIframeEl.contentWindow.$('.jstree');
        if(jstree.length > 0) {
            // we modify only the ids which are visible for the user all other ids stay untouched
            var arrAvailableIds = [];
            jstree.find('li').each(function(){
                arrAvailableIds.push($(this).attr('systemid'));
            });

            var arrEls = jstree.jstree('get_checked');
            var arrItems = [];
            for(var i = 0; i < arrEls.length; i++) {
                var el = $(arrEls[i]);
                var strSystemId = el.attr('id');
                var strDisplayName = el.text().trim();
                var strIcon = el.find('div').data('kajona-icon');

                arrItems.push({
                    strSystemId: strSystemId,
                    strDisplayName: strDisplayName,
                    strIcon: strIcon
                });
            }

            KAJONA.v4skin.setObjectListItems(strElementName, arrItems, arrAvailableIds);

            jsDialog_1.hide();
        }
    }
};

/**
 * Returns all systemids which are available in the object list. The name of the object list element name must be
 * available as GET parameter "element_name"
 *
 * @returns array
 */
KAJONA.v4skin.getCheckboxTreeSelectionFromParent = function(){
    if($('.jstree').length > 0) {
        // the query parameter contains the name of the form element where we insert the selected elements
        var strElementName = KAJONA.v4skin.getQueryParameter("element_name");
        var table = parent.$('#' + strElementName);
        var arrSystemIds = [];
        if(table.length > 0) {
            table.find('input[type="hidden"]').each(function(){
                arrSystemIds.push($(this).val());
            });
        }

        return arrSystemIds;
    }
};

/**
 * Extracts an query parameter from the location query string
 *
 * @param string name
 * @returns string
 */
KAJONA.v4skin.getQueryParameter = function(name) {
    var pos = location.search.indexOf("&" + name + "=");
    if(pos != -1) {
        var endPos = location.search.indexOf("&", pos + 1);
        if(endPos == -1) {
            return location.search.substr(pos + name.length + 2);
        }
        else {
            return location.search.substr(pos + name.length + 2, endPos - (pos + name.length + 2));
        }
    }
    return null;
};
<|endoftext|>


<commit_before>// Amara, universalsubtitles.org
//
// Copyright (C) 2013 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

(function (Popcorn, window, document) {

    var STATIC_ROOT_URL = window.Amara.conf.STATIC_ROOT_URL;
    var

        CURRENT_TIME_MONITOR_MS = 16,
        EMPTY_STRING = "";

    function HTMLFlashFallbackVideoElement(id) {

        // FlashFallback iframe API requires postMessage
        if (!window.postMessage) {
            throw "ERROR: HTMLFlashFallbackVideoElement requires window.postMessage";
        }

        var self = this,
            parent = typeof id === "string" ? Popcorn.dom.find(id) : id,
            elem = document.createElement("div"),

            impl = {
                src: EMPTY_STRING,
                networkState: self.NETWORK_EMPTY,
                readyState: self.HAVE_NOTHING,
                seeking: false,
                autoplay: EMPTY_STRING,
                preload: EMPTY_STRING,
                controls: true,
                loop: false,
                poster: EMPTY_STRING,
                // FlashFallback seems to use .77 as default
                volume: 1,
                // FlashFallback has no concept of muted, store volume values
                // such that muted===0 is unmuted, and muted>0 is muted.
                muted: 0,
                currentTime: 0,
                duration: NaN,
                ended: false,
                paused: true,
                error: null
            },
            playerReady = false,
            playerUID = Popcorn.guid(),
            player,
            playerReadyCallbacks = [],
            timeUpdateInterval,
            currentTimeInterval,
            lastCurrentTime = 0;

        elem.id = Popcorn.guid("amara-flowplayer");
        window.elem = elem;
        // Namespace all events we'll produce
        self._eventNamespace = Popcorn.guid("HTMLFlashFallbackVideoElement::");

        self.parentNode = parent;

        // Mark type as FlashFallback
        self._util.type = "FlashFallback";

        function addPlayerReadyCallback(callback) {
            playerReadyCallbacks.unshift(callback);
        }

        function onPlayerReady() {
            // FIXME: for some reason we need to set the width  / height here
            // this ins't right and will break on window rezise. What's the
            // best approach here?
            var objEl =  jQuery("object", elem).eq(0);
            var targetHeight = jQuery(elem).parent().height();
            var targetWidth =  jQuery(elem).parent().width();
            jQuery(objEl).width(targetWidth + "");
            jQuery(objEl).height(targetHeight + "");

            var clip = player.getClip(0);
            playerReady = true;
            clip.onResume(function () {

                onPlay();
            });
            clip.onPause(function () {
                onPause();
            });
            clip.onStop(function () {
                onPause();
            });
            clip.onStart(function () {
                onPlay();
            });
            clip.onMetaData(function () {
                self.dispatchEvent("loadedmetadata");
            });
        }

        function onPlayerJSReady(event) {
            parent.appendChild(elem);
            var flashEmbedParams = {
                'src': STATIC_ROOT_URL + "flowplayer/flowplayer-3.2.7.swf",
                'wmode': 'opaque',
                'width':impl.width + '',
                'height':impl.height + ''
            };
            var config = {
                'playlist': [
                    {
                        'url': impl.src,
                        'autoPlay': true
                    }
                ],
                'onLoad': function () {
                    onPlayerReady();
                }
            };
            player = player = $f(elem, flashEmbedParams, config);

            impl.networkState = self.NETWORK_LOADING;
            self.dispatchEvent("loadstart");
            self.dispatchEvent("progress");
        }

        function getDuration() {
            if (!playerReady) {
                // Queue a getDuration() call so we have correct duration info for loadedmetadata
                addPlayerReadyCallback(function () {
                    getDuration();
                });
            }
            return player.getClip().duration;
        }

        function destroyPlayer() {
            if (!( playerReady && player )) {
                return;
            }
            clearInterval(currentTimeInterval);
            player.pause();
            parent.removeChild(elem);
            elem = document.createElement("div");
        }

        self.play = function () {
            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    self.play();
                });
                return;
            }

            player.play();
        };

        function changeCurrentTime(aTime) {
            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    changeCurrentTime(aTime);
                });
                return;
            }

            onSeeking();
            player.seek(aTime);
        }

        function onSeeking() {
            impl.seeking = true;
            self.dispatchEvent("seeking");
        }

        function onSeeked() {
            impl.seeking = false;
            self.dispatchEvent("timeupdate");
            self.dispatchEvent("seeked");
            self.dispatchEvent("canplay");
            self.dispatchEvent("canplaythrough");
        }

        self.pause = function () {
            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    self.pause();
                });
                return;
            }
            player.pause();
        };

        function onPause() {
            impl.paused = true;
            clearInterval(timeUpdateInterval);
            self.dispatchEvent("pause");
        }

        function onTimeUpdate() {
            self.dispatchEvent("timeupdate");
        }

        function onPlay() {
            if (impl.ended) {
                changeCurrentTime(0);
            }
            if (!currentTimeInterval) {
                currentTimeInterval = setInterval(monitorCurrentTime,
                    CURRENT_TIME_MONITOR_MS);
                // Only 1 play when video.loop=true
                if (impl.loop) {
                    self.dispatchEvent("play");
                }
            }
            timeUpdateInterval = setInterval(onTimeUpdate,
                self._util.TIMEUPDATE_MS);

            if (impl.paused) {
                impl.paused = false;
                // Only 1 play when video.loop=true
                if (!impl.loop) {
                    self.dispatchEvent("play");
                }
                self.dispatchEvent("playing");
            }
        }

        function onEnded() {
            if (impl.loop) {
                changeCurrentTime(0);
                self.play();
            } else {
                impl.ended = true;
                self.dispatchEvent("ended");
            }
        }

        function onCurrentTime(aTime) {
            var currentTime = impl.currentTime = aTime;

            if (currentTime !== lastCurrentTime) {
                self.dispatchEvent("timeupdate");
            }

            lastCurrentTime = impl.currentTime;
        }

        function monitorCurrentTime() {
            onCurrentTime(player.getTime());
        }

        function loadFlowPlayerJs() {
            var el = document.createElement("script");
            window.jQuery = AmarajQuery;
            el.src = STATIC_ROOT_URL + "flowplayer/flowplayer-3.2.6.min.js";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(el, firstScriptTag);
            var intervalId = setInterval(function () {
                if (window.flowplayer && window.$f) {
                    clearInterval(intervalId);
                    onPlayerJSReady();
                }
            }, 200);
        }

        function changeSrc(aSrc) {
            if (!self._canPlaySrc(aSrc)) {
                impl.error = {
                    name: "MediaError",
                    message: "Media Source Not Supported",
                    code: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
                };
                self.dispatchEvent("error");
                return;
            }
            impl.src = aSrc;
            loadFlowPlayerJs();
            return;
        }

        function onVolume(aValue) {
            if (impl.volume !== aValue) {
                impl.volume = aValue;
                self.dispatchEvent("volumechange");
            }
        }

        function setVolume(aValue) {
            impl.volume = aValue;

            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    setVolume(aValue);
                });
                return;
            }
            player.setVolume(aValue);
            self.dispatchEvent("volumechange");
        }

        function getVolume() {
            // If we're muted, the volume is cached on impl.muted.
            return impl.muted > 0 ? impl.muted : impl.volume;
        }

        function setMuted(aMute) {
            if (!playerReady) {
                impl.muted = aMute ? 1 : 0;
                addPlayerReadyCallback(function () {
                    setMuted(aMute);
                });
                return;
            }

            // Move the existing volume onto muted to cache
            // until we unmute, and set the volume to 0.
            if (aMute) {
                impl.muted = impl.volume;
                setVolume(0);
            } else {
                impl.muted = 0;
                setVolume(impl.muted);
            }
        }

        function getMuted() {
            return impl.muted > 0;
        }

        Object.defineProperties(self, {

            src: {
                get: function () {
                    return impl.src;
                },
                set: function (aSrc) {
                    if (aSrc && aSrc !== impl.src) {
                        changeSrc(aSrc);
                    }
                }
            },

            autoplay: {
                get: function () {
                    return impl.autoplay;
                },
                set: function (aValue) {
                    impl.autoplay = self._util.isAttributeSet(aValue);
                }
            },

            loop: {
                get: function () {
                    return impl.loop;
                },
                set: function (aValue) {
                    impl.loop = self._util.isAttributeSet(aValue);
                }
            },

            width: {
                get: function () {
                    return self.parentNode.offsetWidth;
                }
            },

            height: {
                get: function () {
                    return self.parentNode.offsetHeight;
                }
            },

            currentTime: {
                get: function () {
                    return impl.currentTime;
                },
                set: function (aValue) {
                    changeCurrentTime(aValue);
                }
            },

            duration: {
                get: function () {
                    return impl.duration;
                }
            },

            ended: {
                get: function () {
                    return impl.ended;
                }
            },

            paused: {
                get: function () {
                    return impl.paused;
                }
            },

            seeking: {
                get: function () {
                    return impl.seeking;
                }
            },

            readyState: {
                get: function () {
                    return impl.readyState;
                }
            },

            networkState: {
                get: function () {
                    return impl.networkState;
                }
            },

            volume: {
                get: function () {
                    return getVolume();
                },
                set: function (aValue) {
                    if (aValue < 0 || aValue > 1) {
                        throw "Volume value must be between 0.0 and 1.0";
                    }

                    setVolume(aValue);
                }
            },

            muted: {
                get: function () {
                    return getMuted();
                },
                set: function (aValue) {
                    setMuted(self._util.isAttributeSet(aValue));
                }
            },

            error: {
                get: function () {
                    return impl.error;
                }
            }
        });
    }

    HTMLFlashFallbackVideoElement.prototype = new Popcorn._MediaElementProto();
    HTMLFlashFallbackVideoElement.prototype.constructor = HTMLFlashFallbackVideoElement;

    // Helper for identifying URLs we know how to play.
    HTMLFlashFallbackVideoElement.prototype._canPlaySrc = function (url) {
        var isH264 = (/\.mp4$/i.test(url) || /\.m4v$/i.test(url));
        var supportsVideo = !!document.createElement('video').canPlayType;
        // does this browser supports the native h264?
        var v = document.createElement("video");
        var canPlayH264 = v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');

        if (isH264 && (!supportsVideo || !canPlayH264)){
            return "probably"
        }
    };

    Popcorn.HTMLFlashFallbackVideoElement = function (id) {
        return new HTMLFlashFallbackVideoElement(id);
    };
    Popcorn.HTMLFlashFallbackVideoElement._canPlaySrc = HTMLFlashFallbackVideoElement.prototype._canPlaySrc;

}(Popcorn, window, document));
<commit_msg>2105: Remove fullscreen button, as this will cause more harm than good<commit_after>// Amara, universalsubtitles.org
//
// Copyright (C) 2013 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

(function (Popcorn, window, document) {

    var STATIC_ROOT_URL = window.Amara.conf.STATIC_ROOT_URL;
    var

        CURRENT_TIME_MONITOR_MS = 16,
        EMPTY_STRING = "";

    function HTMLFlashFallbackVideoElement(id) {

        // FlashFallback iframe API requires postMessage
        if (!window.postMessage) {
            throw "ERROR: HTMLFlashFallbackVideoElement requires window.postMessage";
        }

        var self = this,
            parent = typeof id === "string" ? Popcorn.dom.find(id) : id,
            elem = document.createElement("div"),

            impl = {
                src: EMPTY_STRING,
                networkState: self.NETWORK_EMPTY,
                readyState: self.HAVE_NOTHING,
                seeking: false,
                autoplay: EMPTY_STRING,
                preload: EMPTY_STRING,
                controls: true,
                loop: false,
                poster: EMPTY_STRING,
                // FlashFallback seems to use .77 as default
                volume: 1,
                // FlashFallback has no concept of muted, store volume values
                // such that muted===0 is unmuted, and muted>0 is muted.
                muted: 0,
                currentTime: 0,
                duration: NaN,
                ended: false,
                paused: true,
                error: null
            },
            playerReady = false,
            playerUID = Popcorn.guid(),
            player,
            playerReadyCallbacks = [],
            timeUpdateInterval,
            currentTimeInterval,
            lastCurrentTime = 0;

        elem.id = Popcorn.guid("amara-flowplayer");
        window.elem = elem;
        // Namespace all events we'll produce
        self._eventNamespace = Popcorn.guid("HTMLFlashFallbackVideoElement::");

        self.parentNode = parent;

        // Mark type as FlashFallback
        self._util.type = "FlashFallback";

        function addPlayerReadyCallback(callback) {
            playerReadyCallbacks.unshift(callback);
        }

        function onPlayerReady() {
            // FIXME: for some reason we need to set the width  / height here
            // this ins't right and will break on window rezise. What's the
            // best approach here?
            var objEl =  jQuery("object", elem).eq(0);
            var targetHeight = jQuery(elem).parent().height();
            var targetWidth =  jQuery(elem).parent().width();
            jQuery(objEl).width(targetWidth + "");
            jQuery(objEl).height(targetHeight + "");

            var clip = player.getClip(0);
            playerReady = true;
            clip.onResume(function () {

                onPlay();
            });
            clip.onPause(function () {
                onPause();
            });
            clip.onStop(function () {
                onPause();
            });
            clip.onStart(function () {
                onPlay();
            });
            clip.onMetaData(function () {
                self.dispatchEvent("loadedmetadata");
            });
        }

        function onPlayerJSReady(event) {
            parent.appendChild(elem);
            var flashEmbedParams = {
                'src': STATIC_ROOT_URL + "flowplayer/flowplayer-3.2.7.swf",
                'wmode': 'opaque',
                'width':impl.width + '',
                'height':impl.height + ''
            };
            var config = {
                'playlist': [
                    {
                        'url': impl.src,
                        'autoPlay': true
                    }
                ],
                'onLoad': function () {
                    onPlayerReady();
                },
                plugins:{
                    controls:{
                        fullscreen:false
                    }
                }
            };
            player = player = $f(elem, flashEmbedParams, config);

            impl.networkState = self.NETWORK_LOADING;
            self.dispatchEvent("loadstart");
            self.dispatchEvent("progress");
        }

        function getDuration() {
            if (!playerReady) {
                // Queue a getDuration() call so we have correct duration info for loadedmetadata
                addPlayerReadyCallback(function () {
                    getDuration();
                });
            }
            return player.getClip().duration;
        }

        function destroyPlayer() {
            if (!( playerReady && player )) {
                return;
            }
            clearInterval(currentTimeInterval);
            player.pause();
            parent.removeChild(elem);
            elem = document.createElement("div");
        }

        self.play = function () {
            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    self.play();
                });
                return;
            }

            player.play();
        };

        function changeCurrentTime(aTime) {
            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    changeCurrentTime(aTime);
                });
                return;
            }

            onSeeking();
            player.seek(aTime);
        }

        function onSeeking() {
            impl.seeking = true;
            self.dispatchEvent("seeking");
        }

        function onSeeked() {
            impl.seeking = false;
            self.dispatchEvent("timeupdate");
            self.dispatchEvent("seeked");
            self.dispatchEvent("canplay");
            self.dispatchEvent("canplaythrough");
        }

        self.pause = function () {
            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    self.pause();
                });
                return;
            }
            player.pause();
        };

        function onPause() {
            impl.paused = true;
            clearInterval(timeUpdateInterval);
            self.dispatchEvent("pause");
        }

        function onTimeUpdate() {
            self.dispatchEvent("timeupdate");
        }

        function onPlay() {
            if (impl.ended) {
                changeCurrentTime(0);
            }
            if (!currentTimeInterval) {
                currentTimeInterval = setInterval(monitorCurrentTime,
                    CURRENT_TIME_MONITOR_MS);
                // Only 1 play when video.loop=true
                if (impl.loop) {
                    self.dispatchEvent("play");
                }
            }
            timeUpdateInterval = setInterval(onTimeUpdate,
                self._util.TIMEUPDATE_MS);

            if (impl.paused) {
                impl.paused = false;
                // Only 1 play when video.loop=true
                if (!impl.loop) {
                    self.dispatchEvent("play");
                }
                self.dispatchEvent("playing");
            }
        }

        function onEnded() {
            if (impl.loop) {
                changeCurrentTime(0);
                self.play();
            } else {
                impl.ended = true;
                self.dispatchEvent("ended");
            }
        }

        function onCurrentTime(aTime) {
            var currentTime = impl.currentTime = aTime;

            if (currentTime !== lastCurrentTime) {
                self.dispatchEvent("timeupdate");
            }

            lastCurrentTime = impl.currentTime;
        }

        function monitorCurrentTime() {
            onCurrentTime(player.getTime());
        }

        function loadFlowPlayerJs() {
            var el = document.createElement("script");
            window.jQuery = AmarajQuery;
            el.src = STATIC_ROOT_URL + "flowplayer/flowplayer-3.2.6.min.js";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(el, firstScriptTag);
            var intervalId = setInterval(function () {
                if (window.flowplayer && window.$f) {
                    clearInterval(intervalId);
                    onPlayerJSReady();
                }
            }, 200);
        }

        function changeSrc(aSrc) {
            if (!self._canPlaySrc(aSrc)) {
                impl.error = {
                    name: "MediaError",
                    message: "Media Source Not Supported",
                    code: MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED
                };
                self.dispatchEvent("error");
                return;
            }
            impl.src = aSrc;
            loadFlowPlayerJs();
            return;
        }

        function onVolume(aValue) {
            if (impl.volume !== aValue) {
                impl.volume = aValue;
                self.dispatchEvent("volumechange");
            }
        }

        function setVolume(aValue) {
            impl.volume = aValue;

            if (!playerReady) {
                addPlayerReadyCallback(function () {
                    setVolume(aValue);
                });
                return;
            }
            player.setVolume(aValue);
            self.dispatchEvent("volumechange");
        }

        function getVolume() {
            // If we're muted, the volume is cached on impl.muted.
            return impl.muted > 0 ? impl.muted : impl.volume;
        }

        function setMuted(aMute) {
            if (!playerReady) {
                impl.muted = aMute ? 1 : 0;
                addPlayerReadyCallback(function () {
                    setMuted(aMute);
                });
                return;
            }

            // Move the existing volume onto muted to cache
            // until we unmute, and set the volume to 0.
            if (aMute) {
                impl.muted = impl.volume;
                setVolume(0);
            } else {
                impl.muted = 0;
                setVolume(impl.muted);
            }
        }

        function getMuted() {
            return impl.muted > 0;
        }

        Object.defineProperties(self, {

            src: {
                get: function () {
                    return impl.src;
                },
                set: function (aSrc) {
                    if (aSrc && aSrc !== impl.src) {
                        changeSrc(aSrc);
                    }
                }
            },

            autoplay: {
                get: function () {
                    return impl.autoplay;
                },
                set: function (aValue) {
                    impl.autoplay = self._util.isAttributeSet(aValue);
                }
            },

            loop: {
                get: function () {
                    return impl.loop;
                },
                set: function (aValue) {
                    impl.loop = self._util.isAttributeSet(aValue);
                }
            },

            width: {
                get: function () {
                    return self.parentNode.offsetWidth;
                }
            },

            height: {
                get: function () {
                    return self.parentNode.offsetHeight;
                }
            },

            currentTime: {
                get: function () {
                    return impl.currentTime;
                },
                set: function (aValue) {
                    changeCurrentTime(aValue);
                }
            },

            duration: {
                get: function () {
                    return impl.duration;
                }
            },

            ended: {
                get: function () {
                    return impl.ended;
                }
            },

            paused: {
                get: function () {
                    return impl.paused;
                }
            },

            seeking: {
                get: function () {
                    return impl.seeking;
                }
            },

            readyState: {
                get: function () {
                    return impl.readyState;
                }
            },

            networkState: {
                get: function () {
                    return impl.networkState;
                }
            },

            volume: {
                get: function () {
                    return getVolume();
                },
                set: function (aValue) {
                    if (aValue < 0 || aValue > 1) {
                        throw "Volume value must be between 0.0 and 1.0";
                    }

                    setVolume(aValue);
                }
            },

            muted: {
                get: function () {
                    return getMuted();
                },
                set: function (aValue) {
                    setMuted(self._util.isAttributeSet(aValue));
                }
            },

            error: {
                get: function () {
                    return impl.error;
                }
            }
        });
    }

    HTMLFlashFallbackVideoElement.prototype = new Popcorn._MediaElementProto();
    HTMLFlashFallbackVideoElement.prototype.constructor = HTMLFlashFallbackVideoElement;

    // Helper for identifying URLs we know how to play.
    HTMLFlashFallbackVideoElement.prototype._canPlaySrc = function (url) {
        var isH264 = (/\.mp4$/i.test(url) || /\.m4v$/i.test(url));
        var supportsVideo = !!document.createElement('video').canPlayType;
        // does this browser supports the native h264?
        var v = document.createElement("video");
        var canPlayH264 = v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"');

        if (isH264 && (!supportsVideo || !canPlayH264)){
            return "probably"
        }
    };

    Popcorn.HTMLFlashFallbackVideoElement = function (id) {
        return new HTMLFlashFallbackVideoElement(id);
    };
    Popcorn.HTMLFlashFallbackVideoElement._canPlaySrc = HTMLFlashFallbackVideoElement.prototype._canPlaySrc;

}(Popcorn, window, document));
<|endoftext|>