<commit_before>var HistogramView = require('./histogram-view');
var TorqueTimeSliderView = require('./torque-time-slider-view');

/**
 * Torque time-series histogram view.
 * Extends the common histogram chart view with time-control
 * this.dataviewModel is a histogram model
 */
module.exports = HistogramView.extend({
  className: 'CDB-Widget-content CDB-Widget-content--timeSeries',

  initialize: function () {
    if (!this.options.torqueLayerModel) throw new Error('torqeLayerModel is required');
    if (!this.options.rangeFilter) throw new Error('rangeFilter is required');
    if (!this.options.dataviewModel) throw new Error('dataviewModel is required');

    this._torqueLayerModel = this.options.torqueLayerModel;
    this._dataviewModel = this.options.dataviewModel;
    HistogramView.prototype.initialize.call(this);
  },

  _initBinds: function () {
    HistogramView.prototype._initBinds.call(this);

    this._torqueLayerModel.bind('change:renderRange', this._onRenderRangeChanged, this);
    this._torqueLayerModel.bind('change:steps change:start change:end', this._reSelectRange, this);

    this.add_related_model(this._torqueLayerModel);
  },

  _createHistogramView: function () {
    this._chartType = this._torqueLayerModel.get('column_type') === 'date' ? 'time' : 'number';
    HistogramView.prototype._createHistogramView.call(this);

    this._chartView.setAnimated();
    this._chartView.bind('on_brush_click', this._onBrushClick, this);

    var timeSliderView = new TorqueTimeSliderView({
      dataviewModel: this._dataviewModel, // a histogram model
      chartView: this._chartView,
      torqueLayerModel: this._torqueLayerModel
    });
    this.addView(timeSliderView);
    timeSliderView.render();
  },

  _onChangeData: function () {
    HistogramView.prototype._onChangeData.call(this);

    if (this._chartView) {
      this._reSelectRange();
    }
  },

  _onRenderRangeChanged: function (m, r) {
    if (r.start === undefined && r.end === undefined) {
      this._chartView.removeSelection();
      this._rangeFilter.unsetRange();
    }
  },

  _onBrushClick: function (indexPct) {
    var steps = this._torqueLayerModel.get('steps');
    var step = Math.round(steps * indexPct);

    // Going to the last step causes a jump to the beginning immediately
    if (step === steps) step -= 1;

    HistogramView.prototype.resetFilter.apply(this);

    this._torqueLayerModel.set({ step: step });
  },

  _onBrushEnd: function () {
    HistogramView.prototype._onBrushEnd.apply(this, arguments);

    this._reSelectRange();
  },

  _timeToStep: function (timestamp) {
    var steps = this._torqueLayerModel.get('steps');
    var start = this._torqueLayerModel.get('start');
    var end = this._torqueLayerModel.get('end');
    var step = (steps * (1000 * timestamp - start)) / (end - start);
    return step;
  },

  _reSelectRange: function () {
    if (!this._rangeFilter.isEmpty()) {
      var loStep = this._timeToStep(this._rangeFilter.get('min'));
      var hiStep = this._timeToStep(this._rangeFilter.get('max'));

      // clamp values since the range can be outside of the current torque thing
      var steps = this._torqueLayerModel.get('steps');
      this._torqueLayerModel.renderRange(
        this._clampRangeVal(0, steps, loStep), // start
        this._clampRangeVal(0, steps, hiStep) // end
      );
    }
  },

  _clampRangeVal: function (a, b, t) {
    return Math.max(a, Math.min(b, t));
  }
});
<commit_msg>Reset filter if values are not in data (torque only)<commit_after>var _ = require('underscore');
var HistogramView = require('./histogram-view');
var TorqueTimeSliderView = require('./torque-time-slider-view');

/**
 * Torque time-series histogram view.
 * Extends the common histogram chart view with time-control
 * this.dataviewModel is a histogram model
 */
module.exports = HistogramView.extend({
  className: 'CDB-Widget-content CDB-Widget-content--timeSeries',

  initialize: function () {
    if (!this.options.torqueLayerModel) throw new Error('torqeLayerModel is required');
    if (!this.options.rangeFilter) throw new Error('rangeFilter is required');
    if (!this.options.dataviewModel) throw new Error('dataviewModel is required');

    this._torqueLayerModel = this.options.torqueLayerModel;
    this._dataviewModel = this.options.dataviewModel;
    HistogramView.prototype.initialize.call(this);
  },

  _initBinds: function () {
    HistogramView.prototype._initBinds.call(this);

    this._torqueLayerModel.bind('change:renderRange', this._onRenderRangeChanged, this);
    this._torqueLayerModel.bind('change:steps change:start change:end', this._reSelectRange, this);

    this.add_related_model(this._torqueLayerModel);
  },

  _createHistogramView: function () {
    this._chartType = this._torqueLayerModel.get('column_type') === 'date' ? 'time' : 'number';
    HistogramView.prototype._createHistogramView.call(this);

    this._chartView.setAnimated();
    this._chartView.bind('on_brush_click', this._onBrushClick, this);

    var timeSliderView = new TorqueTimeSliderView({
      dataviewModel: this._dataviewModel, // a histogram model
      chartView: this._chartView,
      torqueLayerModel: this._torqueLayerModel
    });
    this.addView(timeSliderView);
    timeSliderView.render();
  },

  _onChangeData: function () {
    HistogramView.prototype._onChangeData.call(this);

    if (this._chartView) {
      this._reSelectRange();
    }
  },

  _onRenderRangeChanged: function (_model, range) {
    if (range.start === undefined && range.end === undefined) {
      this._chartView.removeSelection();
      this._rangeFilter.unsetRange();
    }
  },

  _onBrushClick: function (indexPct) {
    var steps = this._torqueLayerModel.get('steps');
    var step = Math.round(steps * indexPct);

    // Going to the last step causes a jump to the beginning immediately
    if (step === steps) step -= 1;

    HistogramView.prototype.resetFilter.apply(this);

    this._torqueLayerModel.set({ step: step });
  },

  _onBrushEnd: function () {
    HistogramView.prototype._onBrushEnd.apply(this, arguments);
    this._reSelectRange();
  },

  _timeToStep: function (timestamp) {
    var steps = this._torqueLayerModel.get('steps');
    var start = this._torqueLayerModel.get('start');
    var end = this._torqueLayerModel.get('end');
    var step = (steps * (1000 * timestamp - start)) / (end - start);
    return step;
  },

  _reSelectRange: function () {
    if (!this._rangeFilter.isEmpty()) {
      var min = this._rangeFilter.get('min');
      var max = this._rangeFilter.get('max');
      var loStep = this._timeToStep(min);
      var hiStep = this._timeToStep(max);

      // -- HACK: Reset filter if the min/max values are out of the scope
      var data = this._dataviewModel.get('data');
      var loBar = _.findWhere(data, { start: min });
      var hiBar = _.findWhere(data, { end: max });
      if (!loBar || !hiBar) {
        return this._torqueLayerModel.resetRenderRange();
      }

      // clamp values since the range can be outside of the current torque thing
      var steps = this._torqueLayerModel.get('steps');
      this._torqueLayerModel.renderRange(
        this._clampRangeVal(0, steps, loStep), // start
        this._clampRangeVal(0, steps, hiStep) // end
      );
    }
  },

  _clampRangeVal: function (a, b, t) {
    return Math.max(a, Math.min(b, t));
  }
});
<|endoftext|>


<commit_before>/*
 *     (C) Copyright 2012-2013 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform 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.
 *
 *     Wirecloud 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 Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global EzWebExt, Wirecloud*/

Wirecloud.location = {
    'domain': document.location.protocol + '//' + document.location.host,
    'protocol': document.location.protocol.substr(0, document.location.protocol.length - 1),
    'host': document.location.host
};

