<commit_before>/* eslint no-nested-ternary: off */
import { getDocument } from 'ssr-window';
import $ from '../../shared/dom7';
import { extend, deleteProps } from '../../shared/utils';
import Framework7Class from '../../shared/class';
/** @jsx $jsx */
import $jsx from '../../shared/$jsx';

class Gauge extends Framework7Class {
  constructor(app, params = {}) {
    super(params, [app]);

    const self = this;

    const defaults = extend({}, app.params.gauge);

    // Extend defaults with modules params
    self.useModulesParams(defaults);

    self.params = extend(defaults, params);

    const { el } = self.params;
    if (!el) return self;

    const $el = $(el);
    if ($el.length === 0) return self;

    if ($el[0].f7Gauge) return $el[0].f7Gauge;

    extend(self, {
      app,
      $el,
      el: $el && $el[0],
    });

    $el[0].f7Gauge = self;

    // Install Modules
    self.useModules();

    self.init();

    return self;
  }

  calcRadius() {
    const self = this;
    const { size, borderWidth } = self.params;
    return size / 2 - borderWidth / 2;
  }

  calcBorderLength() {
    const self = this;
    const radius = self.calcRadius();
    return 2 * Math.PI * radius;
  }

  render() {
    const self = this;
    if (self.params.render) return self.params.render.call(self, self);

    const {
      type,
      value,
      size,
      bgColor,
      borderBgColor,
      borderColor,
      borderWidth,
      valueText,
      valueTextColor,
      valueFontSize,
      valueFontWeight,
      labelText,
      labelTextColor,
      labelFontSize,
      labelFontWeight,
    } = self.params;

    const semiCircle = type === 'semicircle';
    const radius = self.calcRadius();
    const length = self.calcBorderLength();
    const progress = Math.max(Math.min(value, 1), 0);

    return (
      <svg
        class="gauge-svg"
        width={`${size}px`}
        height={`${semiCircle ? size / 2 : size}px`}
        viewBox={`0 0 ${size} ${semiCircle ? size / 2 : size}`}
      >
        {semiCircle && (
          <path
            class="gauge-back-semi"
            d={`M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`}
            stroke={borderBgColor}
            stroke-width={borderWidth}
            fill={bgColor || 'none'}
          />
        )}
        {semiCircle && (
          <path
            class="gauge-front-semi"
            d={`M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`}
            stroke={borderColor}
            stroke-width={borderWidth}
            stroke-dasharray={length / 2}
            stroke-dashoffset={(length / 2) * (1 + progress)}
            fill={borderBgColor ? 'none' : bgColor || 'none'}
          />
        )}
        {!semiCircle && borderBgColor && (
          <circle
            class="gauge-back-circle"
            stroke={borderBgColor}
            stroke-width={borderWidth}
            fill={bgColor || 'none'}
            cx={size / 2}
            cy={size / 2}
            r={radius}
          />
        )}
        {!semiCircle && (
          <circle
            class="gauge-front-circle"
            transform={`rotate(-90 ${size / 2} ${size / 2})`}
            stroke={borderColor}
            stroke-width={borderWidth}
            stroke-dasharray={length}
            stroke-dashoffset={length * (1 - progress)}
            fill={borderBgColor ? 'none' : bgColor || 'none'}
            cx={size / 2}
            cy={size / 2}
            r={radius}
          />
        )}

        {valueText && (
          <text
            class="gauge-value-text"
            x="50%"
            y={semiCircle ? '100%' : '50%'}
            font-weight={valueFontWeight}
            font-size={valueFontSize}
            fill={valueTextColor}
            dy={semiCircle ? (labelText ? -labelFontSize - 15 : -5) : 0}
            text-anchor="middle"
            dominant-baseline={!semiCircle && 'middle'}
          >
            {valueText}
          </text>
        )}
        {labelText && (
          <text
            class="gauge-label-text"
            x="50%"
            y={semiCircle ? '100%' : '50%'}
            font-weight={labelFontWeight}
            font-size={labelFontSize}
            fill={labelTextColor}
            dy={semiCircle ? -5 : valueText ? valueFontSize / 2 + 10 : 0}
            text-anchor="middle"
            dominant-baseline={!semiCircle && 'middle'}
          >
            {labelText}
          </text>
        )}
      </svg>
    );
  }

  update(newParams = {}) {
    const self = this;
    const document = getDocument();
    const { params, $svgEl } = self;

    Object.keys(newParams).forEach((param) => {
      if (typeof newParams[param] !== 'undefined') {
        params[param] = newParams[param];
      }
    });
    if ($svgEl.length === 0) return self;

    const {
      value,
      size,
      bgColor,
      borderBgColor,
      borderColor,
      borderWidth,
      valueText,
      valueTextColor,
      valueFontSize,
      valueFontWeight,
      labelText,
      labelTextColor,
      labelFontSize,
      labelFontWeight,
    } = params;

    const length = self.calcBorderLength();
    const progress = Math.max(Math.min(value, 1), 0);
    const radius = self.calcRadius();
    const semiCircle = params.type === 'semicircle';

    const svgAttrs = {
      width: `${size}px`,
      height: `${semiCircle ? size / 2 : size}px`,
      viewBox: `0 0 ${size} ${semiCircle ? size / 2 : size}`,
    };
    Object.keys(svgAttrs).forEach((attr) => {
      $svgEl.attr(attr, svgAttrs[attr]);
    });
    if (semiCircle) {
      const backAttrs = {
        d: `M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`,
        stroke: borderBgColor,
        'stroke-width': borderWidth,
        fill: bgColor || 'none',
      };
      const frontAttrs = {
        d: `M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`,
        stroke: borderColor,
        'stroke-width': borderWidth,
        'stroke-dasharray': length / 2,
        'stroke-dashoffset': (length / 2) * (1 + progress),
        fill: borderBgColor ? 'none' : bgColor || 'none',
      };
      Object.keys(backAttrs).forEach((attr) => {
        $svgEl.find('.gauge-back-semi').attr(attr, backAttrs[attr]);
      });
      Object.keys(frontAttrs).forEach((attr) => {
        $svgEl.find('.gauge-front-semi').attr(attr, frontAttrs[attr]);
      });
    } else {
      const backAttrs = {
        stroke: borderBgColor,
        'stroke-width': borderWidth,
        fill: bgColor || 'none',
        cx: size / 2,
        cy: size / 2,
        r: radius,
      };
      const frontAttrs = {
        transform: `rotate(-90 ${size / 2} ${size / 2})`,
        stroke: borderColor,
        'stroke-width': borderWidth,
        'stroke-dasharray': length,
        'stroke-dashoffset': length * (1 - progress),
        fill: borderBgColor ? 'none' : bgColor || 'none',
        cx: size / 2,
        cy: size / 2,
        r: radius,
      };
      Object.keys(backAttrs).forEach((attr) => {
        $svgEl.find('.gauge-back-circle').attr(attr, backAttrs[attr]);
      });
      Object.keys(frontAttrs).forEach((attr) => {
        $svgEl.find('.gauge-front-circle').attr(attr, frontAttrs[attr]);
      });
    }
    if (valueText) {
      if (!$svgEl.find('.gauge-value-text').length) {
        const textEl = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        textEl.classList.add('gauge-value-text');
        $svgEl.append(textEl);
      }
      const textAttrs = {
        x: '50%',
        y: semiCircle ? '100%' : '50%',
        'font-weight': valueFontWeight,
        'font-size': valueFontSize,
        fill: valueTextColor,
        dy: semiCircle ? (labelText ? -labelFontSize - 15 : -5) : 0,
        'text-anchor': 'middle',
        'dominant-baseline': !semiCircle && 'middle',
      };
      Object.keys(textAttrs).forEach((attr) => {
        $svgEl.find('.gauge-value-text').attr(attr, textAttrs[attr]);
      });
      $svgEl.find('.gauge-value-text').text(valueText);
    } else {
      $svgEl.find('.gauge-value-text').remove();
    }
    if (labelText) {
      if (!$svgEl.find('.gauge-label-text').length) {
        const textEl = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        textEl.classList.add('gauge-label-text');
        $svgEl.append(textEl);
      }
      const labelAttrs = {
        x: '50%',
        y: semiCircle ? '100%' : '50%',
        'font-weight': labelFontWeight,
        'font-size': labelFontSize,
        fill: labelTextColor,
        dy: semiCircle ? -5 : valueText ? valueFontSize / 2 + 10 : 0,
        'text-anchor': 'middle',
        'dominant-baseline': !semiCircle && 'middle',
      };
      Object.keys(labelAttrs).forEach((attr) => {
        $svgEl.find('.gauge-label-text').attr(attr, labelAttrs[attr]);
      });
      $svgEl.find('.gauge-label-text').text(labelText);
    } else {
      $svgEl.find('.gauge-label-text').remove();
    }
    return self;
  }