(function () {

    "use strict";

    var setRequestHeaders = function setRequestHeaders() {
        var headers, name;

        headers = EzWebExt.merge({
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
        }, this.options.requestHeaders);

        if (!('Content-Type' in headers) && this.options.contentType != null) {
            headers['Content-Type'] = this.options.contentType;
            if (this.options.encoding != null) {
                headers['Content-Type'] += '; charset=' + this.options.encoding;
            }
        }

        for (name in headers) {
            this.transport.setRequestHeader(name, headers[name]);
        }
    };

    var onReadyStateChange = function onReadyStateChange() {
        if (this.transport.readyState == 4) {

            var response = new Response(this);

            try {
                if (('on' + response.status) in this.options) {
                    this.options['on' + response.status](response);
                } else if (this.options.onSuccess && (response.status >= 200 && response.status < 300)) {
                    this.options.onSuccess(response);
                } else if (this.options.onFailure) {
                    this.options.onFailure(response);
                }
            } catch (e) {
            }

            if (this.options.onComplete) {
                try {
                    this.options.onComplete();
                } catch (e) {}
            }
        }
    };

    var Response = function Response(request) {
        Object.defineProperties(this, {
            'request': {value: request},
            'transport': {value: request.transport},
            'status': {value: request.transport.status},
            'statusText': {value: request.transport.statusText},
            'response': {value: request.transport.response}
        });

        if (request.options.responseType == null || request.options.responseType === '') {
            Object.defineProperty(this, 'responseText', {value: request.transport.responseText});
        }
    };

    Response.prototype.getHeader = function getHeader(name) {
        try {
            return this.transport.getResponseHeader(name);
        } catch (e) { return null; }
    };

    Response.prototype.getAllResponseHeaders = function getAllResponseHeaders() {
        return this.transport.getAllResponseHeaders();
    };

    var toQueryString = function toQueryString(parameters) {
        var key, query = '';

        if (typeof parameters === 'string') {
            return parameters;
        }

        for (key in parameters) {
            query += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]);
        }

        return query.substr(1);
    };

    var Request = function Request(url, options) {
        this.url = url;
        this.options = EzWebExt.merge({
            method:       'POST',
            asynchronous: true,
            responseType: null,
            contentType:  null,
            encoding:     null,
            postBody:     null
        }, options);

        if (this.options.onSuccess != null && typeof this.options.onSuccess !== 'function') {
            throw new TypeError('Invalid onSuccess callback');
        }
        if (this.options.onFailure != null && typeof this.options.onFailure !== 'function') {
            throw new TypeError('Invalid onFailure callback');
        }
        this.method = this.options.method.toUpperCase();

        if (this.options.parameters != null && (typeof this.options.parameters === 'string' || typeof this.options.parameters === 'object')) {
            if (['PUT', 'POST'].indexOf(this.method) !== -1 && this.options.postBody == null) {
                this.postBody = toQueryString(this.options.parameters);
                if (this.options.contentType == null) {
                    this.options.contentType = 'application/x-www-form-urlencoded';
                }
                if (this.options.encoding == null) {
                    this.options.encoding = 'UTF-8';
                }
            } else if (this.method === 'GET') {
                if (this.url.indexOf('?') !== -1) {
                    this.url += '&' + toQueryString(this.options.parameters);
                }  else {
                    this.url += '?' + toQueryString(this.options.parameters);
                }
            }
        }

        this.transport = new XMLHttpRequest();
        this.transport.open(this.options.method, this.url, this.options.asynchronous);
        if (this.options.responseType) {
            this.transport.responseType = this.options.responseType;
        }
        this.transport.addEventListener('readystatechange', onReadyStateChange.bind(this), true);
        setRequestHeaders.call(this);
        this.transport.send(this.options.postBody);
    };

    var io = {};

    io.buildProxyURL = function buildProxyURL(url, options) {
        var final_url, protocolEnd, link, forceProxy, hostStart, pathStart, protocol,
            host, rest;

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

        forceProxy = !!options.forceProxy;

        if (url.length > 4 && url.indexOf('www.') === 0) {
            url = 'http://' + url;
        }

        protocol = Wirecloud.location.protocol;
        host = Wirecloud.location.host;

        protocolEnd = url.indexOf('://');
        if (protocolEnd !== -1) {
            hostStart = protocolEnd + 3;
            pathStart = url.indexOf('/', hostStart);
            if (pathStart === -1) {
                pathStart = url.length;
            }

            protocol = url.substr(0, protocolEnd);
            host = url.substr(hostStart, pathStart - hostStart);
            rest = url.substring(pathStart);
            final_url = url;
        } else {
            if (url.charAt(0) === '/') {
                rest = url;
            } else {
                rest = '/' + url;
            }

            if (!forceProxy) {
                final_url = Wirecloud.location.domain + rest;
            }
        }

        if (forceProxy || (options.supportsAccessControl !== true && (protocol !== Wirecloud.location.protocol || host !== Wirecloud.location.host))) {
            final_url = Wirecloud.location.domain +
                Wirecloud.URLs.PROXY.evaluate({protocol: protocol, domain: host, path: rest});
        }

        return final_url;
    };

    io.makeRequest = function makeRequest(url, options) {
        var handlerRegExp, key;

        if (options != null && options.context != null) {
            handlerRegExp = new RegExp(/^on(?:Create|Complete|Exception|Failure|Interactive|Loaded|Loading|Success|Uninitialized|\d{3})$/);
            for (key in options) {
                if (handlerRegExp.test(key) && typeof options[key] === 'function') {
                    options[key] = options[key].bind(options.context);
                }
            }
        }

        return new Request(Wirecloud.io.buildProxyURL(url, options), options);
    };

    Wirecloud.io = io;

})();
<commit_msg>Add responseXML to the list of attributes of a response<commit_after>/*
 *     (C) Copyright 2012-2013 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform 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.
 *
 *     Wirecloud 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 Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global EzWebExt, Wirecloud*/

Wirecloud.location = {
    'domain': document.location.protocol + '//' + document.location.host,
    'protocol': document.location.protocol.substr(0, document.location.protocol.length - 1),
    'host': document.location.host
};

(function () {

    "use strict";

    var setRequestHeaders = function setRequestHeaders() {
        var headers, name;

        headers = EzWebExt.merge({
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
        }, this.options.requestHeaders);

        if (!('Content-Type' in headers) && this.options.contentType != null) {
            headers['Content-Type'] = this.options.contentType;
            if (this.options.encoding != null) {
                headers['Content-Type'] += '; charset=' + this.options.encoding;
            }
        }

        for (name in headers) {
            this.transport.setRequestHeader(name, headers[name]);
        }
    };

    var onReadyStateChange = function onReadyStateChange() {
        if (this.transport.readyState == 4) {

            var response = new Response(this);

            try {
                if (('on' + response.status) in this.options) {
                    this.options['on' + response.status](response);
                } else if (this.options.onSuccess && (response.status >= 200 && response.status < 300)) {
                    this.options.onSuccess(response);
                } else if (this.options.onFailure) {
                    this.options.onFailure(response);
                }
            } catch (e) {
            }

            if (this.options.onComplete) {
                try {
                    this.options.onComplete();
                } catch (e) {}
            }
        }
    };

    var Response = function Response(request) {
        Object.defineProperties(this, {
            'request': {value: request},
            'transport': {value: request.transport},
            'status': {value: request.transport.status},
            'statusText': {value: request.transport.statusText},
            'response': {value: request.transport.response},
            'responseXML': {value: request.transport.responseXML}
        });

        if (request.options.responseType == null || request.options.responseType === '') {
            Object.defineProperty(this, 'responseText', {value: request.transport.responseText});
        }
    };

    Response.prototype.getHeader = function getHeader(name) {
        try {
            return this.transport.getResponseHeader(name);
        } catch (e) { return null; }
    };

    Response.prototype.getAllResponseHeaders = function getAllResponseHeaders() {
        return this.transport.getAllResponseHeaders();
    };

    var toQueryString = function toQueryString(parameters) {
        var key, query = '';

        if (typeof parameters === 'string') {
            return parameters;
        }

        for (key in parameters) {
            query += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]);
        }

        return query.substr(1);
    };

    var Request = function Request(url, options) {
        this.url = url;
        this.options = EzWebExt.merge({
            method:       'POST',
            asynchronous: true,
            responseType: null,
            contentType:  null,
            encoding:     null,
            postBody:     null
        }, options);

        if (this.options.onSuccess != null && typeof this.options.onSuccess !== 'function') {
            throw new TypeError('Invalid onSuccess callback');
        }
        if (this.options.onFailure != null && typeof this.options.onFailure !== 'function') {
            throw new TypeError('Invalid onFailure callback');
        }
        this.method = this.options.method.toUpperCase();

        if (this.options.parameters != null && (typeof this.options.parameters === 'string' || typeof this.options.parameters === 'object')) {
            if (['PUT', 'POST'].indexOf(this.method) !== -1 && this.options.postBody == null) {
                this.postBody = toQueryString(this.options.parameters);
                if (this.options.contentType == null) {
                    this.options.contentType = 'application/x-www-form-urlencoded';
                }
                if (this.options.encoding == null) {
                    this.options.encoding = 'UTF-8';
                }
            } else if (this.method === 'GET') {
                if (this.url.indexOf('?') !== -1) {
                    this.url += '&' + toQueryString(this.options.parameters);
                }  else {
                    this.url += '?' + toQueryString(this.options.parameters);
                }
            }
        }

        this.transport = new XMLHttpRequest();
        this.transport.open(this.options.method, this.url, this.options.asynchronous);
        if (this.options.responseType) {
            this.transport.responseType = this.options.responseType;
        }
        this.transport.addEventListener('readystatechange', onReadyStateChange.bind(this), true);
        setRequestHeaders.call(this);
        this.transport.send(this.options.postBody);
    };

    var io = {};

    io.buildProxyURL = function buildProxyURL(url, options) {
        var final_url, protocolEnd, link, forceProxy, hostStart, pathStart, protocol,
            host, rest;

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

        forceProxy = !!options.forceProxy;

        if (url.length > 4 && url.indexOf('www.') === 0) {
            url = 'http://' + url;
        }

        protocol = Wirecloud.location.protocol;
        host = Wirecloud.location.host;

        protocolEnd = url.indexOf('://');
        if (protocolEnd !== -1) {
            hostStart = protocolEnd + 3;
            pathStart = url.indexOf('/', hostStart);
            if (pathStart === -1) {
                pathStart = url.length;
            }

            protocol = url.substr(0, protocolEnd);
            host = url.substr(hostStart, pathStart - hostStart);
            rest = url.substring(pathStart);
            final_url = url;
        } else {
            if (url.charAt(0) === '/') {
                rest = url;
            } else {
                rest = '/' + url;
            }

            if (!forceProxy) {
                final_url = Wirecloud.location.domain + rest;
            }
        }

        if (forceProxy || (options.supportsAccessControl !== true && (protocol !== Wirecloud.location.protocol || host !== Wirecloud.location.host))) {
            final_url = Wirecloud.location.domain +
                Wirecloud.URLs.PROXY.evaluate({protocol: protocol, domain: host, path: rest});
        }

        return final_url;
    };

    io.makeRequest = function makeRequest(url, options) {
        var handlerRegExp, key;

        if (options != null && options.context != null) {
            handlerRegExp = new RegExp(/^on(?:Create|Complete|Exception|Failure|Interactive|Loaded|Loading|Success|Uninitialized|\d{3})$/);
            for (key in options) {
                if (handlerRegExp.test(key) && typeof options[key] === 'function') {
                    options[key] = options[key].bind(options.context);
                }
            }
        }

        return new Request(Wirecloud.io.buildProxyURL(url, options), options);
    };

    Wirecloud.io = io;

})();
<|endoftext|>


<commit_before>ZBase.registerView((function() {
  var Overview = {};
  var Editor = {};
  var path_parts;

  Editor.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Editor.validateAndFetchDocument();

    Editor.doc_sync = new DocSync(function() {
      return "content=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane fn-codeeditor").getValue()) +
      "&name=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane input[name='doc_name']").value)
      },
      "/analytics/api/v1/sql_queries/" + Editor.doc_id,
      document.querySelector(".zbase_sql_editor_pane .zbase_sql_editor_infobar")
    );
    Editor.source_handler = new EventSourceHandler();
  };

  Editor.validateAndFetchDocument = function() {
    Editor.doc_id = path_parts[3];
    // invalid docid
    if (!/^[A-Za-z0-9]+$/.test(Editor.doc_id)) {
      //TODO redirect and display message
      alert("invalid docid");
      return;
    }

    // fetch document
    ZBase.util.httpGet("/analytics/api/v1/documents/sql_queries/" + Editor.doc_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        Editor.handleNameEditing(doc.name);
        Editor.setQueryContent(doc.sql_query);
        Editor.observeQueryExecution();

        document.querySelector(".zbase_sql_editor_pane .zbase_loader")
          .classList.add("hidden");
      }
    });
  };

  Editor.setQueryContent = function(query) {
    document.querySelector(".zbase_sql_editor_pane fn-codeeditor").setValue(query);
    if (query != "-- SELECT ... FROM ...;" && query.length > 0) {
      Editor.executeQuery(query);
    }
  };

  Editor.observeQueryExecution = function() {
    var editor = document.querySelector(".zbase_sql_editor_pane fn-codeeditor");
    var exec_btn = document.querySelector(
      ".zbase_sql_editor_pane button[data-action='execute-query']");

    /*document.querySelector("fn-tooltip[data-target='query_exec_btn']").init(
      exec_btn);*/

    exec_btn.addEventListener('click', function() {
      Editor.executeQuery(editor.getValue());
    }, false);

    var cmd_pressed = false;
    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = true;
      }
    }, false);

    editor.addEventListener('keyup', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = false;
      }
    }, false);

    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 13 && cmd_pressed) {
        e.preventDefault();
        Editor.executeQuery(editor.getValue());
      }
    }, false);

    var value = editor.getValue();
    editor.addEventListener('keyup', function() {
      var new_value = editor.getValue();
      if (value == new_value) {return;}
      value = new_value;
      /*Editor.doc_sync.cur_version++;
      Editor.doc_sync.documentChanged("content_changed");*/
    }, false);

  };

  Editor.executeQuery = function(query) {
    var id = "query";

    Editor.source_handler.close(id);
    var source = Editor.source_handler.get(
      id,
      "/analytics/api/v1/sql_stream?query=" + encodeURIComponent(query));

    source.addEventListener('result', function(e) {
      var end = (new Date()).getTime();
      Editor.source_handler.close(id);
      var data = JSON.parse(e.data);
      //document.querySelector(".message[name='error']").classList.add("hidden");
      Editor.renderResults(data.results);
    });

    source.addEventListener('error', function(e) {
      Editorr.source_handler.close(id);
      queryStatus.stop(true);
      result_pane.style.display = "none";
      document.getElementById('exec_info').classList.add("hidden");
      try {
        document.getElementById('error_text').innerHTML = JSON.parse(e.data).error;
      } catch (e) {
        document.getElementById('error_text').innerHTML = e.data;
      }
      Analytics.displayMessage('error');
    });

  };

  Editor.renderResultTable = function(rows, columns) {
    var table = document.createElement("table");
    table.className = 'zbase_table';

    table.innerHTML = "

";

    columns.forEach(function(column) {
      table.innerHTML += "" + column + "	";
    });

    table.innerHTML += "

";

    rows.forEach(function(row) {
      table.innerHTML += "
";
      row.forEach(function(cell) {
        table.innerHTML += "" + cell, "	";
      });
      table.innerHTML += "
";
    });

    table.innerHTML += "</tbody";
    return table;
  };

  Editor.renderResultChart = function(svg) {
    var elem = document.createElement("div");
    elem.className = "result_chart result_content";
    elem.innerHTML = svg;
    return elem;
  };

  Editor.renderResultBar = function(index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-index', index);
    bar.setAttribute('data-active', 'active');
    bar.innerHTML =
      "Result " + (index + 1) + "";
    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
          return;
        }
        this.setAttribute('data-active', 'active');
      }, false);
    }
    return bar;
  };

  Editor.renderResults = function(results) {
    var result_pane = document.querySelector(
      ".zbase_sql_editor_pane .zbase_sql_editor_result_pane");

    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      result_pane.appendChild(Editor.renderResultBar(i, results.length > 1));
      var elem;
      switch (results[i].type) {
        case "chart":
          elem = Editor.renderResultChart(results[i].svg);
          break;
        case "table":
          elem = Editor.renderResultTable(results[i].rows, results[i].columns)
          break;
      }
      result_pane.appendChild(elem);
    }
  };

  Editor.handleNameEditing = function(doc_name) {
    var name_elem = document.querySelector(".zbase_sql_editor_pane .pagetitle");
    name_elem.innerHTML = doc_name;

    name_elem.addEventListener("click", function() {
      console.log("open update name modal");
    }, false);
  };

  Overview.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_overview_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Overview.load();
    Overview.handleNewQueryButton();
  };

  Overview.handleNewQueryButton = function() {
    document.querySelector(
      ".zbase_sql_editor button[data-action='new-query']")
      .addEventListener("click", function() {
        ZBase.util.httpPost("/analytics/api/v1/documents/sql_queries", "", function(r) {
          var response = JSON.parse(r.response);
          window.location.href = "/a/sql/" + response.uuid;
        });
      });
  };

  Overview.renderTable = function(documents) {
    var tbody = document.querySelector(".zbase_sql_editor_overview tbody");
    documents.forEach(function(doc) {
      var url = "/a/sql/" + doc.uuid;
      var tr = document.createElement("tr");
      tr.innerHTML = "" + doc.name + "	" +
        "" + doc.type + "	—	";
      tbody.appendChild(tr);

      tr.addEventListener("click", function() {
        window.location.href = url;
      });
    });

    document.querySelector(".zbase_sql_editor_overview .zbase_loader")
      .classList.add("hidden");
  };

  Overview.load = function() {
    ZBase.util.httpGet("/analytics/api/v1/documents", function(r) {
      if (r.status == 200) {
        var documents = JSON.parse(r.response).documents;
        Overview.renderTable(documents);
      } else {
        //TODO render error message
      }
    });
  };

  var render = function(path) {
    path_parts = path.split("/");
    var view;
    // render view
    if (path_parts.length == 4 && path_parts[3].length > 0) {
      Editor.render();
    } else {
      Overview.render();
    }
  };

  return {
    name: "sql_editor",

    loadView: function(params) {
      render(params.path);
    },
    unloadView: function() {
      if (Editor.source_handler) {
        Editor.source_handler.closeAll();
      }
    },
    handleNavigationChange: function(url){
      render(url);
    }
  };

})());
<commit_msg>render result table<commit_after>ZBase.registerView((function() {
  var Overview = {};
  var Editor = {};
  var path_parts;

  Editor.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Editor.validateAndFetchDocument();

    Editor.doc_sync = new DocSync(function() {
      return "content=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane fn-codeeditor").getValue()) +
      "&name=" + encodeURIComponent(document.querySelector(".zbase_sql_editor_pane input[name='doc_name']").value)
      },
      "/analytics/api/v1/sql_queries/" + Editor.doc_id,
      document.querySelector(".zbase_sql_editor_pane .zbase_sql_editor_infobar")
    );
    Editor.source_handler = new EventSourceHandler();
  };

  Editor.validateAndFetchDocument = function() {
    Editor.doc_id = path_parts[3];
    // invalid docid
    if (!/^[A-Za-z0-9]+$/.test(Editor.doc_id)) {
      //TODO redirect and display message
      alert("invalid docid");
      return;
    }

    // fetch document
    ZBase.util.httpGet("/analytics/api/v1/documents/sql_queries/" + Editor.doc_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        Editor.handleNameEditing(doc.name);
        Editor.setQueryContent(doc.sql_query);
        Editor.observeQueryExecution();

        document.querySelector(".zbase_sql_editor_pane .zbase_loader")
          .classList.add("hidden");
      }
    });
  };

  Editor.setQueryContent = function(query) {
    document.querySelector(".zbase_sql_editor_pane fn-codeeditor").setValue(query);
    if (query != "-- SELECT ... FROM ...;" && query.length > 0) {
      Editor.executeQuery(query);
    }
  };

  Editor.observeQueryExecution = function() {
    var editor = document.querySelector(".zbase_sql_editor_pane fn-codeeditor");
    var exec_btn = document.querySelector(
      ".zbase_sql_editor_pane button[data-action='execute-query']");

    /*document.querySelector("fn-tooltip[data-target='query_exec_btn']").init(
      exec_btn);*/

    exec_btn.addEventListener('click', function() {
      Editor.executeQuery(editor.getValue());
    }, false);

    var cmd_pressed = false;
    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = true;
      }
    }, false);

    editor.addEventListener('keyup', function(e) {
      if (e.keyCode == 17 || e.keyCode == 91) {
        cmd_pressed = false;
      }
    }, false);

    editor.addEventListener('keydown', function(e) {
      if (e.keyCode == 13 && cmd_pressed) {
        e.preventDefault();
        Editor.executeQuery(editor.getValue());
      }
    }, false);

    var value = editor.getValue();
    editor.addEventListener('keyup', function() {
      var new_value = editor.getValue();
      if (value == new_value) {return;}
      value = new_value;
      /*Editor.doc_sync.cur_version++;
      Editor.doc_sync.documentChanged("content_changed");*/
    }, false);

  };

  Editor.executeQuery = function(query) {
    var id = "query";

    Editor.source_handler.close(id);
    var source = Editor.source_handler.get(
      id,
      "/analytics/api/v1/sql_stream?query=" + encodeURIComponent(query));

    source.addEventListener('result', function(e) {
      var end = (new Date()).getTime();
      Editor.source_handler.close(id);
      var data = JSON.parse(e.data);
      //document.querySelector(".message[name='error']").classList.add("hidden");
      Editor.renderResults(data.results);
    });

    source.addEventListener('error', function(e) {
      Editorr.source_handler.close(id);
      queryStatus.stop(true);
      result_pane.style.display = "none";
      document.getElementById('exec_info').classList.add("hidden");
      try {
        document.getElementById('error_text').innerHTML = JSON.parse(e.data).error;
      } catch (e) {
        document.getElementById('error_text').innerHTML = e.data;
      }
      Analytics.displayMessage('error');
    });

  };

  Editor.renderResultTable = function(rows, columns) {
    var table = document.createElement("table");
    table.className = 'zbase_table';

    innerHTML = "

";
    columns.forEach(function(column) {
      innerHTML += "" + column + "	";
    });

    innerHTML += "

";

    rows.forEach(function(row) {
      innerHTML += "
";
      row.forEach(function(cell) {
        innerHTML += "" + cell + "	";
      });
      innerHTML += "
";
    });

    innerHTML += "
";
    table.innerHTML = innerHTML;
    console.log(innerHTML);
    return table;
  };

  Editor.renderResultChart = function(svg) {
    var elem = document.createElement("div");
    elem.className = "result_chart result_content";
    elem.innerHTML = svg;
    return elem;
  };

  Editor.renderResultBar = function(index, multiple_results) {
    var bar = document.createElement("div");
    bar.className = "zbase_result_pane_bar";
    bar.setAttribute('data-index', index);
    bar.setAttribute('data-active', 'active');
    bar.innerHTML =
      "Result " + (index + 1) + "";
    if (multiple_results) {
      bar.className += " clickable";
      bar.addEventListener('click', function() {
        if (this.hasAttribute('data-active')) {
          this.removeAttribute('data-active');
          return;
        }
        this.setAttribute('data-active', 'active');
      }, false);
    }
    return bar;
  };

  Editor.renderResults = function(results) {
    var result_pane = document.querySelector(
      ".zbase_sql_editor_pane .zbase_sql_editor_result_pane");

    result_pane.innerHTML = "";
    for (var i = 0; i < results.length; i++) {
      result_pane.appendChild(Editor.renderResultBar(i, results.length > 1));
      var elem;
      switch (results[i].type) {
        case "chart":
          elem = Editor.renderResultChart(results[i].svg);
          break;
        case "table":
          elem = Editor.renderResultTable(results[i].rows, results[i].columns)
          break;
      }
      result_pane.appendChild(elem);
    }
  };

  Editor.handleNameEditing = function(doc_name) {
    var name_elem = document.querySelector(".zbase_sql_editor_pane .pagetitle");
    name_elem.innerHTML = doc_name;

    name_elem.addEventListener("click", function() {
      console.log("open update name modal");
    }, false);
  };

  Overview.render = function() {
    var viewport = document.getElementById("zbase_viewport");
    var page = ZBase.getTemplate(
      "sql_editor", "zbase_sql_editor_overview_main_tpl");
    ZBase.util.install_link_handlers(page);

    viewport.innerHTML = "";
    viewport.appendChild(page);

    Overview.load();
    Overview.handleNewQueryButton();
  };

  Overview.handleNewQueryButton = function() {
    document.querySelector(
      ".zbase_sql_editor button[data-action='new-query']")
      .addEventListener("click", function() {
        ZBase.util.httpPost("/analytics/api/v1/documents/sql_queries", "", function(r) {
          var response = JSON.parse(r.response);
          window.location.href = "/a/sql/" + response.uuid;
        });
      });
  };

  Overview.renderTable = function(documents) {
    var tbody = document.querySelector(".zbase_sql_editor_overview tbody");
    documents.forEach(function(doc) {
      var url = "/a/sql/" + doc.uuid;
      var tr = document.createElement("tr");
      tr.innerHTML = "" + doc.name + "	" +
        "" + doc.type + "	—	";
      tbody.appendChild(tr);

      tr.addEventListener("click", function() {
        window.location.href = url;
      });
    });

    document.querySelector(".zbase_sql_editor_overview .zbase_loader")
      .classList.add("hidden");
  };

  Overview.load = function() {
    ZBase.util.httpGet("/analytics/api/v1/documents", function(r) {
      if (r.status == 200) {
        var documents = JSON.parse(r.response).documents;
        Overview.renderTable(documents);
      } else {
        //TODO render error message
      }
    });
  };

  var render = function(path) {
    path_parts = path.split("/");
    var view;
    // render view
    if (path_parts.length == 4 && path_parts[3].length > 0) {
      Editor.render();
    } else {
      Overview.render();
    }
  };

  return {
    name: "sql_editor",

    loadView: function(params) {
      render(params.path);
    },
    unloadView: function() {
      if (Editor.source_handler) {
        Editor.source_handler.closeAll();
      }
    },
    handleNavigationChange: function(url){
      render(url);
    }
  };

})());
<|endoftext|>