  init() {
    const self = this;
    const $svgEl = $(self.render()).eq(0);
    $svgEl.f7Gauge = self;
    extend(self, {
      $svgEl,
      svgEl: $svgEl && $svgEl[0],
    });
    self.$el.append($svgEl);
    return self;
  }

  destroy() {
    const self = this;
    if (!self.$el || self.destroyed) return;
    self.$el.trigger('gauge:beforedestroy');
    self.emit('local::beforeDestroy selfBeforeDestroy', self);
    self.$svgEl.remove();
    delete self.$el[0].f7Gauge;
    deleteProps(self);
    self.destroyed = true;
  }
}
export default Gauge;
<commit_msg>fix(gauge): fix typed in `gaugeBeforeDestroy` event<commit_after>/* eslint no-nested-ternary: off */
import { getDocument } from 'ssr-window';
import $ from '../../shared/dom7';
import { extend, deleteProps } from '../../shared/utils';
import Framework7Class from '../../shared/class';
/** @jsx $jsx */
import $jsx from '../../shared/$jsx';

class Gauge extends Framework7Class {
  constructor(app, params = {}) {
    super(params, [app]);

    const self = this;

    const defaults = extend({}, app.params.gauge);

    // Extend defaults with modules params
    self.useModulesParams(defaults);

    self.params = extend(defaults, params);

    const { el } = self.params;
    if (!el) return self;

    const $el = $(el);
    if ($el.length === 0) return self;

    if ($el[0].f7Gauge) return $el[0].f7Gauge;

    extend(self, {
      app,
      $el,
      el: $el && $el[0],
    });

    $el[0].f7Gauge = self;

    // Install Modules
    self.useModules();

    self.init();

    return self;
  }

  calcRadius() {
    const self = this;
    const { size, borderWidth } = self.params;
    return size / 2 - borderWidth / 2;
  }

  calcBorderLength() {
    const self = this;
    const radius = self.calcRadius();
    return 2 * Math.PI * radius;
  }

  render() {
    const self = this;
    if (self.params.render) return self.params.render.call(self, self);

    const {
      type,
      value,
      size,
      bgColor,
      borderBgColor,
      borderColor,
      borderWidth,
      valueText,
      valueTextColor,
      valueFontSize,
      valueFontWeight,
      labelText,
      labelTextColor,
      labelFontSize,
      labelFontWeight,
    } = self.params;

    const semiCircle = type === 'semicircle';
    const radius = self.calcRadius();
    const length = self.calcBorderLength();
    const progress = Math.max(Math.min(value, 1), 0);

    return (
      <svg
        class="gauge-svg"
        width={`${size}px`}
        height={`${semiCircle ? size / 2 : size}px`}
        viewBox={`0 0 ${size} ${semiCircle ? size / 2 : size}`}
      >
        {semiCircle && (
          <path
            class="gauge-back-semi"
            d={`M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`}
            stroke={borderBgColor}
            stroke-width={borderWidth}
            fill={bgColor || 'none'}
          />
        )}
        {semiCircle && (
          <path
            class="gauge-front-semi"
            d={`M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`}
            stroke={borderColor}
            stroke-width={borderWidth}
            stroke-dasharray={length / 2}
            stroke-dashoffset={(length / 2) * (1 + progress)}
            fill={borderBgColor ? 'none' : bgColor || 'none'}
          />
        )}
        {!semiCircle && borderBgColor && (
          <circle
            class="gauge-back-circle"
            stroke={borderBgColor}
            stroke-width={borderWidth}
            fill={bgColor || 'none'}
            cx={size / 2}
            cy={size / 2}
            r={radius}
          />
        )}
        {!semiCircle && (
          <circle
            class="gauge-front-circle"
            transform={`rotate(-90 ${size / 2} ${size / 2})`}
            stroke={borderColor}
            stroke-width={borderWidth}
            stroke-dasharray={length}
            stroke-dashoffset={length * (1 - progress)}
            fill={borderBgColor ? 'none' : bgColor || 'none'}
            cx={size / 2}
            cy={size / 2}
            r={radius}
          />
        )}

        {valueText && (
          <text
            class="gauge-value-text"
            x="50%"
            y={semiCircle ? '100%' : '50%'}
            font-weight={valueFontWeight}
            font-size={valueFontSize}
            fill={valueTextColor}
            dy={semiCircle ? (labelText ? -labelFontSize - 15 : -5) : 0}
            text-anchor="middle"
            dominant-baseline={!semiCircle && 'middle'}
          >
            {valueText}
          </text>
        )}
        {labelText && (
          <text
            class="gauge-label-text"
            x="50%"
            y={semiCircle ? '100%' : '50%'}
            font-weight={labelFontWeight}
            font-size={labelFontSize}
            fill={labelTextColor}
            dy={semiCircle ? -5 : valueText ? valueFontSize / 2 + 10 : 0}
            text-anchor="middle"
            dominant-baseline={!semiCircle && 'middle'}
          >
            {labelText}
          </text>
        )}
      </svg>
    );
  }

  update(newParams = {}) {
    const self = this;
    const document = getDocument();
    const { params, $svgEl } = self;

    Object.keys(newParams).forEach((param) => {
      if (typeof newParams[param] !== 'undefined') {
        params[param] = newParams[param];
      }
    });
    if ($svgEl.length === 0) return self;

    const {
      value,
      size,
      bgColor,
      borderBgColor,
      borderColor,
      borderWidth,
      valueText,
      valueTextColor,
      valueFontSize,
      valueFontWeight,
      labelText,
      labelTextColor,
      labelFontSize,
      labelFontWeight,
    } = params;

    const length = self.calcBorderLength();
    const progress = Math.max(Math.min(value, 1), 0);
    const radius = self.calcRadius();
    const semiCircle = params.type === 'semicircle';

    const svgAttrs = {
      width: `${size}px`,
      height: `${semiCircle ? size / 2 : size}px`,
      viewBox: `0 0 ${size} ${semiCircle ? size / 2 : size}`,
    };
    Object.keys(svgAttrs).forEach((attr) => {
      $svgEl.attr(attr, svgAttrs[attr]);
    });
    if (semiCircle) {
      const backAttrs = {
        d: `M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`,
        stroke: borderBgColor,
        'stroke-width': borderWidth,
        fill: bgColor || 'none',
      };
      const frontAttrs = {
        d: `M${size - borderWidth / 2},${size / 2} a1,1 0 0,0 -${size - borderWidth},0`,
        stroke: borderColor,
        'stroke-width': borderWidth,
        'stroke-dasharray': length / 2,
        'stroke-dashoffset': (length / 2) * (1 + progress),
        fill: borderBgColor ? 'none' : bgColor || 'none',
      };
      Object.keys(backAttrs).forEach((attr) => {
        $svgEl.find('.gauge-back-semi').attr(attr, backAttrs[attr]);
      });
      Object.keys(frontAttrs).forEach((attr) => {
        $svgEl.find('.gauge-front-semi').attr(attr, frontAttrs[attr]);
      });
    } else {
      const backAttrs = {
        stroke: borderBgColor,
        'stroke-width': borderWidth,
        fill: bgColor || 'none',
        cx: size / 2,
        cy: size / 2,
        r: radius,
      };
      const frontAttrs = {
        transform: `rotate(-90 ${size / 2} ${size / 2})`,
        stroke: borderColor,
        'stroke-width': borderWidth,
        'stroke-dasharray': length,
        'stroke-dashoffset': length * (1 - progress),
        fill: borderBgColor ? 'none' : bgColor || 'none',
        cx: size / 2,
        cy: size / 2,
        r: radius,
      };
      Object.keys(backAttrs).forEach((attr) => {
        $svgEl.find('.gauge-back-circle').attr(attr, backAttrs[attr]);
      });
      Object.keys(frontAttrs).forEach((attr) => {
        $svgEl.find('.gauge-front-circle').attr(attr, frontAttrs[attr]);
      });
    }
    if (valueText) {
      if (!$svgEl.find('.gauge-value-text').length) {
        const textEl = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        textEl.classList.add('gauge-value-text');
        $svgEl.append(textEl);
      }
      const textAttrs = {
        x: '50%',
        y: semiCircle ? '100%' : '50%',
        'font-weight': valueFontWeight,
        'font-size': valueFontSize,
        fill: valueTextColor,
        dy: semiCircle ? (labelText ? -labelFontSize - 15 : -5) : 0,
        'text-anchor': 'middle',
        'dominant-baseline': !semiCircle && 'middle',
      };
      Object.keys(textAttrs).forEach((attr) => {
        $svgEl.find('.gauge-value-text').attr(attr, textAttrs[attr]);
      });
      $svgEl.find('.gauge-value-text').text(valueText);
    } else {
      $svgEl.find('.gauge-value-text').remove();
    }
    if (labelText) {
      if (!$svgEl.find('.gauge-label-text').length) {
        const textEl = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        textEl.classList.add('gauge-label-text');
        $svgEl.append(textEl);
      }
      const labelAttrs = {
        x: '50%',
        y: semiCircle ? '100%' : '50%',
        'font-weight': labelFontWeight,
        'font-size': labelFontSize,
        fill: labelTextColor,
        dy: semiCircle ? -5 : valueText ? valueFontSize / 2 + 10 : 0,
        'text-anchor': 'middle',
        'dominant-baseline': !semiCircle && 'middle',
      };
      Object.keys(labelAttrs).forEach((attr) => {
        $svgEl.find('.gauge-label-text').attr(attr, labelAttrs[attr]);
      });
      $svgEl.find('.gauge-label-text').text(labelText);
    } else {
      $svgEl.find('.gauge-label-text').remove();
    }
    return self;
  }

  init() {
    const self = this;
    const $svgEl = $(self.render()).eq(0);
    $svgEl.f7Gauge = self;
    extend(self, {
      $svgEl,
      svgEl: $svgEl && $svgEl[0],
    });
    self.$el.append($svgEl);
    return self;
  }

  destroy() {
    const self = this;
    if (!self.$el || self.destroyed) return;
    self.$el.trigger('gauge:beforedestroy');
    self.emit('local::beforeDestroy gaugeBeforeDestroy', self);
    self.$svgEl.remove();
    delete self.$el[0].f7Gauge;
    deleteProps(self);
    self.destroyed = true;
  }
}
export default Gauge;
<|endoftext|>


<commit_before>/*
 * L.Util is a namespace for various utility functions.
 */

L.Util = {
	extend: function(/*Object*/ dest) /*-> Object*/ {	// merge src properties into dest
		var sources = Array.prototype.slice.call(arguments, 1);
		for (var j = 0, len = sources.length, src; j < len; j++) {
			src = sources[j] || {};
			for (var i in src) {
				if (src.hasOwnProperty(i)) {
					dest[i] = src[i];
				}
			}
		}
		return dest;
	},

	bind: function(/*Function*/ fn, /*Object*/ obj) /*-> Object*/ {
		return function() {
			return fn.apply(obj, arguments);
		};
	},

	stamp: (function() {
		var lastId = 0, key = '_leaflet_id';
		return function(/*Object*/ obj) {
			obj[key] = obj[key] || ++lastId;
			return obj[key];
		};
	})(),

	limitExecByInterval: function(fn, time, context, delayFirstExec) {
		var lock, execOnUnlock, args;
		return function() {
			args = arguments;
			if (!lock) {
				lock = true;
				setTimeout(function(){
					lock = false;
					if (execOnUnlock) {
						args.callee.apply(context, args);
						execOnUnlock = false;
					}
				}, time);
				if (!delayFirstExec) {
					fn.apply(context, args);
				} else {
					delayFirstExec = false;
					execOnUnlock = true;
				}
			} else {
				execOnUnlock = true;
			}
		};
	},

	falseFn: function() { return false; },

	formatNum: function(num, digits) {
		var pow = Math.pow(10, digits);
		return Math.round(num * pow) / pow;
	}
};
<commit_msg>deferExecByInterval<commit_after>/*
 * L.Util is a namespace for various utility functions.
 */

L.Util = {
	extend: function(/*Object*/ dest) /*-> Object*/ {	// merge src properties into dest
		var sources = Array.prototype.slice.call(arguments, 1);
		for (var j = 0, len = sources.length, src; j < len; j++) {
			src = sources[j] || {};
			for (var i in src) {
				if (src.hasOwnProperty(i)) {
					dest[i] = src[i];
				}
			}
		}
		return dest;
	},

	bind: function(/*Function*/ fn, /*Object*/ obj) /*-> Object*/ {
		return function() {
			return fn.apply(obj, arguments);
		};
	},

	stamp: (function() {
		var lastId = 0, key = '_leaflet_id';
		return function(/*Object*/ obj) {
			obj[key] = obj[key] || ++lastId;
			return obj[key];
		};
	})(),

	limitExecByInterval: function(fn, time, context) {
		var lock, execOnUnlock, args;
		function exec(){
			lock = false;
			if (execOnUnlock) {
				args.callee.apply(context, args);
				execOnUnlock = false;
			}
		}
		return function() {
			args = arguments;
			if (!lock) {
				lock = true;
				setTimeout(exec, time);
				fn.apply(context, args);
			} else {
				execOnUnlock = true;
			}
		};
	},

	deferExecByInterval: function(fn, time, context) {
		var args, lock;
		function exec() {
			lock = false;
			fn.apply(context, args);
		}
		return function() {
			args = arguments;
			if (!lock) {
				lock = true;
				setTimeout(exec, time);
			}
		};
	},

	falseFn: function() { return false; },

	formatNum: function(num, digits) {
		var pow = Math.pow(10, digits);
		return Math.round(num * pow) / pow;
	}
};
<|endoftext|>


<commit_before>//viewmodel for the assess page
function pageViewModel(gvm) {
    console.log(document.title);
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    console.log(document.title + " test3");
    gvm.userId = -1;

    console.log(document.title + " test2");
    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.currentCourseId = null;
    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-course span:first").text(item.course);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentCourseId = item.courseid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateCourses(item.trainingid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/apirapporten/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("training");
                    $(".btn-course span:first").text("course");
                });
            });
        });
    };

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentCourseId = null;
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-course span:first").text("course");
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });

}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<commit_msg>test undo<commit_after>//viewmodel for the assess page
function pageViewModel(gvm) {
    console.log(document.title);
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n. __("AssessTitle2");}, gvm);
    console.log(document.title + " test3");
    gvm.userId = -1;

    console.log(document.title + " test2");
    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.currentCourseId = null;
    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-course span:first").text(item.course);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentCourseId = item.courseid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateCourses(item.trainingid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/api/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("training");
                    $(".btn-course span:first").text("course");
                });
            });
        });
    };

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentCourseId = null;
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-course span:first").text("course");
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });

}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<|endoftext|>


<commit_before>function makeDeleteButton() {
    return $('<button/>')
        .addClass('delete')
        .click(function() { $(this).closest('.toDelete').remove(); updateUrl(this); })
        .text('-');
}

function insertRoute(val) {
    var currentRouteValue = $('.route', $(val).parent()).val();
    $(val).parent().after(makeRoute('', currentRouteValue));
}

function makeRoute(val, currentRouteValue) {
    var input = $('<input/>')
                        .attr({type: 'text',
                               onfocus: 'routeValOnFocus(this)',
                               onkeyup: 'updateUrl(this)'})
                        .addClass('route')
    if (currentRouteValue == 'coverage') {
        var res = $('')
        .addClass('toDelete')
        .addClass('routeElt')
        .append(' ')
        .append($('')
                .addClass('pathElt')
                .append(input)
                .append(makeDeleteButton()))
        .append('<button class="add" onclick="insertRoute(this)">+</button>')
        makeCoverageList(val, input);
        return res;
    } else {
        return $('')
        .addClass('toDelete')
        .addClass('routeElt')
        .append(' ')
        .append($('')
                .addClass('pathElt')
                .append($('<input/>')
                        .attr({type: 'text',
                               onfocus: 'updateUrl(this)',
                               onkeyup: 'updateUrl(this)'})
                        .addClass('route')
                        .val(val))
                .append(makeDeleteButton()))
        .append('<button class="add" onclick="insertRoute(this)">+</button>')
    }
}

function routeValOnFocus(valInput) {
    var cov = $('.route', $(valInput).parent().parent().prev()).val();

    if (cov == 'coverage' && ! $(valInput).attr('class').contains('route ui-autocomplete-input')) {
        makeCoverageList($(valInput).val(), valInput);
    } else if (cov != 'coverage' && $(valInput).attr('class').contains('route ui-autocomplete-input')) {
        var delete_button = $('.delete', $(valInput).parent());
        var v = $(valInput).val();

        $(valInput).remove();

        var valueElt = $('<input/>', {type: 'text',
                                      onfocus: 'routeValOnFocus(this)',
                                      onkeyup: 'updateUrl(this)',
                                      class: 'route',
                                      value: v});
        valueElt.insertBefore(delete_button);
        valueElt.focus();
        valInput = valueElt;
    }
    updateUrl(valInput);
}

function makeParam(key, val) {
    var res = $('')
        .addClass('param')
        .addClass('toDelete')
        .append(' ');

    var attr = {type: 'text', onfocus: 'updateUrl(this)', onkeyup: '"updateUrl(this)"'};

    var intputKeyAttr = Object.assign(attr, {class: 'key', value: key});
    res.append($('<input/>', intputKeyAttr));
    res.append('=');
    var inputValAttr = Object.assign(attr, {class: 'value', value: val});
    var valueElt = $('<input/>', inputValAttr);

    autocomplete(valueElt);
    res.append(valueElt);
    res.append(makeDeleteButton());
    return res;
}

function insertParam() {
    $("#parameterList").append(makeParam('', ''));
}

function getFocusedElemValue(elemToTest, focusedElem, noEncoding) {
    if (focusedElem == elemToTest) {
        return '{0}'
            .format(noEncoding ? elemToTest.value : elemToTest.value.encodeURI());
    }
    return noEncoding ? elemToTest.value : elemToTest.value.encodeURI();
}