<commit_before>define(
// require.js dependency injection
[
  './module'
],

// require.js module scope
function(module) {
  'use strict';

  module.controller(

    // controller name
    'MainCtrl',

    // dependencies injection
    ['ProgressConfig', 'MenuConfig', '$scope',

  // controller definition
  function(progressConfig, menu, $scope) {

    $scope.appLoaded = 'ok';

    //--- @begin: loading progressbar config
    progressConfig.eventListeners();
    progressConfig.color('#428bca');
    //--- @end: loading progressbar config

    //--- @begin: menu items
    menu.addMenuItem('Home', '');
    menu.addMenuItem('Boorkmars', 'bookmarks');
    menu.addMenuItem('About', 'about');
    //--- @end: menu items

  }]);

});<commit_msg>angular-ee swt : label menu review<commit_after>define(
// require.js dependency injection
[
  './module'
],

// require.js module scope
function(module) {
  'use strict';

  module.controller(

    // controller name
    'MainCtrl',

    // dependencies injection
    ['ProgressConfig', 'MenuConfig', '$scope',

  // controller definition
  function(progressConfig, menu, $scope) {

    $scope.appLoaded = 'ok';

    //--- @begin: loading progressbar config
    progressConfig.eventListeners();
    progressConfig.color('#428bca');
    //--- @end: loading progressbar config

    //--- @begin: menu items
    menu.addMenuItem('Home', '');
    menu.addMenuItem('Boorkmarks', 'bookmarks');
    menu.addMenuItem('About', 'about');
    //--- @end: menu items

  }]);

});<|endoftext|>


<commit_before>// jshint esversion: 6
'use strict';

describe('playList', function () {

    //load the module
    beforeEach(module('playList'));

    // Test the controller
    describe('PlayListControllerTest', function () {
        var $httpBackend, ctrl;

        var plays = [
            {
                "date": "01/09/15",
                "game": "7wonders",
                "id": 0,
                "players": [
                    {
                        "name": "lolo",
                        "score": 28
                    },
                    {
                        "name": "clemence",
                        "score": 46
                    },
                ]
            },
            {
                "date": "02/09/15",
                "game": "7wonders",
                "id": 1,
                "players": [
                    {
                        "name": "lolo",
                        "score": 39
                    },
                    {
                        "name": "clemence",
                        "score": 39
                    }
                ]
            }
        ];

        beforeEach(inject(function ($componentController, _$httpBackend_) {
            $httpBackend = _$httpBackend_;
            // program response
            $httpBackend.expectGET('api/v1/plays')
                .respond(plays);
            //create controller here
            ctrl = $componentController('playListComponent');
        }));
        // Test
        it('should create a `plays` property with 2 plays fetched with `$http`', function () {
            jasmine.addCustomEqualityTester(angular.equals);
            expect(ctrl.plays).toEqual([]);
            $httpBackend.flush();
            expect(ctrl.plays.length).toBe(2);
            expect(ctrl.plays).toEqual(plays);
        });
        // Test
        it('should set a default value for the `orderProp` property', function () {
            expect(ctrl.orderProp).toBe('date');
        });

    });

});
<commit_msg>Fix javascript tests<commit_after>// jshint esversion: 6
'use strict';