function makeCoverageList(val, obj) {
    var search = new URI(window.location).search(true);
    var api = $("#api input.api").attr('value');
    var request =  api + "/coverage";
    var token = search["token"];
    var res = [];

    $.ajax({
        headers: isUndefined(token) ? {} : { Authorization: "Basic " + btoa(token + ":" ) },
        dataType: "json",
        url: request,
        success: function(data) {
                for (var dict in data) {
                    for (var cov = 0; cov < data[dict].length; cov++) {
                        res.push(data[dict][cov].id);
                    }
                    if (val) { $(obj).val(val); }
                    var auto = $(obj).autocomplete({source: res, minLength: 0, scroll: true, delay: 500});
                    auto.focus(function() {
                        auto.autocomplete("search", '');
                    });
                    return auto;
                }
            }
    });
}

function finalUrl(focusedElem) {
    var finalUrl = getFocusedElemValue($('#api input.api')[0], focusedElem, true);
    $("#route .route").each(function(){
        finalUrl += '/' + getFocusedElemValue(this, focusedElem);
    });

    finalUrl += '?';

    $('#parameters input.key, #parameters input.value').each(function(){
        finalUrl += getFocusedElemValue(this, focusedElem);
        if ($(this).hasClass('key')) {
            finalUrl += '=';
        }
        if ($(this).hasClass('value')) {
            finalUrl += '&';
        }
    });
    return finalUrl;
}

function submit() {
    var token = $('#token input.token').val();
    var f = finalUrl(); // finalUrl can be called without any args
    window.location = '?request={0}&token={1}'.format(f.encodeURI(), token.encodeURI());
}

function updateUrl(focusedElem) {
    var f = finalUrl(focusedElem);
    $('#urlDynamic span').html(f);
}

function getCoverage() {
    var prevIsCoverage = false;
    var coverage = null;
    var covElt = $("#route input.route").each(function() {
        if (prevIsCoverage) {
            coverage = $(this).val();
        }
        prevIsCoverage = $(this).val() == 'coverage';
    });
    return coverage;
}

function autocomplete(elt) {
    $(elt).autocomplete({
        source: function(request, response) {
            var keyValue = elt.parent().children(".key").val();
            if ($.inArray(keyValue, ['from', 'to']) == -1) {
                response([]);
                return;
            }
            var token = $('#token input.token').val();
            var url = $('#api input.api').val();
            var cov = getCoverage();
            if (cov !== null) {
                url = '{0}/coverage/{1}'.format(url, cov);
            }
            $.ajax({
                url: '{0}/places?q={1}'.format(url, request.term.encodeURI()),
                headers: isUndefined(token) ? {} : { Authorization: "Basic " + btoa(token) },
                success: function(data) {
                    var res = [];
                    if ('places' in data) {
                        data['places'].forEach(function(place) {
                            res.push({ value: place.id, label: place.name });
                        });
                    }
                    response(res);
                },
                error: function() {
                    response([]);
                }
            });
        },
    });
}

$(document).ready(function() {
    var search = new URI(window.location).search(true);
    var token = search['token'];
    if (isUndefined(token)) { token = ''; }
    $("#token input.token").attr('value', token);
    $("#urlFormToken").attr('value', token);

    var request = search['request'];
    if (isUndefined(request)) { return; }

    var req_uri = new URI(request);
    var origin = req_uri.origin();
    var paths = req_uri.path().split('/');
    // The first element after a split is an empty string("")
    if (paths.length == 1) { return; }
    var api = origin;

    var vxxFound = false;
    paths.slice(1).forEach(function(r) {
      if (!r) { return; }
      if (vxxFound) {
        var currentRouteValue = $('#route span .route').last().val();
        $("#route").append(makeRoute(r.decodeURI(), currentRouteValue));
      } else {
        api = api + '/' + r.decodeURI();
        vxxFound = /^v\d+$/.test(r);
    	$("#api input.api").attr('value', api);
      }
    })

    var params = req_uri.search(true);

    if (! isUndefined(params)) {
        var param_elt = $("#parameterList");
        for (var key in params) {
          var value = params[key];
          // a list of params, ex.: forbidded_uris[]
          if (Array.isArray(value)) {
              value.forEach(function(v){
                param_elt.append(makeParam(key.decodeURI(), v.decodeURI()));
              });
          } else {
            param_elt.append(makeParam(key.decodeURI(), params[key]));
          }
        }
    }
    $('#urlDynamic span').html(request);
});
<commit_msg>restore input<commit_after>function makeDeleteButton() {
    return $('<button/>')
        .addClass('delete')
        .click(function() { $(this).closest('.toDelete').remove(); updateUrl(this); })
        .text('-');
}

function insertRoute(val) {
    var currentRouteValue = $('.route', $(val).parent()).val();
    $(val).parent().after(makeRoute('', currentRouteValue));
}

function makeRoute(val, currentRouteValue) {
    var input = $('<input/>')
                        .attr({type: 'text',
                               onfocus: 'routeValOnFocus(this)',
                               onkeyup: 'updateUrl(this)'})
                        .addClass('route')
    if (currentRouteValue == 'coverage') {
        var res = $('')
        .addClass('toDelete')
        .addClass('routeElt')
        .append(' ')
        .append($('')
                .addClass('pathElt')
                .append(input)
                .append(makeDeleteButton()))
        .append('<button class="add" onclick="insertRoute(this)">+</button>')
        makeCoverageList(val, input);
        return res;
    } else {
        return $('')
        .addClass('toDelete')
        .addClass('routeElt')
        .append(' ')
        .append($('')
                .addClass('pathElt')
                .append($('<input/>')
                        .attr({type: 'text',
                               onfocus: 'updateUrl(this)',
                               onkeyup: 'updateUrl(this)'})
                        .addClass('route')
                        .val(val))
                .append(makeDeleteButton()))
        .append('<button class="add" onclick="insertRoute(this)">+</button>')
    }
}

function routeValOnFocus(valInput) {
    var cov = $('.route', $(valInput).parent().parent().prev()).val();

    if (cov == 'coverage' && ! $(valInput).attr('class').contains('route ui-autocomplete-input')) {
        makeCoverageList($(valInput).val(), valInput);
    } else if (cov != 'coverage' && $(valInput).attr('class').contains('route ui-autocomplete-input')) {
        var delete_button = $('.delete', $(valInput).parent());
        var v = $(valInput).val();

        $(valInput).remove();

        var valueElt = $('<input/>', {type: 'text',
                                      onfocus: 'routeValOnFocus(this)',
                                      onkeyup: 'updateUrl(this)',
                                      class: 'route',
                                      value: v});
        valueElt.insertBefore(delete_button);
        valueElt.focus();
        valInput = valueElt;
    }
    updateUrl(valInput);
}

function makeParam(key, val) {
    var res = $('')
        .addClass('param')
        .addClass('toDelete')
        .append(' ');

    var attr = {type: 'text', onfocus: 'updateUrl(this)', onkeyup: '"updateUrl(this)"'};

    var intputKeyAttr = Object.assign(attr, {class: 'key', value: key});
    res.append($('<input/>', intputKeyAttr));
    res.append('=');
    var inputValAttr = Object.assign(attr, {class: 'value', value: val});
    var valueElt = $('<input/>', inputValAttr);

    autocomplete(valueElt);
    res.append(valueElt);
    res.append(makeDeleteButton());
    return res;
}

function insertParam() {
    $("#parameterList").append(makeParam('', ''));
}

function getFocusedElemValue(elemToTest, focusedElem, noEncoding) {
    if (focusedElem == elemToTest) {
        return '{0}'
            .format(noEncoding ? elemToTest.value : elemToTest.value.encodeURI());
    }
    return noEncoding ? elemToTest.value : elemToTest.value.encodeURI();
}

function makeCoverageList(val, obj) {
    var search = new URI(window.location).search(true);
    var api = $("#api input.api").attr('value');
    var request =  api + "/coverage";
    var token = search["token"];
    var res = [];

    $.ajax({
        headers: isUndefined(token) ? {} : { Authorization: "Basic " + btoa(token + ":" ) },
        dataType: "json",
        url: request,
        success: function(data) {
                for (var dict in data) {
                    for (var cov = 0; cov < data[dict].length; cov++) {
                        res.push(data[dict][cov].id);
                    }
                    if (val) { $(obj).val(val); }
                    var auto = $(obj).autocomplete({source: res, minLength: 0, scroll: true, delay: 500});
                    auto.focus(function() {
                        auto.autocomplete("search", '');
                    });
                    return auto;
                }
            }
    });
}

function finalUrl(focusedElem) {
    var finalUrl = getFocusedElemValue($('#api input.api')[0], focusedElem, true);
    $("#route input.route").each(function(){
        finalUrl += '/' + getFocusedElemValue(this, focusedElem);
    });

    finalUrl += '?';

    $('#parameters input.key, #parameters input.value').each(function(){
        finalUrl += getFocusedElemValue(this, focusedElem);
        if ($(this).hasClass('key')) {
            finalUrl += '=';
        }
        if ($(this).hasClass('value')) {
            finalUrl += '&';
        }
    });
    return finalUrl;
}

function submit() {
    var token = $('#token input.token').val();
    var f = finalUrl(); // finalUrl can be called without any args
    window.location = '?request={0}&token={1}'.format(f.encodeURI(), token.encodeURI());
}

function updateUrl(focusedElem) {
    var f = finalUrl(focusedElem);
    $('#urlDynamic span').html(f);
}

function getCoverage() {
    var prevIsCoverage = false;
    var coverage = null;
    var covElt = $("#route input.route").each(function() {
        if (prevIsCoverage) {
            coverage = $(this).val();
        }
        prevIsCoverage = $(this).val() == 'coverage';
    });
    return coverage;
}

function autocomplete(elt) {
    $(elt).autocomplete({
        source: function(request, response) {
            var keyValue = elt.parent().children(".key").val();
            if ($.inArray(keyValue, ['from', 'to']) == -1) {
                response([]);
                return;
            }
            var token = $('#token input.token').val();
            var url = $('#api input.api').val();
            var cov = getCoverage();
            if (cov !== null) {
                url = '{0}/coverage/{1}'.format(url, cov);
            }
            $.ajax({
                url: '{0}/places?q={1}'.format(url, request.term.encodeURI()),
                headers: isUndefined(token) ? {} : { Authorization: "Basic " + btoa(token) },
                success: function(data) {
                    var res = [];
                    if ('places' in data) {
                        data['places'].forEach(function(place) {
                            res.push({ value: place.id, label: place.name });
                        });
                    }
                    response(res);
                },
                error: function() {
                    response([]);
                }
            });
        },
    });
}

$(document).ready(function() {
    var search = new URI(window.location).search(true);
    var token = search['token'];
    if (isUndefined(token)) { token = ''; }
    $("#token input.token").attr('value', token);
    $("#urlFormToken").attr('value', token);

    var request = search['request'];
    if (isUndefined(request)) { return; }

    var req_uri = new URI(request);
    var origin = req_uri.origin();
    var paths = req_uri.path().split('/');
    // The first element after a split is an empty string("")
    if (paths.length == 1) { return; }
    var api = origin;

    var vxxFound = false;
    paths.slice(1).forEach(function(r) {
      if (!r) { return; }
      if (vxxFound) {
        var currentRouteValue = $('#route span .route').last().val();
        $("#route").append(makeRoute(r.decodeURI(), currentRouteValue));
      } else {
        api = api + '/' + r.decodeURI();
        vxxFound = /^v\d+$/.test(r);
    	$("#api input.api").attr('value', api);
      }
    })

    var params = req_uri.search(true);

    if (! isUndefined(params)) {
        var param_elt = $("#parameterList");
        for (var key in params) {
          var value = params[key];
          // a list of params, ex.: forbidded_uris[]
          if (Array.isArray(value)) {
              value.forEach(function(v){
                param_elt.append(makeParam(key.decodeURI(), v.decodeURI()));
              });
          } else {
            param_elt.append(makeParam(key.decodeURI(), params[key]));
          }
        }
    }
    $('#urlDynamic span').html(request);
});
<|endoftext|>


<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import Realm from 'realm';

export class PeriodSchedule extends Realm.Object {
  getUseablePeriodsForProgram(program, maxOrdersPerPeriod) {
    const periods = this.periods.reduce(period => {
      if (period.numberOfRequisitionsForProgram(program) >= maxOrdersPerPeriod) return null;
      return period;
    });
    return periods;
  }

  addPeriodIfUnique(period) {
    if (this.periods.filtered('id == $0', period.id).length > 0) return;
    this.periods.push(period);
  }
}

export default PeriodSchedule;

PeriodSchedule.schema = {
  name: 'PeriodSchedule',
  primaryKey: 'id',
  properties: {
    id: 'string',
    name: { type: 'string', default: 'Placeholder Name' },
    periods: { type: 'list', objectType: 'Period' },
  },
};
<commit_msg>Add fix to periods helper method<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import Realm from 'realm';

export class PeriodSchedule extends Realm.Object {
  getUseablePeriodsForProgram(program, maxOrdersPerPeriod) {
    const periods = this.periods.filter(
      period => period.numberOfRequisitionsForProgram(program) < maxOrdersPerPeriod
    );
    return periods;
  }

  addPeriodIfUnique(period) {
    if (this.periods.filtered('id == $0', period.id).length > 0) return;
    this.periods.push(period);
  }
}

export default PeriodSchedule;

PeriodSchedule.schema = {
  name: 'PeriodSchedule',
  primaryKey: 'id',
  properties: {
    id: 'string',
    name: { type: 'string', default: 'Placeholder Name' },
    periods: { type: 'list', objectType: 'Period' },
  },
};
<|endoftext|>


<commit_before>

// Player(id, path, parts);

// Parameters:
//     - id {String} id of div for video player
//     - path {String} path with video files
//     - parts {Number} count of 10sec parts

// Examples:
//     var player = new Player('video', '/users/1/video/2/', 40, watch_function);
//     player.startVideo();

function Player(elementId , video_path, duration, watch){
  this.videoPath  = video_path;
  this.highPath   = this.videoPath+'/720/';
  this.mediumPath = this.videoPath+'/360/';
  this.poorPath   = this.videoPath+'/240/';
  this.globalId   = elementId;
  this.wrapperId  = 'video_player_wrapper';
  this.counter = 0;
  this.partCounter = 0;
  this.playable = true;
  this.inner = '';
  this.parts = parseInt(duration);
  this.quality = 1;
  this.lock = true;
  this.newTime = false;
  this.fullscreen = false;
  this.watch = watch;

  this.createDom();
}
Player.prototype.createVideo = function(itemId){
  if(document.getElementById(itemId)){ // если уже такой открывок есть
    return false;
  }
  this.loadStarted();
  videoItem = $("<video id='"+itemId+"' src='"+(this.getPath()+this.counter)+".mp4'></video>");

  videoItem.on('loadedmetadata', { player: this }, function(event){
    event.data.player.loadEnded();
  });

  videoItem.hide();

  $(this.playerItem).append(videoItem);
}

Player.prototype.hideVideo = function(itemId){
  $('#'+itemId).remove();
}