describe('playList', function () {

    //load the module
    beforeEach(module('playList'));

    // Test the controller
    describe('PlayListControllerTest', function () {
        var $httpBackend, ctrl;

        var plays = [
            {
                "date": "01/09/15",
                "game": "7wonders",
                "id": 0,
                "players": [
                    {
                        "name": "lolo",
                        "score": 28
                    },
                    {
                        "name": "clemence",
                        "score": 46
                    },
                ]
            },
            {
                "date": "02/09/15",
                "game": "7wonders",
                "id": 1,
                "players": [
                    {
                        "name": "lolo",
                        "score": 39
                    },
                    {
                        "name": "clemence",
                        "score": 39
                    }
                ]
            }
        ];

        beforeEach(inject(function ($componentController, _$httpBackend_) {
            $httpBackend = _$httpBackend_;
            // program response
            $httpBackend.expectGET('api/v1/plays')
                .respond(plays);
            //create controller here
            ctrl = $componentController('playListComponent');
        }));
        // Test
        it('should create a `plays` property with 2 plays fetched with `$http`', function () {
            jasmine.addCustomEqualityTester(angular.equals);
            expect(ctrl.plays).toEqual([]);
            $httpBackend.flush();
            expect(ctrl.plays.length).toBe(2);
            expect(ctrl.plays).toEqual(plays);
        });
        // Test
        it('should set a default value for the `orderProp` property', function () {
            expect(ctrl.orderProp).toBe('-id');
        });

    });

});
<|endoftext|>


<commit_before>/* Compose - Attachments */

Mailpile.Composer.Attachments.UploaderImagePreview = function(file, mid) {

  var item = $('

').prependTo($('#compose-attachments-files-' + mid));
  var image = $(new Image()).appendTo(item);

  // Create an instance of the mOxie Image object. This
  // utility object provides several means of reading in
  // and loading image data from various sources.
  // Wiki: https://github.com/moxiecode/moxie/wiki/Image
  var preloader = new mOxie.Image();

  // Define the onload BEFORE you execute the load()
  // command as load() does not execute async.
  preloader.onload = function() {

      // This will scale the image (in memory) before it
      // tries to render it. This just reduces the amount
      // of Base64 data that needs to be rendered.
      preloader.downsize(100, 100);

      // Now that the image is preloaded, grab the Base64
      // encoded data URL. This will show the image
      // without making an Network request using the
      // client-side file binary.
      image.prop("src", preloader.getAsDataURL());
  };

  // Calling the .getSource() on the file will return an
  // instance of mOxie.File, which is a unified file
  // wrapper that can be used across the various runtime
  // Wiki: https://github.com/moxiecode/plupload/wiki/File
  preloader.load(file.getSource());
};

Mailpile.Composer.Attachments.Uploader = function(settings) {

  var uploader = new plupload.Uploader({
  	runtimes : 'html5',
  	browse_button : settings.browse_button, // you can pass in id...
  	container: settings.container, // ... or DOM Element itself
    drop_element: settings.container,
  	url : '/api/0/message/attach/',
    multipart : true,
    multipart_params : {'mid': settings.mid},
    file_data_name : 'file-data',
  	filters : {
  		max_file_size : '50mb',
  		mime_types: [
  			{title : "Audio files", extensions : "mp3,aac,flac,wav,ogg,aiff,midi"},
  			{title : "Document files", extensions : "pdf,doc,docx,xls,txt,rtf,ods"},
  			{title : "Image files", extensions : "jpg,jpeg,gif,png,svg,psd,tiff,bmp,ai,sketch"},
  			{title : "Image files", extensions : "mp2,mp4,mov,avi,mkv"},
  			{title : "Zip files", extensions : "zip,rar"},
  			{title : "Crypto files", extensions : "asc,pub,key"}
  		]
  	},
    resize: {
      width: '3600',
      height: '3600',
      crop: true,
      quaility: 100
    },
    views: {
      list: true,
      thumbs: true,
      active: 'thumbs'
    },
  	init: {
      PostInit: function() {
        $('#compose-attachments-' + settings.mid).find('.compose-attachment-pick').removeClass('hide');
        $('#compose-attachments-' + settings.mid).find('.attachment-browswer-unsupported').addClass('hide');
        uploader.refresh();
      },
      FilesAdded: function(up, files) {
        var start_upload = true;

        // Upload files
      	plupload.each(files, function(file) {

          // Show Warning for 50 mb or larger
          if (file.size > 52428800) {
            start_upload = false;
            alert(file.name + ' {{_("is")}} ' + plupload.formatSize(file.size) + '. {{_("Some people cannot receive attachments larger than 50 Megabytes.")}}');
          } else {
           // Show image preview
            if (_.indexOf(['image/jpg', 'image/jpeg', 'image/gif', 'image/png'], file.type) > -1) {
              Mailpile.Composer.Attachments.UploaderImagePreview(file, settings.mid);
            } else {
              var attachment_html = '

' + file.name + '
 ' + plupload.formatSize(file.size) + '
';
          		$('#compose-attachments-files-' + settings.mid).append(attachment_html);
            }
          }
      	});

        if (start_upload) {
          uploader.start();
        }
      },
      UploadProgress: function(up, file) {
      	$('#' + file.id).find('b').html('' + file.percent + '%');
      },
      Error: function(up, err) {
        Mailpile.notification({status: 'error', message: "Oops, could not upload attachment because: " + err.message });
        $('#' + err.file.id).find('b').html('Failed ' + err.code);
        uploader.refresh();
      }
    }
  });

  return uploader.init();
};<commit_msg>Added attachment filetypes .md and .html, fixes #976<commit_after>/* Compose - Attachments */

Mailpile.Composer.Attachments.UploaderImagePreview = function(file, mid) {

  var item = $('

').prependTo($('#compose-attachments-files-' + mid));
  var image = $(new Image()).appendTo(item);

  // Create an instance of the mOxie Image object. This
  // utility object provides several means of reading in
  // and loading image data from various sources.
  // Wiki: https://github.com/moxiecode/moxie/wiki/Image
  var preloader = new mOxie.Image();

  // Define the onload BEFORE you execute the load()
  // command as load() does not execute async.
  preloader.onload = function() {

      // This will scale the image (in memory) before it
      // tries to render it. This just reduces the amount
      // of Base64 data that needs to be rendered.
      preloader.downsize(100, 100);

      // Now that the image is preloaded, grab the Base64
      // encoded data URL. This will show the image
      // without making an Network request using the
      // client-side file binary.
      image.prop("src", preloader.getAsDataURL());
  };

  // Calling the .getSource() on the file will return an
  // instance of mOxie.File, which is a unified file
  // wrapper that can be used across the various runtime
  // Wiki: https://github.com/moxiecode/plupload/wiki/File
  preloader.load(file.getSource());
};

Mailpile.Composer.Attachments.Uploader = function(settings) {

  var uploader = new plupload.Uploader({
  	runtimes : 'html5',
  	browse_button : settings.browse_button, // you can pass in id...
  	container: settings.container, // ... or DOM Element itself
    drop_element: settings.container,
  	url : '/api/0/message/attach/',
    multipart : true,
    multipart_params : {'mid': settings.mid},
    file_data_name : 'file-data',
  	filters : {
  		max_file_size : '50mb',
  		mime_types: [
  			{title : "Audio files", extensions : "mp3,aac,flac,wav,ogg,aiff,midi"},
  			{title : "Document files", extensions : "pdf,doc,docx,xls,txt,rtf,ods,html,md"},
  			{title : "Image files", extensions : "jpg,jpeg,gif,png,svg,psd,tiff,bmp,ai,sketch"},
  			{title : "Image files", extensions : "mp2,mp4,mov,avi,mkv"},
  			{title : "Zip files", extensions : "zip,rar"},
  			{title : "Crypto files", extensions : "asc,pub,key"}
  		]
  	},
    resize: {
      width: '3600',
      height: '3600',
      crop: true,
      quaility: 100
    },
    views: {
      list: true,
      thumbs: true,
      active: 'thumbs'
    },
  	init: {
      PostInit: function() {
        $('#compose-attachments-' + settings.mid).find('.compose-attachment-pick').removeClass('hide');
        $('#compose-attachments-' + settings.mid).find('.attachment-browswer-unsupported').addClass('hide');
        uploader.refresh();
      },
      FilesAdded: function(up, files) {
        var start_upload = true;

        // Upload files
      	plupload.each(files, function(file) {

          // Show Warning for 50 mb or larger
          if (file.size > 52428800) {
            start_upload = false;
            alert(file.name + ' {{_("is")}} ' + plupload.formatSize(file.size) + '. {{_("Some people cannot receive attachments larger than 50 Megabytes.")}}');
          } else {
           // Show image preview
            if (_.indexOf(['image/jpg', 'image/jpeg', 'image/gif', 'image/png'], file.type) > -1) {
              Mailpile.Composer.Attachments.UploaderImagePreview(file, settings.mid);
            } else {
              var attachment_html = '

' + file.name + '
 ' + plupload.formatSize(file.size) + '
';
          		$('#compose-attachments-files-' + settings.mid).append(attachment_html);
            }
          }
      	});

        if (start_upload) {
          uploader.start();
        }
      },
      UploadProgress: function(up, file) {
      	$('#' + file.id).find('b').html('' + file.percent + '%');
      },
      Error: function(up, err) {
        Mailpile.notification({status: 'error', message: '{{_("Could not upload attachment because")}}: ' + err.message });
        $('#' + err.file.id).find('b').html('Failed ' + err.code);
        uploader.refresh();
      }
    }
  });

  return uploader.init();
};<|endoftext|>


<commit_before>var SearchResult;

(function ($) {
  SearchResult = Class.extend({
    isInitialized: false,

    $resultListEl: $('.searchResults'),
    $filtersEl: $('#searchFilters'),
    $filterHeaderEl: $('.header-filter'),
    $searchHeaderEl: $('.search-results-header'),
    $searchCounterEl: $('.results-number'),
    $searchBarForm: $('#searchControlBarForm'),
    $searchBarInput: $('#controlBarSearch'),
    $loadingEl: $('#search-loading'),
    $orderByEl: $('#sortOrder'),
    $searchFeedBtnEl: $('.search-feed'),
    $searchAlertOpenModalBtnEl: $('.open-search-alert-modal'),
    $searchAlertCloseModalBtnEl: $('.btn-cancel-savedsearch'),
    $searchAlertSaveBtnEl: $('#btn-save-savedsearch'),
    $searchAlertModalEl: $('#search-alert-modal'),
    resultPerPageElId: '#resultsPerPageDropdown',
    resetFiltersElId: '#clearAllFiltersButton',

    currentSearchParams: {
      "filterJournals": null,
      "filterSubjects": null,
      "filterArticleTypes": null,
      "filterAuthors": null,
      "filterSections": null,
      "filterStartDate": null,
      "filterEndDate": null,
      "resultsPerPage": null,
      "unformattedQuery": null,
      "q": null,
      "sortOrder": null,
      "page": 1
    },
    currentUrlParams: null,
    searchEndpoint: 'search',
    ajaxSearchEndpoint: 'dynamicSearch',
    searchFeedEndpoint: 'search/feed/atom',

    searchFilters: {},
    results: [],
    resultTotalRecords: 0,
    resultsOffset: 0,
    pagination: null,
    filtersParams: [
      "filterJournals",
      "filterSubjects",
      "filterArticleTypes",
      "filterAuthors",
      "filterSections",
      "filterStartDate",
      "filterEndDate"
    ],
    filtersTitles: {
      "journal": "Journal",
      "subject_area": "Subject Area",
      "article_type": "Article Type",
      "author": "Author",
      "section": "Where my keywords appear"
    },

    init: function () {
      var that = this;
      this.loadUrlParams();
      this.bindSearchEvents();
      var currentPage = this.getCurrentPage();
      var itemsPerPage = this.getResultsPerPage();
      this.pagination = new Pagination(currentPage, this.resultTotalRecords, itemsPerPage, function (currentPage) {
        that.currentSearchParams.page = currentPage;
        that.processRequest();
      });
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      if(this.currentSearchParams.q != null) {
        this.processRequest();
      }
      else {
        this.isInitialized = true;
      }
    },
    getCurrentPage: function() {
      if(this.currentSearchParams.page && this.currentSearchParams.page != null) {
        return parseInt(this.currentSearchParams.page);
      }
      else {
        return 1;
      }
    },
    getResultsPerPage: function () {
      if(this.currentSearchParams.resultsPerPage && this.currentSearchParams.resultsPerPage != null) {
        return parseInt(this.currentSearchParams.resultsPerPage);
      }
      else {
        return 15;
      }
    },
    showLoading: function () {
      this.$loadingEl.show();
    },
    hideLoading: function () {
      this.$loadingEl.hide();
    },
    loadUrlParams: function () {
      var that = this;
      var urlVars = this.getJsonFromUrl();
      this.currentSearchParams = _.mapObject(this.currentSearchParams, function (item, key) {
        var urlVar = urlVars[key];
        if(!_.isEmpty(urlVar)) {
          return urlVar;
        }
        else {
          return null;
        }
      });
    },
    createUrlParams: function () {
      var urlParams = '?';
      _.each(this.currentSearchParams, function (item, key) {
        if(item != null) {
          if(_.isArray(item)) {
            _.each(item, function (item) {
              urlParams = urlParams + key + '=' + encodeURIComponent(item) + '&';
            });
          }
          else {
            urlParams = urlParams + key + '=' + encodeURIComponent(item) + '&';
          }
        }
      });
      this.currentUrlParams = urlParams.slice(0, -1).replace('%20', '+');
      this.updatePageUrl();
    },
    updatePageUrl: function () {
      if(this.isInitialized) {
        var title = document.title;
        var href = this.searchEndpoint + this.currentUrlParams;
        window.history.pushState(href, title, href);
        this.$searchFeedBtnEl.prop('href', this.searchFeedEndpoint + this.currentUrlParams);
      }
    },
    bindSearchEvents: function () {
      var that = this;
      this.$searchBarForm.on('submit', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var inputValue = that.$searchBarInput.val();
        that.currentSearchParams.unformattedQuery = null;
        that.currentSearchParams.q = inputValue;
        that.currentSearchParams.page = 1;

        that.processRequest();
      });

      this.$orderByEl.on('change', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.currentSearchParams.sortOrder = $(this).val();
        that.currentSearchParams.page = 1;
        that.processRequest();
      });

      $('body').on('click', '[data-filter-param-name]', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var param = $(this).data('filter-param-name');
        var value = $(this).data('filter-value');

        var currentValue = that.currentSearchParams[param];

        if(_.isArray(currentValue)) {
          var index = _.indexOf(currentValue, value);

          if (index == -1) {
            that.currentSearchParams[param].push(value);
          }
          else {
            that.currentSearchParams[param].splice(index, 1);
          }
        }
        else {
          if(currentValue == value) {
            that.currentSearchParams[param] = [];
          }
          else if(currentValue != null) {
            that.currentSearchParams[param] = [currentValue, value];
          }
          else {
            that.currentSearchParams[param] = [value];
          }
        }

        that.currentSearchParams.page = 1;

        that.processRequest();
      }).on('change', this.resultPerPageElId, function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.currentSearchParams.resultsPerPage = $(this).val();
        that.currentSearchParams.page = 1;
        that.processRequest();
      }).on('click', this.resetFiltersElId, function (e) {
        e.preventDefault();
        e.stopPropagation();

        _.each(that.filtersParams, function (filter) {
          that.currentSearchParams[filter] = null;
        });
        that.processRequest();
      }).on('click', '[data-show-more-items]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        $(this).parent('ul').find('li:gt(4)').fadeIn();
        $(this).hide();
      }).on('click', '[data-show-less-items]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        $(this).parent('ul').find('li:gt(4)').fadeOut();
        $(this).hide();
        $(this).parent('ul').find('[data-show-more-items]').fadeIn();
      });

      this.$searchAlertOpenModalBtnEl.on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.$searchAlertModalEl.foundation('reveal', 'open');

        if(that.$searchAlertModalEl.hasClass('loggedIn')) {
          var textInput = $('#text_name_savedsearch');
          textInput.val(that.currentSearchParams.q);
          textInput.focus();
          textInput[0].selectionStart = textInput[0].selectionEnd = textInput[0].value.length;
        }
      });

      this.$searchAlertCloseModalBtnEl.on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        that.$searchAlertModalEl.foundation('reveal', 'close');
      });

      this.$searchAlertSaveBtnEl.on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.processSearchAlert();
      });
    },

    processSearchAlert: function () {
      var that = this;
      var name = $('#text_name_savedsearch').val();
      var query = {};

      _.mapObject(this.currentSearchParams, function (item, key) {
        if(!_.isEmpty(item)) {
          query[key] = item;
        }
      });
      query = JSON.stringify(query);
      var weekly = $('#cb_weekly_savedsearch').is(':checked');
      var monthly = $('#cb_monthly_savedsearch').is(':checked');

      $.ajax({
        type: 'POST',
        url: 'searchalert/add',
        data: 'name=' + encodeURIComponent(name)
        + "&query=" + encodeURIComponent(query)
        + (weekly ? "&frequency=weekly" : "") + (monthly ? "&frequency=monthly" : ""),
        dataType:'json',
        success: function(response) {
          if (response.error) {
            var errorMessage = response.error;
            $('#span_error_savedsearch').html(errorMessage);
            return;
          }

          that.$searchAlertModalEl.foundation('reveal', 'close');
        },
        error: function(req, textStatus, errorThrown) {
          $('#span_error_savedsearch').html(errorThrown);
          console.log('error: ' + errorThrown);
        }
      });
    },

    processRequest: function () {
      var that = this;
      this.pagination.setCurrentPage(this.getCurrentPage());
      this.showLoading();
      this.createUrlParams();

      if(!this.isInitialized) {
        this.isInitialized = true;
      }

      $.ajax({
        url: this.ajaxSearchEndpoint+this.currentUrlParams,
        method: 'GET',
        jsonp: 'callback',
        dataType: 'json',
        timeout: 20000,
        success: function (response) {
          that.$resultListEl.html('');
          if(response.cannotParseQueryError) {
            that.showParseError();
          }
          else if (response.unknownQueryError) {
            that.showRequestError();
          }
          else {
            that.resultTotalRecords = response.searchResults.numFound;
            if (that.resultTotalRecords > 0) {
              that.results = response.searchResults.docs;
              var currentPage = that.getCurrentPage();
              var itemsPerPage = that.getResultsPerPage();
              that.pagination.setItemsPerPage(itemsPerPage);
              that.pagination.setTotalRecords(that.resultTotalRecords);
              that.pagination.setCurrentPage(currentPage);
              that.resultsOffset = response.searchResults.start;

              that.searchFilters = response.searchFilters;

              that.$searchHeaderEl.show();
              that.$filtersEl.show();

              that.createFilters();
              that.updateCounterText();
              that.createResultList();

              that.hideLoading();
            }
            else {
              that.showNoResults();
            }
          }
        },
        error: function (jqXHR, textStatus) {
          that.showRequestError();
        }
      });

    },
    showRequestError: function () {
      var errorTemplate = _.template($('#searchGeneralErrorTemplate').html());
      this.$resultListEl.append(errorTemplate());
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      this.createFilters();
    },
    showParseError: function () {
      var errorTemplate = _.template($('#searchParseErrorTemplate').html());
      this.$resultListEl.append(errorTemplate());
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      this.createFilters();
    },
    showNoResults: function() {
      var noResultsTemplate = _.template($('#searchNoResultsTemplate').html());

      this.$resultListEl.append(noResultsTemplate(this.currentSearchParams));
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      this.createFilters();

    },
    createResultList: function () {
      var resultListTemplate = _.template($('#searchListItemTemplate').html());
      var list = resultListTemplate({results: this.results});

      this.$resultListEl.append(list);
      this.$resultListEl.append(this.pagination.createPaginationElement());
      this.createPageSelector();
    },
    createPageSelector: function () {
      if(this.resultTotalRecords > 0) {
        var pages = {
          15: false,
          30: false,
          60: false
        };
        var pagingTemplate = _.template($('#searchPagingSelectorTemplate').html());
        pages[this.getResultsPerPage()] = true;
        this.$resultListEl.append(pagingTemplate({ pages:pages }));
      }
    },
    updateCounterText: function () {
      var counterText = '%TOTAL% %RESULTSTR% for <strong>%TERM%</strong>';
      counterText = counterText.replace('%TOTAL%', this.resultTotalRecords);
      if(this.resultTotalRecords > 1) {
        counterText = counterText.replace('%RESULTSTR%', 'results');
      }
      else {
        counterText = counterText.replace('%RESULTSTR%', 'result');
      }
      counterText = counterText.replace('%TERM%', this.currentSearchParams.q);

      this.$searchCounterEl.html(counterText);
    },
    createFilters: function () {
      var that = this;

      this.$filtersEl.html('');
      this.$filterHeaderEl.html('');
      if(this.resultTotalRecords > 0) {
        var activeFilters = [];
        var filterSectionTemplate = _.template($('#searchListFilterSectionTemplate').html());

        _.each(this.filtersTitles, function (filterTitle, key) {
          var filter = that.searchFilters[key];
          filter.filterTitle = filterTitle;
          if(filter.activeFilterItems.length > 0 || filter.inactiveFilterItems.length > 0) {
            activeFilters = activeFilters.concat(filter.activeFilterItems);

            that.$filtersEl.append(filterSectionTemplate(filter));
          }
        });

        $('.filterSection').each(function () {
          var items = $(this).find('ul:not(".active-filters") li');
          var $moreButton = $(this).find('[data-show-more-items]');
          if (items.length > 5) {
            $(this).find('ul:not(".active-filters") li:gt(4)').hide();
            $moreButton.show();
          }
          else {
            $moreButton.hide();
          }
        });

        this.createFilterHeader(activeFilters);
      }
    },
    createFilterHeader: function (activeFilters) {
      var filterHeaderTemplate = _.template($('#searchHeaderFilterTemplate').html());
      if(activeFilters.length) {
        this.$filterHeaderEl.append(filterHeaderTemplate({activeFilterItems: activeFilters}));
      }
    },
    getJsonFromUrl: function (hashBased) {
      var query;
      if(hashBased) {
        var pos = location.href.indexOf("?");
        if(pos==-1) return [];
        query = location.href.substr(pos+1);
      } else {
        query = location.search.substr(1);
      }
      var result = {};
      query.split("&").forEach(function(part) {
        if(!part) return;
        part = part.split("+").join(" "); // replace every + with space, regexp-free version
        var eq = part.indexOf("=");
        var key = eq>-1 ? part.substr(0,eq) : part;
        var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
        var from = key.indexOf("[");
        if(from==-1) {
          var key = decodeURIComponent(key);
          if(!_.isEmpty(result[key])) {
            if(_.isArray(result[key])) {
              result[key].push(val);
            }
            else {
              var val = [result[key], val];
              result[key] = val;
            }
          }
          else {
            result[key] = val;
          }
        }
        else {
          var to = key.indexOf("]");
          var index = decodeURIComponent(key.substring(from+1,to));
          key = decodeURIComponent(key.substring(0,from));
          if(!result[key]) result[key] = [];
          if(!index) result[key].push(val);
          else result[key][index] = val;
        }
      });
      return result;
    }
  });

  new SearchResult();
})(jQuery);