Player.prototype.showVideo = function(itemId){
  item = document.getElementById(itemId);
  item.play();
  item.style.display = 'block';
  item.style.width   = '100%';
  item.style.height  = '100%';
}
Player.prototype.update = function() {
  console.log({lock: this.lock, part: this.counter, playable: this.playable, counter: this.partCounter, quality: this.quality, fullscreen: this.fullscreen});

  if(this.counter > (this.parts/2)){
    this.watch();
  }
  if(!this.lock) {
    this.partCounter--;
  }
  if((this.counter<this.parts)&&(this.partCounter%10==0)&&this.playable){
    this.partCounter = 0;

    if(this.counter == 0 || this.newTime) {
      this.newTime = false;

      newVideoId = this.globalId+this.counter;

      this.createVideo(newVideoId);
      this.showVideo(newVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      setTimeout(function(){ this.createVideo(this.newVideoId) }.bind(this), 1000);

      this.partCounter++;

    } else if(this.lock) {

      this.oldVideoId = this.globalId+(this.counter-1);
      this.hideVideo(this.oldVideoId);

      this.currentVideoId = this.globalId+this.counter;
      this.showVideo(this.currentVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      setTimeout(function(){ this.createVideo(this.newVideoId) }.bind(this), 1000);
    }
  }

  this.partCounter++;
  $('.player-controls.rewind').val(this.counter-1);
}

Player.prototype.pauseVideo = function(){
  itemId = this.globalId+(this.counter-1);
  item = document.getElementById(itemId);
  item.pause();
  this.playable = false;
}
Player.prototype.playVideo = function(){
  itemId = this.globalId+(this.counter-1);
  item = document.getElementById(itemId);
  item.play();
  this.playable = true;
}

Player.prototype.startVideo = function(){
  this.update();
  var self = this; // hack for 'this' forwarding into update
  setInterval(function(){self.update.call(self)}, 1000);

}

Player.prototype.setPath = function(time){

 if(time<4000){
    if(this.quality<2) this.quality++;
  }
  if(time>6000){
    if(this.quality>0) this.quality--;
  }
}

Player.prototype.getPath = function(){
  switch(this.quality){
    case 0:
      return this.poorPath;
    case 1:
      return this.mediumPath;
    case 2:
      return this.highPath;
  }
}

Player.prototype.goTo = function(value){
  this.partCounter = 0;
  this.hideVideo(this.globalId + (this.counter - 1));
  this.newTime = true;
  this.counter = parseInt(value);
}

Player.prototype.createDom = function(){
  $('#' + this.globalId).append('

')
  $('#' + this.wrapperId).append('

')
  $('#' + this.wrapperId).append('

')
  $('#' + this.wrapperId).append('

')
  $('#' + this.wrapperId + ' .play-controls').append('<button class="player-controls play">▶</button>')
  $('#' + this.wrapperId + ' .play-controls').append('<button class="player-controls pause">||</button>')
  $('#' + this.wrapperId + ' .play-controls').append('<button class="player-controls fullscreen">⬚</button>')
  $('#' + this.wrapperId + ' .rewind-controls').append('<input class="player-controls rewind" type="range" min="0" max="'+this.parts+'" value="0" />')

  this.playerItem = document.getElementById('player_videos');
  this.setEvents()
}

Player.prototype.setEvents = function(){
  $('.player-controls.play').on('click', { player: this }, function(event){
    event.data.player.playVideo();
  })

  $('.player-controls.pause').on('click', { player: this }, function(event){
    event.data.player.pauseVideo();
  })

  $('.player-controls.rewind').on('change', { player: this }, function(event){
    event.data.player.goTo($(this).val());
  })

  $('.player-controls.fullscreen').on('click', { player: this }, function(event){
    event.data.player.toggleFullScreen();
  })
}

Player.prototype.loadStarted = function(){
  this.lock = false;
  this.loadingTime = Date.now();
}

Player.prototype.loadEnded = function(){
  this.lock = true;
  this.loadingTime = Date.now() - this.loadingTime;
  this.setPath(this.loadingTime);
}

Player.prototype.toggleFullScreen = function(){
  if(this.fullscreen){
    this.fullscreen = false;
    wrapper.attr("style", "");
  } else {
    this.fullscreen = true;
    wrapper = $('#' + this.wrapperId);
    style = "position: fixed; right: 0; bottom: 0; min-width: 100%; min-height: 100%; width: auto; height: auto; z-index: 100;"
    wrapper.attr("style", style);
  }
}<commit_msg>pause bug fix<commit_after>

// Player(id, path, parts);

// Parameters:
//     - id {String} id of div for video player
//     - path {String} path with video files
//     - parts {Number} count of 10sec parts

// Examples:
//     var player = new Player('video', '/users/1/video/2/', 40, watch_function);
//     player.startVideo();

function Player(elementId , video_path, duration, watch){
  this.videoPath  = video_path;
  this.highPath   = this.videoPath+'/720/';
  this.mediumPath = this.videoPath+'/360/';
  this.poorPath   = this.videoPath+'/240/';
  this.globalId   = elementId;
  this.wrapperId  = 'video_player_wrapper';
  this.counter = 0;
  this.partCounter = 0;
  this.playable = true;
  this.inner = '';
  this.parts = parseInt(duration);
  this.quality = 1;
  this.lock = true;
  this.newTime = false;
  this.fullscreen = false;
  this.watch = watch;

  this.createDom();
}
Player.prototype.createVideo = function(itemId){
  if(document.getElementById(itemId)){ // если уже такой открывок есть
    return false;
  }
  this.loadStarted();
  videoItem = $("<video id='"+itemId+"' src='"+(this.getPath()+this.counter)+".mp4'></video>");

  videoItem.on('loadedmetadata', { player: this }, function(event){
    event.data.player.loadEnded();
  });

  videoItem.hide();

  $(this.playerItem).append(videoItem);
}

Player.prototype.hideVideo = function(itemId){
  $('#'+itemId).remove();
}

Player.prototype.showVideo = function(itemId){
  item = document.getElementById(itemId);
  item.play();
  item.style.display = 'block';
  item.style.width   = '100%';
  item.style.height  = '100%';
}
Player.prototype.update = function() {
  console.log({lock: this.lock, part: this.counter, playable: this.playable, counter: this.partCounter, quality: this.quality, fullscreen: this.fullscreen});

  if(this.counter > (this.parts/2)){
    this.watch();
  }
  if(!this.lock) {
    this.partCounter--;
  }
  if((this.counter<this.parts)&&(this.partCounter%10==0)&&this.playable){
    this.partCounter = 0;

    if(this.counter == 0 || this.newTime) {
      this.newTime = false;

      newVideoId = this.globalId+this.counter;

      this.createVideo(newVideoId);
      this.showVideo(newVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      setTimeout(function(){ this.createVideo(this.newVideoId) }.bind(this), 1000);

      this.partCounter++;

    } else if(this.lock) {

      this.oldVideoId = this.globalId+(this.counter-1);
      this.hideVideo(this.oldVideoId);

      this.currentVideoId = this.globalId+this.counter;
      this.showVideo(this.currentVideoId);

      this.counter++;
      this.newVideoId = this.globalId+this.counter;

      setTimeout(function(){ this.createVideo(this.newVideoId) }.bind(this), 1000);
    }
  }
  if(this.playable){
    this.partCounter++;
  }
  $('.player-controls.rewind').val(this.counter-1);
}

Player.prototype.pauseVideo = function(){
  itemId = this.globalId+(this.counter-1);
  item = document.getElementById(itemId);
  item.pause();
  this.playable = false;
}
Player.prototype.playVideo = function(){
  itemId = this.globalId+(this.counter-1);
  item = document.getElementById(itemId);
  item.play();
  this.playable = true;
}

Player.prototype.startVideo = function(){
  this.update();
  var self = this; // hack for 'this' forwarding into update
  setInterval(function(){self.update.call(self)}, 1000);

}

Player.prototype.setPath = function(time){

 if(time<4000){
    if(this.quality<2) this.quality++;
  }
  if(time>6000){
    if(this.quality>0) this.quality--;
  }
}

Player.prototype.getPath = function(){
  switch(this.quality){
    case 0:
      return this.poorPath;
    case 1:
      return this.mediumPath;
    case 2:
      return this.highPath;
  }
}

Player.prototype.goTo = function(value){
  this.partCounter = 0;
  this.hideVideo(this.globalId + (this.counter - 1));
  this.newTime = true;
  this.counter = parseInt(value);
}

Player.prototype.createDom = function(){
  $('#' + this.globalId).append('

')
  $('#' + this.wrapperId).append('

')
  $('#' + this.wrapperId).append('

')
  $('#' + this.wrapperId).append('

')
  $('#' + this.wrapperId + ' .play-controls').append('<button class="player-controls play">▶</button>')
  $('#' + this.wrapperId + ' .play-controls').append('<button class="player-controls pause">||</button>')
  $('#' + this.wrapperId + ' .play-controls').append('<button class="player-controls fullscreen">⬚</button>')
  $('#' + this.wrapperId + ' .rewind-controls').append('<input class="player-controls rewind" type="range" min="0" max="'+this.parts+'" value="0" />')

  this.playerItem = document.getElementById('player_videos');
  this.setEvents()
}

Player.prototype.setEvents = function(){
  $('.player-controls.play').on('click', { player: this }, function(event){
    event.data.player.playVideo();
  })

  $('.player-controls.pause').on('click', { player: this }, function(event){
    event.data.player.pauseVideo();
  })

  $('.player-controls.rewind').on('change', { player: this }, function(event){
    event.data.player.goTo($(this).val());
  })

  $('.player-controls.fullscreen').on('click', { player: this }, function(event){
    event.data.player.toggleFullScreen();
  })
}

Player.prototype.loadStarted = function(){
  this.lock = false;
  this.loadingTime = Date.now();
}

Player.prototype.loadEnded = function(){
  this.lock = true;
  this.loadingTime = Date.now() - this.loadingTime;
  this.setPath(this.loadingTime);
}

Player.prototype.toggleFullScreen = function(){
  if(this.fullscreen){
    this.fullscreen = false;
    wrapper.attr("style", "");
  } else {
    this.fullscreen = true;
    wrapper = $('#' + this.wrapperId);
    style = "position: fixed; right: 0; bottom: 0; min-width: 100%; min-height: 100%; width: auto; height: auto; z-index: 100;"
    wrapper.attr("style", style);
  }
}<|endoftext|>


<commit_before>/*
 Geo-OV - applicatie voor het registreren van KAR meldpunten

 Copyright (C) 2009-2013 B3Partners B.V.

 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/>.
 */
var store = null;
var grid = null;

function loadGrid (){
    store = Ext.create('Ext.data.Store',{
        storeId : 'rseqStore',
        fields : ['id','naam','dataowner','type','karAddress'],
        data : {
            'items' : rseqs
        },
        proxy : {
            type : 'memory',
            reader : {
                type : 'json',
                root : 'items'
            }
        }
    });
    grid = Ext.create(Ext.grid.Panel,{
        title : 'Geselecteerde verkeerssystemen',
        xtype : "grid",
        id : "grid",
        store : store,
        columns : [
            {
                text : 'KAR Adres',
                dataIndex : 'karAddress'
            },
            {
                text : 'Omschrijving',
                dataIndex : 'naam'
            },
            {
                text : 'Dataowner',
                dataIndex : 'dataowner',
                flex : 1
            },
            {
                text : 'Type',
                dataIndex : 'type'
            }
        ],
        height : 300,
        width : 700,
        renderTo : 'body',
        listeners : {
            select : {
                scope : this,
                fn : rowSelected
            }

        }
    });
}

function rowSelected (rowmodel,record){
    var selectedId = record.data.id;
    var iframe = Ext.get("VRIDetail").dom;
    iframe.src = righsUrl + "&rseq=" + selectedId;
}
var rseqType = {
    "" : "nieuw verkeerssysteem",
    "CROSSING" : "VRI",
    "GUARD" : "bewakingssysteem nadering voertuig",
    "BAR" : "afsluittingssysteem"
};

var rightsStore;
var rightsGrid;

function rseqFrame (){
    var me = this;
    Ext.create('Ext.form.Panel',{
        title : 'Bewerken ' + me.rseqType[rseq.type] + (rseq.karAddress == null ? "" : " met KAR adres " + rseq.karAddress),
        height : 320,
        width : 450,
        renderTo : 'rseq',
        icon : rseq.type == "" ? karTheme.crossing : karTheme[rseq.type.toLowerCase()],
        layout : 'fit',
        items : {
            id : 'rseqForm',
            xtype : 'form',
            bodyStyle : 'padding: 5px 5px 0',
            fieldDefaults : {
                msgTarget : 'side',
                disabled : true,
                disabledCls : 'myDisabledClass',
                labelWidth : 150
            },
            defaultType : 'textfield',
            defaults : {
                anchor : '100%'
            },
            items : [{
                    xtype : 'fieldcontainer',
                    fieldLabel : 'Soort verkeerssysteem',
                    defaultType : 'radiofield',
                    layout : 'vbox',
                    items : [{
                            name : 'type',
                            inputValue : 'CROSSING',
                            checked : rseq.type == 'CROSSING',
                            boxLabel : me.rseqType['CROSSING']
                        },{
                            name : 'type',
                            inputValue : 'GUARD',
                            checked : rseq.type == 'GUARD',
                            boxLabel : me.rseqType['GUARD']
                        },{
                            name : 'type',
                            inputValue : 'BAR',
                            checked : rseq.type == 'BAR',
                            boxLabel : me.rseqType['BAR']
                        }]
                }
                ,{
                    fieldLabel : 'Beheerder',
                    //xtype: 'text',
                    name : 'dataOwner',
                    value : dataOwner
                }
                ,{
                    fieldLabel : 'Beheerdersaanduiding',
                    name : 'crossingCode',
                    value : rseq.crossingCode
                },{
                    xtype : 'numberfield',
                    fieldLabel : 'KAR adres',
                    name : 'karAddress',
                    allowBlank : false,
                    minValue : 0,
                    value : rseq.karAddress,
                    listeners : {
                        change : function (field,value){
                            value = parseInt(value,10);
                            field.setValue(value);
                        }
                    }
                },{
                    fieldLabel : 'Plaats',
                    name : 'town',
                    value : rseq.town
                },{
                    fieldLabel : 'Locatie',
                    name : 'description',
                    value : rseq.description
                },{
                    xtype : 'datefield',
                    format : 'Y-m-d',
                    fieldLabel : 'Geldig vanaf',
                    name : 'validFrom',
                    value : rseq.validFrom
                },{
                    xtype : 'datefield',
                    format : 'Y-m-d',
                    fieldLabel : 'Geldig tot',
                    name : 'validUntil',
                    value : rseq.validUntil
                }]
        }
    });

    var checkboxRenderer = function (p1,p2,record,row,column,store,grid){
        var field = ["","read","write"][column];
        return Ext.String.format("<input type='checkbox' {0} onclick='rightChangedClick(event,{1},{2})'></input>",
                record.get(field) ? "checked='checked'" : "",
                row,
                column
                );
    };

    rightsStore = Ext.create('Ext.data.Store',{
        storeId : 'rightsStore',
        fields : ['id','user','read','write'],
        data : {
            'items' : [{
                    user : 'meine',
                    read : true,
                    write : false
                }]
        },
        proxy : {
            type : 'memory',
            reader : {
                type : 'json',
                root : 'items'
            }
        }
    });
    rightsGrid = Ext.create(Ext.grid.Panel,{
        title : 'Geselecteerde verkeerssystemen',
        xtype : "grid",
        id : "grid",
        store : rightsStore,
        columns : [
            {
                text : 'Gebruiker',
                dataIndex : 'user',
                flex : 1
            },
            {
                text : 'Lezen',
                dataIndex : 'read',
                renderer : checkboxRenderer
            },
            {
                text : 'Schrijven',
                dataIndex : 'write',
                renderer : checkboxRenderer
            }
        ],
        height : 300,
        width : 400,
        renderTo : 'rseqRights',
        dockedItems : [{
                xtype : 'toolbar',
                dock : 'bottom',
                ui : 'footer',
                defaults : {
                    minWidth : 100
                },
                items : [
                    {
                        xtype : "combo",
                        id: "gebruikerCombo",
                        fieldLabel : 'Gebruiker',
                        allowBlank : false,
                        store : Ext.create('Ext.data.Store',{
                            fields : ['fullname','id'],
                            data : me.gebruikers
                        }),
                        queryMode : 'local',
                        displayField : 'fullname',
                        valueField : 'id',
                        layout : {
                            width : 150
                        },
                        name : 'gebruikerCombo',
                        emptyText : "Selecteer",
                        flex : 1
                    },
                     {
                        xtype : 'button',
                        text : 'Voeg toe',
                        handler: function(){
                            var a = 0;
                        }
                    }
                ]
            }]
    });

}<commit_msg>Adding of users to the grid<commit_after>/*
 Geo-OV - applicatie voor het registreren van KAR meldpunten

 Copyright (C) 2009-2013 B3Partners B.V.

 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/>.
 */
var store = null;
var grid = null;

function loadGrid (){
    store = Ext.create('Ext.data.Store',{
        storeId : 'rseqStore',
        fields : ['id','naam','dataowner','type','karAddress'],
        data : {
            'items' : rseqs
        },
        proxy : {
            type : 'memory',
            reader : {
                type : 'json',
                root : 'items'
            }
        }
    });
    grid = Ext.create(Ext.grid.Panel,{
        title : 'Geselecteerde verkeerssystemen',
        xtype : "grid",
        id : "grid",
        store : store,
        columns : [
            {
                text : 'KAR Adres',
                dataIndex : 'karAddress'
            },
            {
                text : 'Omschrijving',
                dataIndex : 'naam'
            },
            {
                text : 'Dataowner',
                dataIndex : 'dataowner',
                flex : 1
            },
            {
                text : 'Type',
                dataIndex : 'type'
            }
        ],
        height : 300,
        width : 700,
        renderTo : 'body',
        listeners : {
            select : {
                scope : this,
                fn : rowSelected
            }

        }
    });
}

function rowSelected (rowmodel,record){
    var selectedId = record.data.id;
    var iframe = Ext.get("VRIDetail").dom;
    iframe.src = righsUrl + "&rseq=" + selectedId;
}
var rseqType = {
    "" : "nieuw verkeerssysteem",
    "CROSSING" : "VRI",
    "GUARD" : "bewakingssysteem nadering voertuig",
    "BAR" : "afsluittingssysteem"
};

var rightsStore;
var rightsGrid;

function rseqFrame (){
    var me = this;
    Ext.create('Ext.form.Panel',{
        title : 'Bewerken ' + me.rseqType[rseq.type] + (rseq.karAddress == null ? "" : " met KAR adres " + rseq.karAddress),
        height : 320,
        width : 450,
        renderTo : 'rseq',
        icon : rseq.type == "" ? karTheme.crossing : karTheme[rseq.type.toLowerCase()],
        layout : 'fit',
        items : {
            id : 'rseqForm',
            xtype : 'form',
            bodyStyle : 'padding: 5px 5px 0',
            fieldDefaults : {
                msgTarget : 'side',
                disabled : true,
                disabledCls : 'myDisabledClass',
                labelWidth : 150
            },
            defaultType : 'textfield',
            defaults : {
                anchor : '100%'
            },
            items : [{
                    xtype : 'fieldcontainer',
                    fieldLabel : 'Soort verkeerssysteem',
                    defaultType : 'radiofield',
                    layout : 'vbox',
                    items : [{
                            name : 'type',
                            inputValue : 'CROSSING',
                            checked : rseq.type == 'CROSSING',
                            boxLabel : me.rseqType['CROSSING']
                        },{
                            name : 'type',
                            inputValue : 'GUARD',
                            checked : rseq.type == 'GUARD',
                            boxLabel : me.rseqType['GUARD']
                        },{
                            name : 'type',
                            inputValue : 'BAR',
                            checked : rseq.type == 'BAR',
                            boxLabel : me.rseqType['BAR']
                        }]
                }
                ,{
                    fieldLabel : 'Beheerder',
                    //xtype: 'text',
                    name : 'dataOwner',
                    value : dataOwner
                }
                ,{
                    fieldLabel : 'Beheerdersaanduiding',
                    name : 'crossingCode',
                    value : rseq.crossingCode
                },{
                    xtype : 'numberfield',
                    fieldLabel : 'KAR adres',
                    name : 'karAddress',
                    allowBlank : false,
                    minValue : 0,
                    value : rseq.karAddress,
                    listeners : {
                        change : function (field,value){
                            value = parseInt(value,10);
                            field.setValue(value);
                        }
                    }
                },{
                    fieldLabel : 'Plaats',
                    name : 'town',
                    value : rseq.town
                },{
                    fieldLabel : 'Locatie',
                    name : 'description',
                    value : rseq.description
                },{
                    xtype : 'datefield',
                    format : 'Y-m-d',
                    fieldLabel : 'Geldig vanaf',
                    name : 'validFrom',
                    value : rseq.validFrom
                },{
                    xtype : 'datefield',
                    format : 'Y-m-d',
                    fieldLabel : 'Geldig tot',
                    name : 'validUntil',
                    value : rseq.validUntil
                }]
        }
    });

    var checkboxRenderer = function (p1,p2,record,row,column,store,grid){
        var field = ["","read","write"][column];
        return Ext.String.format("<input type='checkbox' {0} onclick='rightChangedClick(event,{1},{2})'></input>",
                record.get(field) ? "checked='checked'" : "",
                row,
                column
                );
    };

    rightsStore = Ext.create('Ext.data.Store',{
        storeId : 'rightsStore',
        fields : ['id','user','read','write'],
        data : {
            'items' : [{
                    user : 'meine',
                    read : true,
                    write : false
                }]
        },
        proxy : {
            type : 'memory',
            reader : {
                type : 'json',
                root : 'items'
            }
        }
    });
    rightsGrid = Ext.create(Ext.grid.Panel,{
        title : 'Geselecteerde verkeerssystemen',
        xtype : "grid",
        id : "grid",
        store : rightsStore,
        columns : [
            {
                text : 'Gebruiker',
                dataIndex : 'user',
                flex : 1
            },
            {
                text : 'Lezen',
                dataIndex : 'read',
                renderer : checkboxRenderer
            },
            {
                text : 'Schrijven',
                dataIndex : 'write',
                renderer : checkboxRenderer
            }
        ],
        height : 300,
        width : 400,
        renderTo : 'rseqRights',
        dockedItems : [{
                xtype : 'toolbar',
                dock : 'bottom',
                ui : 'footer',
                items : [
                    {
                        xtype : "combo",
                        id: "gebruikerCombo",
                        fieldLabel : 'Gebruiker',
                        allowBlank : false,
                        store : Ext.create('Ext.data.Store',{
                            fields : ['fullname','id'],
                            data : me.gebruikers
                        }),
                        queryMode : 'local',
                        displayField : 'fullname',
                        valueField : 'id',
                        name : 'gebruikerCombo',
                        emptyText : "Selecteer",
                        flex : 1
                    },
                     {
                        xtype : 'button',
                        text : 'Voeg toe',
                        handler: function(){
                            var combo = Ext.getCmp("gebruikerCombo");
                            var userId = combo.getValue();
                            if(userId){
                                var displayValue = combo.getDisplayValue();
                                rightsStore.loadData([{
                                    id:userId,
                                    user:displayValue,
                                    read:false,
                                    write:false
                                }],true);
                            }
                        }
                    },
                     {
                        xtype : 'button',
                        text : 'Verwijder',
                        handler: function(){
                            var a = 0;
                        }
                    }
                ]
            }]
    });

}<|endoftext|>


<commit_before>$(document).ready(function(){
    var dataset = {'id': 'guest'};
    connectServer('POST',
                  JSON.stringify(dataset),
                  'request',
                  function(data){
        if(data[0]["status"] == "0"){
            $('#update_date').html('更新時間：' + data[1]['time'] + '　　　瀏覽次數：' + data[1]['counter']);
            $('#update_message').html(data[1]['message']);
            $('#requesting').hide();

            var statistic_cnt_total = 0, statistic_cnt_sale = 0;
            for(var i = 0; i < 4; i++){
                var rate = (parseInt(data[2][i]['sale']) / parseInt(data[2][i]['total']) * 100).toFixed(1);
                statistic_cnt_total += parseInt(data[2][i]['total']);
                statistic_cnt_sale += parseInt(data[2][i]['sale']);
                $('#statistic_label_' + data[2][i]['type']).html(data[2][i]['price'] + '元：' + rate + '%');
                $('#statistic_bar_progress_' + data[2][i]['type']).css('width', (rate * 1.7).toFixed());
            }
            $('#statistic_label_total').html("總計：" + (statistic_cnt_sale / statistic_cnt_total * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_total').css('width', (statistic_cnt_sale / statistic_cnt_total * 170).toFixed());
            $('#statistic_label_DM').html("DM發送量： [" + data[2][5]['sale'] + ' / ' + data[2][5]['total'] + '] ' + (data[2][5]['sale'] / data[2][5]['total'] * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_DM').css('width', (statistic_cnt_sale / statistic_cnt_total * 950).toFixed());

            for(var i = 3; i < data.length; i++){
                var seat_id = '#seat_' + data[i]['floor'] + '_' + data[i]['row'] + '_' + data[i]['seat'];
                var seat_state = parseInt(data[i]['state']);
                var seat_type = parseInt(data[i]['type']);
                var seat_preserve = parseInt(data[i]['preserve']);
                if(seat_preserve > 0)
                    $(seat_id).addClass('seat_type_6');
                else if(seat_state == 2)
                    $(seat_id).addClass('seat_type_5');
                else if(seat_state == 1)
                    $(seat_id).addClass('seat_type_4');
                else{
                    if(seat_type >= 4)
                        $(seat_id).addClass('seat_type_6');
                    else
                        $(seat_id).addClass('seat_type_' + seat_type);
                }
            }
            $('#message').show();
            $('#floor_4').show();
            $('#floor_3').show();
            $('#floor_2').show();
            $('#statistic').show();
        }
        else if(data[0]["status"] == '1'){
            $('#requesting').html('目前非購票時段');
        }
        else{
            $('#requesting').html('讀取失敗，請稍候再試或聯絡管理員');
        }
    });
});
<commit_msg>fix bug<commit_after>$(document).ready(function(){
    var dataset = {'id': 'guest'};
    connectServer('POST',
                  JSON.stringify(dataset),
                  'request',
                  function(data){
        if(data[0]["status"] == "0"){
            $('#update_date').html('更新時間：' + data[1]['time'] + '　　　瀏覽次數：' + data[1]['counter']);
            $('#update_message').html(data[1]['message']);
            $('#requesting').hide();

            var statistic_cnt_total = 0, statistic_cnt_sale = 0;
            for(var i = 0; i < 4; i++){
                var rate = (parseInt(data[2][i]['sale']) / parseInt(data[2][i]['total']) * 100).toFixed(1);
                statistic_cnt_total += parseInt(data[2][i]['total']);
                statistic_cnt_sale += parseInt(data[2][i]['sale']);
                $('#statistic_label_' + data[2][i]['type']).html(data[2][i]['price'] + '元：' + rate + '%');
                $('#statistic_bar_progress_' + data[2][i]['type']).css('width', (rate * 1.7).toFixed());
            }
            $('#statistic_label_total').html("總計：" + (statistic_cnt_sale / statistic_cnt_total * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_total').css('width', (statistic_cnt_sale / statistic_cnt_total * 170).toFixed());
            $('#statistic_label_DM').html("DM發送量： [" + data[2][5]['sale'] + ' / ' + data[2][5]['total'] + '] ' + (data[2][5]['sale'] / data[2][5]['total'] * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_DM').css('width', (data[2][5]['sale'] / data[2][5]['total'] * 950).toFixed());

            for(var i = 3; i < data.length; i++){
                var seat_id = '#seat_' + data[i]['floor'] + '_' + data[i]['row'] + '_' + data[i]['seat'];
                var seat_state = parseInt(data[i]['state']);
                var seat_type = parseInt(data[i]['type']);
                var seat_preserve = parseInt(data[i]['preserve']);
                if(seat_preserve > 0)
                    $(seat_id).addClass('seat_type_6');
                else if(seat_state == 2)
                    $(seat_id).addClass('seat_type_5');
                else if(seat_state == 1)
                    $(seat_id).addClass('seat_type_4');
                else{
                    if(seat_type >= 4)
                        $(seat_id).addClass('seat_type_6');
                    else
                        $(seat_id).addClass('seat_type_' + seat_type);
                }
            }
            $('#message').show();
            $('#floor_4').show();
            $('#floor_3').show();
            $('#floor_2').show();
            $('#statistic').show();
        }
        else if(data[0]["status"] == '1'){
            $('#requesting').html('目前非購票時段');
        }
        else{
            $('#requesting').html('讀取失敗，請稍候再試或聯絡管理員');
        }
    });
});
<|endoftext|>