<commit_msg>DPRO-1941 - Show more and less items on filters as a function<commit_after>var SearchResult;

(function ($) {
  SearchResult = Class.extend({
    isInitialized: false,

    $resultListEl: $('.searchResults'),
    $filtersEl: $('#searchFilters'),
    $filterHeaderEl: $('.header-filter'),
    $searchHeaderEl: $('.search-results-header'),
    $searchCounterEl: $('.results-number'),
    $searchBarForm: $('#searchControlBarForm'),
    $searchBarInput: $('#controlBarSearch'),
    $loadingEl: $('#search-loading'),
    $orderByEl: $('#sortOrder'),
    $searchFeedBtnEl: $('.search-feed'),
    $searchAlertOpenModalBtnEl: $('.open-search-alert-modal'),
    $searchAlertCloseModalBtnEl: $('.btn-cancel-savedsearch'),
    $searchAlertSaveBtnEl: $('#btn-save-savedsearch'),
    $searchAlertModalEl: $('#search-alert-modal'),
    resultPerPageElId: '#resultsPerPageDropdown',
    resetFiltersElId: '#clearAllFiltersButton',

    currentSearchParams: {
      "filterJournals": null,
      "filterSubjects": null,
      "filterArticleTypes": null,
      "filterAuthors": null,
      "filterSections": null,
      "filterStartDate": null,
      "filterEndDate": null,
      "resultsPerPage": null,
      "unformattedQuery": null,
      "q": null,
      "sortOrder": null,
      "page": 1
    },
    currentUrlParams: null,
    searchEndpoint: 'search',
    ajaxSearchEndpoint: 'dynamicSearch',
    searchFeedEndpoint: 'search/feed/atom',

    searchFilters: {},
    results: [],
    resultTotalRecords: 0,
    resultsOffset: 0,
    pagination: null,
    filtersParams: [
      "filterJournals",
      "filterSubjects",
      "filterArticleTypes",
      "filterAuthors",
      "filterSections",
      "filterStartDate",
      "filterEndDate"
    ],
    filtersTitles: {
      "journal": "Journal",
      "subject_area": "Subject Area",
      "article_type": "Article Type",
      "author": "Author",
      "section": "Where my keywords appear"
    },

    init: function () {
      var that = this;
      this.loadUrlParams();
      this.bindSearchEvents();
      var currentPage = this.getCurrentPage();
      var itemsPerPage = this.getResultsPerPage();
      this.pagination = new Pagination(currentPage, this.resultTotalRecords, itemsPerPage, function (currentPage) {
        that.currentSearchParams.page = currentPage;
        that.processRequest();
      });
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      if(this.currentSearchParams.q != null) {
        this.processRequest();
      }
      else {
        this.isInitialized = true;
      }
    },
    getCurrentPage: function() {
      if(this.currentSearchParams.page && this.currentSearchParams.page != null) {
        return parseInt(this.currentSearchParams.page);
      }
      else {
        return 1;
      }
    },
    getResultsPerPage: function () {
      if(this.currentSearchParams.resultsPerPage && this.currentSearchParams.resultsPerPage != null) {
        return parseInt(this.currentSearchParams.resultsPerPage);
      }
      else {
        return 15;
      }
    },
    showLoading: function () {
      this.$loadingEl.show();
    },
    hideLoading: function () {
      this.$loadingEl.hide();
    },
    loadUrlParams: function () {
      var that = this;
      var urlVars = this.getJsonFromUrl();
      this.currentSearchParams = _.mapObject(this.currentSearchParams, function (item, key) {
        var urlVar = urlVars[key];
        if(!_.isEmpty(urlVar)) {
          return urlVar;
        }
        else {
          return null;
        }
      });
    },
    createUrlParams: function () {
      var urlParams = '?';
      _.each(this.currentSearchParams, function (item, key) {
        if(item != null) {
          if(_.isArray(item)) {
            _.each(item, function (item) {
              urlParams = urlParams + key + '=' + encodeURIComponent(item) + '&';
            });
          }
          else {
            urlParams = urlParams + key + '=' + encodeURIComponent(item) + '&';
          }
        }
      });
      this.currentUrlParams = urlParams.slice(0, -1).replace('%20', '+');
      this.updatePageUrl();
    },
    updatePageUrl: function () {
      if(this.isInitialized) {
        var title = document.title;
        var href = this.searchEndpoint + this.currentUrlParams;
        window.history.pushState(href, title, href);
        this.$searchFeedBtnEl.prop('href', this.searchFeedEndpoint + this.currentUrlParams);
      }
    },
    bindSearchEvents: function () {
      var that = this;
      this.$searchBarForm.on('submit', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var inputValue = that.$searchBarInput.val();
        that.currentSearchParams.unformattedQuery = null;
        that.currentSearchParams.q = inputValue;
        that.currentSearchParams.page = 1;

        that.processRequest();
      });

      this.$orderByEl.on('change', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.currentSearchParams.sortOrder = $(this).val();
        that.currentSearchParams.page = 1;
        that.processRequest();
      });

      $('body').on('click', '[data-filter-param-name]', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var param = $(this).data('filter-param-name');
        var value = $(this).data('filter-value');

        var currentValue = that.currentSearchParams[param];

        if(_.isArray(currentValue)) {
          var index = _.indexOf(currentValue, value);

          if (index == -1) {
            that.currentSearchParams[param].push(value);
          }
          else {
            that.currentSearchParams[param].splice(index, 1);
          }
        }
        else {
          if(currentValue == value) {
            that.currentSearchParams[param] = [];
          }
          else if(currentValue != null) {
            that.currentSearchParams[param] = [currentValue, value];
          }
          else {
            that.currentSearchParams[param] = [value];
          }
        }

        that.currentSearchParams.page = 1;

        that.processRequest();
      }).on('change', this.resultPerPageElId, function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.currentSearchParams.resultsPerPage = $(this).val();
        that.currentSearchParams.page = 1;
        that.processRequest();
      }).on('click', this.resetFiltersElId, function (e) {
        e.preventDefault();
        e.stopPropagation();

        _.each(that.filtersParams, function (filter) {
          that.currentSearchParams[filter] = null;
        });
        that.processRequest();
      }).on('click', '[data-show-more-items]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.showMoreFilterItems($(this));
      }).on('click', '[data-show-less-items]', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.showLessFilterItems($(this));
      });

      this.$searchAlertOpenModalBtnEl.on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.$searchAlertModalEl.foundation('reveal', 'open');

        if(that.$searchAlertModalEl.hasClass('loggedIn')) {
          var textInput = $('#text_name_savedsearch');
          textInput.val(that.currentSearchParams.q);
          textInput.focus();
          textInput[0].selectionStart = textInput[0].selectionEnd = textInput[0].value.length;
        }
      });

      this.$searchAlertCloseModalBtnEl.on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        that.$searchAlertModalEl.foundation('reveal', 'close');
      });

      this.$searchAlertSaveBtnEl.on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        that.processSearchAlert();
      });
    },

    showLessFilterItems: function ($btn) {
      $btn.parent('ul').find('li:gt(4)').fadeOut();
      $btn.hide();
      $btn.parent('ul').find('[data-show-more-items]').fadeIn();
    },
    showMoreFilterItems: function ($btn) {
      $btn.parent('ul').find('li:gt(4)').fadeIn();
      $btn.hide();
    },

    processSearchAlert: function () {
      var that = this;
      var name = $('#text_name_savedsearch').val();
      var query = {};

      _.mapObject(this.currentSearchParams, function (item, key) {
        if(!_.isEmpty(item)) {
          query[key] = item;
        }
      });
      query = JSON.stringify(query);
      var weekly = $('#cb_weekly_savedsearch').is(':checked');
      var monthly = $('#cb_monthly_savedsearch').is(':checked');

      $.ajax({
        type: 'POST',
        url: 'searchalert/add',
        data: 'name=' + encodeURIComponent(name)
        + "&query=" + encodeURIComponent(query)
        + (weekly ? "&frequency=weekly" : "") + (monthly ? "&frequency=monthly" : ""),
        dataType:'json',
        success: function(response) {
          if (response.error) {
            var errorMessage = response.error;
            $('#span_error_savedsearch').html(errorMessage);
            return;
          }

          that.$searchAlertModalEl.foundation('reveal', 'close');
        },
        error: function(req, textStatus, errorThrown) {
          $('#span_error_savedsearch').html(errorThrown);
          console.log('error: ' + errorThrown);
        }
      });
    },

    processRequest: function () {
      var that = this;
      this.pagination.setCurrentPage(this.getCurrentPage());
      this.showLoading();
      this.createUrlParams();

      if(!this.isInitialized) {
        this.isInitialized = true;
      }

      $.ajax({
        url: this.ajaxSearchEndpoint+this.currentUrlParams,
        method: 'GET',
        jsonp: 'callback',
        dataType: 'json',
        timeout: 20000,
        success: function (response) {
          that.$resultListEl.html('');
          if(response.cannotParseQueryError) {
            that.showParseError();
          }
          else if (response.unknownQueryError) {
            that.showRequestError();
          }
          else {
            that.resultTotalRecords = response.searchResults.numFound;
            if (that.resultTotalRecords > 0) {
              that.results = response.searchResults.docs;
              var currentPage = that.getCurrentPage();
              var itemsPerPage = that.getResultsPerPage();
              that.pagination.setItemsPerPage(itemsPerPage);
              that.pagination.setTotalRecords(that.resultTotalRecords);
              that.pagination.setCurrentPage(currentPage);
              that.resultsOffset = response.searchResults.start;

              that.searchFilters = response.searchFilters;

              that.$searchHeaderEl.show();
              that.$filtersEl.show();

              that.createFilters();
              that.updateCounterText();
              that.createResultList();

              that.hideLoading();
            }
            else {
              that.showNoResults();
            }
          }
        },
        error: function (jqXHR, textStatus) {
          that.showRequestError();
        }
      });

    },
    showRequestError: function () {
      var errorTemplate = _.template($('#searchGeneralErrorTemplate').html());
      this.$resultListEl.append(errorTemplate());
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      this.createFilters();
    },
    showParseError: function () {
      var errorTemplate = _.template($('#searchParseErrorTemplate').html());
      this.$resultListEl.append(errorTemplate());
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      this.createFilters();
    },
    showNoResults: function() {
      var noResultsTemplate = _.template($('#searchNoResultsTemplate').html());

      this.$resultListEl.append(noResultsTemplate(this.currentSearchParams));
      this.$searchHeaderEl.hide();
      this.$filtersEl.hide();
      this.createFilters();

    },
    createResultList: function () {
      var resultListTemplate = _.template($('#searchListItemTemplate').html());
      var list = resultListTemplate({results: this.results});

      this.$resultListEl.append(list);
      this.$resultListEl.append(this.pagination.createPaginationElement());
      this.createPageSelector();
    },
    createPageSelector: function () {
      if(this.resultTotalRecords > 0) {
        var pages = {
          15: false,
          30: false,
          60: false
        };
        var pagingTemplate = _.template($('#searchPagingSelectorTemplate').html());
        pages[this.getResultsPerPage()] = true;
        this.$resultListEl.append(pagingTemplate({ pages:pages }));
      }
    },
    updateCounterText: function () {
      var counterText = '%TOTAL% %RESULTSTR% for <strong>%TERM%</strong>';
      counterText = counterText.replace('%TOTAL%', this.resultTotalRecords);
      if(this.resultTotalRecords > 1) {
        counterText = counterText.replace('%RESULTSTR%', 'results');
      }
      else {
        counterText = counterText.replace('%RESULTSTR%', 'result');
      }
      counterText = counterText.replace('%TERM%', this.currentSearchParams.q);

      this.$searchCounterEl.html(counterText);
    },
    createFilters: function () {
      var that = this;

      this.$filtersEl.html('');
      this.$filterHeaderEl.html('');
      if(this.resultTotalRecords > 0) {
        var activeFilters = [];
        var filterSectionTemplate = _.template($('#searchListFilterSectionTemplate').html());

        _.each(this.filtersTitles, function (filterTitle, key) {
          var filter = that.searchFilters[key];
          filter.filterTitle = filterTitle;
          if(filter.activeFilterItems.length > 0 || filter.inactiveFilterItems.length > 0) {
            activeFilters = activeFilters.concat(filter.activeFilterItems);

            that.$filtersEl.append(filterSectionTemplate(filter));
          }
        });

        $('.filterSection').each(function () {
          var items = $(this).find('ul:not(".active-filters") li');
          var $moreButton = $(this).find('[data-show-more-items]');
          if (items.length > 5) {
            that.showLessFilterItems($moreButton);
          }
          else {
            $moreButton.hide();
          }
        });

        this.createFilterHeader(activeFilters);
      }
    },
    createFilterHeader: function (activeFilters) {
      var filterHeaderTemplate = _.template($('#searchHeaderFilterTemplate').html());
      if(activeFilters.length) {
        this.$filterHeaderEl.append(filterHeaderTemplate({activeFilterItems: activeFilters}));
      }
    },
    getJsonFromUrl: function (hashBased) {
      var query;
      if(hashBased) {
        var pos = location.href.indexOf("?");
        if(pos==-1) return [];
        query = location.href.substr(pos+1);
      } else {
        query = location.search.substr(1);
      }
      var result = {};
      query.split("&").forEach(function(part) {
        if(!part) return;
        part = part.split("+").join(" "); // replace every + with space, regexp-free version
        var eq = part.indexOf("=");
        var key = eq>-1 ? part.substr(0,eq) : part;
        var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
        var from = key.indexOf("[");
        if(from==-1) {
          var key = decodeURIComponent(key);
          if(!_.isEmpty(result[key])) {
            if(_.isArray(result[key])) {
              result[key].push(val);
            }
            else {
              var val = [result[key], val];
              result[key] = val;
            }
          }
          else {
            result[key] = val;
          }
        }
        else {
          var to = key.indexOf("]");
          var index = decodeURIComponent(key.substring(from+1,to));
          key = decodeURIComponent(key.substring(0,from));
          if(!result[key]) result[key] = [];
          if(!index) result[key].push(val);
          else result[key][index] = val;
        }
      });
      return result;
    }
  });

  new SearchResult();
})(jQuery);

<|endoftext|>