<commit_before>var appConfig = require('./storage-config'),
    request = require('request'),
    ObjectID = require('mongodb').ObjectID;

var storagePlugin = {};

var db = undefined;

var init = function(app, dbConn) {
  db = dbConn;
};
storagePlugin.init = init;

var findUserAccount = function(params,done) {
  db.collection('useraccounts').findOne(params, done);
};
storagePlugin.findUserAccount = findUserAccount;

var saveUserAccount = function(user,done) {
  db.collection('useraccounts').save(user, {safe:true},done);
};
storagePlugin.saveUserAccount = saveUserAccount;

var removeUserAccount = function(params,done) {
  db.collection('useraccounts').remove(params, {single:true, safe:true},done);
};
storagePlugin.removeUserAccount = removeUserAccount;

var findUserHook = function(params,done) {
  if(params._id) {
    params._id = new ObjectID(params._id);
  }
  db.collection('userhooks').findOne(params,done);
};
storagePlugin.findUserHook = findUserHook;

var findUserHooks = function(params,done) {
  if(params._id) {
    params._id = new ObjectID(params._id);
  }
  db.collection('userhooks').find(params).toArray(done);
};
storagePlugin.findUserHooks = findUserHooks;

var saveUserHook = function(hook,done) {
  db.collection('userhooks').save(hook, {safe:true},done);
};
storagePlugin.saveUserHook = saveUserHook;

var removeUserHook = function(params,done) {
  if(params._id) {
    params._id = new ObjectID(params._id);
  }
  db.collection('userhooks').remove(params, {single:true, safe:true},done);
};
storagePlugin.removeUserHook = removeUserHook;

var ingestUserData = function(meta,data, done) {
  data._meta = {
    'user' : meta.user,
    'api' : meta.api,
    'url' : meta.url,
    'createTime' : new Date().getTime()
  };

  db.collection('temporary').save(data, function(err,doc){
     if(err) {
       console.log('Failed to save temp data: ' + JSON.stringify(err));
       done(undefined);
     } else {
       if(Array.isArray(doc)) {
         var docs = []; // should use _ here
         for(var i=0;i<doc.length;i++) {
           docs.push(doc[i]._id);
         }
         done(docs);
       }
       else {
         done([doc._id]);
       }
     }
  });
};
storagePlugin.ingestUserData = ingestUserData;

var queryUserData = function(meta,query,done) {

  if(!meta || !meta.user || meta.user.trim().length==0) {
     console.log('Queries must have user');
     done(undefined);
     return;
  }

  var data = {};

  // inspect and translate the params for query
  try {
    for(var key in query) {
      var value = query[key];
      var operator = 'eq'; // equal is the default operator

      // key~op indicates which operator should be used.
      if(key.match(/^.+\~(eq|lt|lte|gt|gte|ne|in|nin|re|rei)$/i)) { // NOTE: case insensitive here
        var delimPosition = key.lastIndexOf('~');
        operator = key.substring(delimPosition+1).toLowerCase();
        key = key.substring(0,delimPosition);
      }

      // make sure the data is clean
      if(!(typeof key === "string"            // key is string
         && typeof value  === "string"      // value is string
         && key.trim().length > 0           // key must not be empty
         && key.match(/^[a-zA-Z0-9._-]+$/)   // key only alpha, numeric, dot, underscore, dash
         && value.trim().length > 0)) {      // value must not be empty

        throw ('invalid parameter: ' + key + ' = ' + value);
      }

      // error if similar condition already defined or not compatible
      if(data[key] &&
         (operator.match(/^(eq|re|rei)$/)
          || typeof(data[key]) === "string"
          || data[key] instanceof Regexp)) {

          throw  'not handling compound conditions for eq, re, or rei operators';
      }

      // cast values. take into account that value may need to be split
      var castValues = operator.match(/^(in|nin)$/) ? value.split('~') : [value];
      for(var v=0;v<castValues.length;v++) {
        var castValue = castValues[v];

        // handle casting
        if(castValue.match(/^[+-]?[0-9]+$/)) {
          castValue = parseInt(castValue);
        }
        else if(castValue.match(/^[+-]?[0-9]+\.[0-9]+$/)) {
          castValue = parseFloat(castValue);
        }
        else if(key === '_id') {
          castValue = new ObjectID(castValue);
        }

        castValues[v] = castValue;
      }
      value = castValues.length==1 ? castValues[0] : castValues;

      if(operator === "eq") {
        data[key] = value;
      }
      else if(operator === "re" || operator === "rei") {
        try {
          var regex;
          if(operator === "rei") {
            regex = new RegExp(value,"i");
          }
          else {
            regex = new RegExp(value);
          }
          data[key] = regex;
        }
        catch(e) {
          throw ('invalid regex: ' + value);
        }
      }
      else {
        var conditionKey = '$' + operator;
        var conditionValue;
        // account for array values for IN and NOT IN
        if(operator.match(/^(in|nin)$/)) {
          if(Array.isArray(value)) {
            conditionValue = value;
          }
          else { // it needs to be an array
            conditionValue = [value];
          }
        }
        else {
          conditionValue = value;
        }

        //account for multiple conditions
        if(!data[key]) {
          data[key] = {};
        }
        data[key][conditionKey] = conditionValue;
      }
    }
    console.log("QUERY = " + JSON.stringify(data));
  }
  catch(ex) {
    console.log('INVALID QUERY: ' + ex);
    done(undefined);
    return;
  }

// this must be last
data['_meta.user'] = meta.user;

var options = {
  "limit": 20
};

db.collection('temporary').find(data,options).toArray(function(err,docs){
   if(err) {
     console.log('Failed to find matching data: ' + JSON.stringify(err));
     done(undefined);
   }
   else {
     done(docs);
   }
});

};
storagePlugin.queryUserData = queryUserData;

module.exports = storagePlugin;
<commit_msg>account ingestion being an array for _meta<commit_after>var appConfig = require('./storage-config'),
    request = require('request'),
    ObjectID = require('mongodb').ObjectID;

var storagePlugin = {};

var db = undefined;

var init = function(app, dbConn) {
  db = dbConn;
};
storagePlugin.init = init;

var findUserAccount = function(params,done) {
  db.collection('useraccounts').findOne(params, done);
};
storagePlugin.findUserAccount = findUserAccount;

var saveUserAccount = function(user,done) {
  db.collection('useraccounts').save(user, {safe:true},done);
};
storagePlugin.saveUserAccount = saveUserAccount;

var removeUserAccount = function(params,done) {
  db.collection('useraccounts').remove(params, {single:true, safe:true},done);
};
storagePlugin.removeUserAccount = removeUserAccount;

var findUserHook = function(params,done) {
  if(params._id) {
    params._id = new ObjectID(params._id);
  }
  db.collection('userhooks').findOne(params,done);
};
storagePlugin.findUserHook = findUserHook;

var findUserHooks = function(params,done) {
  if(params._id) {
    params._id = new ObjectID(params._id);
  }
  db.collection('userhooks').find(params).toArray(done);
};
storagePlugin.findUserHooks = findUserHooks;

var saveUserHook = function(hook,done) {
  db.collection('userhooks').save(hook, {safe:true},done);
};
storagePlugin.saveUserHook = saveUserHook;

var removeUserHook = function(params,done) {
  if(params._id) {
    params._id = new ObjectID(params._id);
  }
  db.collection('userhooks').remove(params, {single:true, safe:true},done);
};
storagePlugin.removeUserHook = removeUserHook;

var ingestUserData = function(meta,data, done) {
  var metaInstance = {
    'user' : meta.user,
    'api' : meta.api,
    'url' : meta.url,
    'createTime' : new Date().getTime()
  };

  if(Array.isArray(data)) {
    for(var i=0;i<data.length;i++) {
      data[i]._meta = metaInstance;
    }
  }
  else {
    data._meta = metaInstance;
  }

  db.collection('temporary').save(data, function(err,doc){
     if(err) {
       console.log('Failed to save temp data: ' + JSON.stringify(err));
       done(undefined);
     } else {
       if(Array.isArray(doc)) {
         var docs = []; // should use _ here
         for(var i=0;i<doc.length;i++) {
           docs.push(doc[i]._id);
         }
         done(docs);
       }
       else {
         done([doc._id]);
       }
     }
  });
};
storagePlugin.ingestUserData = ingestUserData;

var queryUserData = function(meta,query,done) {

  if(!meta || !meta.user || meta.user.trim().length==0) {
     console.log('Queries must have user');
     done(undefined);
     return;
  }

  var data = {};

  // inspect and translate the params for query
  try {
    for(var key in query) {
      var value = query[key];
      var operator = 'eq'; // equal is the default operator

      // key~op indicates which operator should be used.
      if(key.match(/^.+\~(eq|lt|lte|gt|gte|ne|in|nin|re|rei)$/i)) { // NOTE: case insensitive here
        var delimPosition = key.lastIndexOf('~');
        operator = key.substring(delimPosition+1).toLowerCase();
        key = key.substring(0,delimPosition);
      }

      // make sure the data is clean
      if(!(typeof key === "string"            // key is string
         && typeof value  === "string"      // value is string
         && key.trim().length > 0           // key must not be empty
         && key.match(/^[a-zA-Z0-9._-]+$/)   // key only alpha, numeric, dot, underscore, dash
         && value.trim().length > 0)) {      // value must not be empty

        throw ('invalid parameter: ' + key + ' = ' + value);
      }

      // error if similar condition already defined or not compatible
      if(data[key] &&
         (operator.match(/^(eq|re|rei)$/)
          || typeof(data[key]) === "string"
          || data[key] instanceof Regexp)) {

          throw  'not handling compound conditions for eq, re, or rei operators';
      }

      // cast values. take into account that value may need to be split
      var castValues = operator.match(/^(in|nin)$/) ? value.split('~') : [value];
      for(var v=0;v<castValues.length;v++) {
        var castValue = castValues[v];

        // handle casting
        if(castValue.match(/^[+-]?[0-9]+$/)) {
          castValue = parseInt(castValue);
        }
        else if(castValue.match(/^[+-]?[0-9]+\.[0-9]+$/)) {
          castValue = parseFloat(castValue);
        }
        else if(key === '_id') {
          castValue = new ObjectID(castValue);
        }

        castValues[v] = castValue;
      }
      value = castValues.length==1 ? castValues[0] : castValues;

      if(operator === "eq") {
        data[key] = value;
      }
      else if(operator === "re" || operator === "rei") {
        try {
          var regex;
          if(operator === "rei") {
            regex = new RegExp(value,"i");
          }
          else {
            regex = new RegExp(value);
          }
          data[key] = regex;
        }
        catch(e) {
          throw ('invalid regex: ' + value);
        }
      }
      else {
        var conditionKey = '$' + operator;
        var conditionValue;
        // account for array values for IN and NOT IN
        if(operator.match(/^(in|nin)$/)) {
          if(Array.isArray(value)) {
            conditionValue = value;
          }
          else { // it needs to be an array
            conditionValue = [value];
          }
        }
        else {
          conditionValue = value;
        }

        //account for multiple conditions
        if(!data[key]) {
          data[key] = {};
        }
        data[key][conditionKey] = conditionValue;
      }
    }
    console.log("QUERY = " + JSON.stringify(data));
  }
  catch(ex) {
    console.log('INVALID QUERY: ' + ex);
    done(undefined);
    return;
  }

// this must be last
data['_meta.user'] = meta.user;

var options = {
  "limit": 20
};

db.collection('temporary').find(data,options).toArray(function(err,docs){
   if(err) {
     console.log('Failed to find matching data: ' + JSON.stringify(err));
     done(undefined);
   }
   else {
     done(docs);
   }
});

};
storagePlugin.queryUserData = queryUserData;

module.exports = storagePlugin;
<|endoftext|>


<commit_before>var SimpleView = (function (containerID) {

  function SimpleView() {

    ViewContextAndStyle.apply(this, arguments);

    var _width  = 400;
    var _height = 200;

    this.cvs.width  = _width;
    this.cvs.height = _height;

    var xpad = 10;
    var ypad = 10;

    this.noteFontSize = _height - 2 * ypad;
    this.freqFontSize = 0.2 * _height;

    var semiMajorAxis = _width / 6;
    var semiMinorAxis = _height / 3;

    var cx = _width / 2;
    var cy = _height / 2;
    var x  = _width - (semiMajorAxis + 2 * xpad);

    var verticalSepX  = cx + xpad;
    var verticalSepBY = _height - ypad;
    var horizontalSepY = this.noteFontSize + 2 * ypad;

    var noteFontMaxWidth = cx - xpad;

    Object.defineProperties(this, {
      "width" : {
        enumerable   : true,
        configurable : false,
        get          : function () {
          return _width;
        },
        set          : function (val) {
          _width = val;

          this.cvs.width = _width;
          semiMajorAxis  = _width / 6;

          cx = _width / 2;
          x  = _width - (semiMajorAxis + xpad);
          noteFontMaxWidth = cx - xpad;
          verticalSepX     = cx + xpad;
        }
      },
      "height" : {
        enumerable   : true,
        configurable : false,
        get          : function () {
          return _height;
        },
        set          : function (val) {
          _height = val;

          cy              = _height / 2;
          this.cvs.height = _height;
          semiMinorAxis   = _height / 3;
          verticalSepBY   = _height - ypad;
          horizontalSepY  = this.noteFontSize + 2 * ypad;

          this.noteFontSize = 0.6 * _height;
          this.freqFontSize = 0.2 * _height;
        }
      }
    });

    Object.defineProperties(SimpleView.prototype, {
      "drawArrow" : {
        value        : function (direction) {

          var y = cy + (this.freqFontSize / 2 * direction);
          var dir    = semiMinorAxis * direction;
          var rpoint = y + (dir / 2);

          this.ctx.beginPath();

          this.ctx.moveTo(x - semiMajorAxis,y);
          this.ctx.lineTo(x,y + dir);
          this.ctx.lineTo(x + semiMajorAxis, y);
          this.ctx.bezierCurveTo(x, rpoint, x, rpoint, x - semiMajorAxis, y);

          this.ctx.fill();
        },
        enumerable   : false,
        configurable : false,
        writable     : false,
      },
     "drawNoteName" : {
       value        : function () {

         this.ctx.textAlign    = 'left';
         this.ctx.textBaseline = 'middle';
         this.ctx.font         = this.noteFont;

         this.ctx.fillText(this.peek.note.name, xpad, cy, noteFontMaxWidth);
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },
     "drawFrequency" : {
       value        : function () {

         var cents = Math.abs(this.peek.cents);

         this.ctx.fillStyle = cents - 5 <= 5 ? this.tunedColor : this.notTunedColor;

         this.ctx.textAlign    = 'center';
         this.ctx.textBaseline = 'middle';
         this.ctx.font         = this.freqFont;

         this.ctx.fillText(this.peek.frequency.toFixed(2), x, cy);

         this.ctx.fillStyle = black;
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },
     "drawSeparator" : {
       value        : function (x0, y0, x1, y1) {

         this.ctx.save();

         this.ctx.beginPath();

         this.ctx.moveTo(x0, y0);
         this.ctx.lineTo(x1, y1);

         this.ctx.strokeStyle = lightBlack;
         this.ctx.lineCap = "round";

         this.ctx.stroke();

         this.ctx.restore();
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },

     "run" : {
       value        : function () {

         var cents   = this.peek.cents;
         var tuneDir = cents > 0 ? 1 : -1;

         this.ctx.clearRect(0, 0, _width, _height);

         this.drawSeparator(verticalSepX, ypad, verticalSepX, verticalSepBY);
         this.drawArrow(tuneDir);
         this.drawFrequency();
         this.drawNoteName();

         window.requestAnimationFrame(this.run.bind(this));
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },
     "update" : {
       value        : function (element) {
         this.peek = element.peek;
       },
       enumerable   : true,
       configurable : false,
       writable     : false
     }
    });
  }

  if (!this.instance) {
    this.instance = new SimpleView(containerID);
  } else {
    console.log("An instance of SimpleView already exists.");
  }

  return this.instance;

});<commit_msg>Use save/restore instead of reasignment.<commit_after>var SimpleView = (function (containerID) {

  function SimpleView() {

    ViewContextAndStyle.apply(this, arguments);

    var _width  = 400;
    var _height = 200;

    this.cvs.width  = _width;
    this.cvs.height = _height;

    var xpad = 10;
    var ypad = 10;

    this.noteFontSize = _height - 2 * ypad;
    this.freqFontSize = 0.2 * _height;

    var semiMajorAxis = _width / 6;
    var semiMinorAxis = _height / 3;

    var cx = _width / 2;
    var cy = _height / 2;
    var x  = _width - (semiMajorAxis + 2 * xpad);

    var verticalSepX  = cx + xpad;
    var verticalSepBY = _height - ypad;
    var horizontalSepY = this.noteFontSize + 2 * ypad;

    var noteFontMaxWidth = cx - xpad;

    Object.defineProperties(this, {
      "width" : {
        enumerable   : true,
        configurable : false,
        get          : function () {
          return _width;
        },
        set          : function (val) {
          _width = val;

          this.cvs.width = _width;
          semiMajorAxis  = _width / 6;

          cx = _width / 2;
          x  = _width - (semiMajorAxis + xpad);
          noteFontMaxWidth = cx - xpad;
          verticalSepX     = cx + xpad;
        }
      },
      "height" : {
        enumerable   : true,
        configurable : false,
        get          : function () {
          return _height;
        },
        set          : function (val) {
          _height = val;

          cy              = _height / 2;
          this.cvs.height = _height;
          semiMinorAxis   = _height / 3;
          verticalSepBY   = _height - ypad;
          horizontalSepY  = this.noteFontSize + 2 * ypad;

          this.noteFontSize = 0.6 * _height;
          this.freqFontSize = 0.2 * _height;
        }
      }
    });

    Object.defineProperties(SimpleView.prototype, {
      "drawArrow" : {
        value        : function (direction) {

          var y = cy + (this.freqFontSize / 2 * direction);
          var dir    = semiMinorAxis * direction;
          var rpoint = y + (dir / 2);

          this.ctx.beginPath();

          this.ctx.moveTo(x - semiMajorAxis,y);
          this.ctx.lineTo(x,y + dir);
          this.ctx.lineTo(x + semiMajorAxis, y);
          this.ctx.bezierCurveTo(x, rpoint, x, rpoint, x - semiMajorAxis, y);

          this.ctx.fill();
        },
        enumerable   : false,
        configurable : false,
        writable     : false,
      },
     "drawNoteName" : {
       value        : function () {

         this.ctx.save();

         this.ctx.textAlign    = 'left';
         this.ctx.textBaseline = 'middle';
         this.ctx.font         = this.noteFont;

         this.ctx.fillText(this.peek.note.name, xpad, cy, noteFontMaxWidth);

         this.ctx.restore();
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },
     "drawFrequency" : {
       value        : function () {

         var cents = Math.abs(this.peek.cents);

         this.ctx.save();

         this.ctx.fillStyle = cents - 5 <= 5 ? this.tunedColor : this.notTunedColor;

         this.ctx.textAlign    = 'center';
         this.ctx.textBaseline = 'middle';
         this.ctx.font         = this.freqFont;

         this.ctx.fillText(this.peek.frequency.toFixed(2), x, cy);

         this.ctx.restore();
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },
     "drawSeparator" : {
       value        : function (x0, y0, x1, y1) {

         this.ctx.save();

         this.ctx.beginPath();

         this.ctx.moveTo(x0, y0);
         this.ctx.lineTo(x1, y1);

         this.ctx.strokeStyle = lightBlack;
         this.ctx.lineCap = "round";

         this.ctx.stroke();

         this.ctx.restore();
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },

     "run" : {
       value        : function () {

         var cents   = this.peek.cents;
         var tuneDir = cents > 0 ? 1 : -1;

         this.ctx.clearRect(0, 0, _width, _height);

         this.drawSeparator(verticalSepX, ypad, verticalSepX, verticalSepBY);
         this.drawArrow(tuneDir);
         this.drawFrequency();
         this.drawNoteName();

         window.requestAnimationFrame(this.run.bind(this));
       },
       enumerable   : false,
       configurable : false,
       writable     : false
     },
     "update" : {
       value        : function (element) {
         this.peek = element.peek;
       },
       enumerable   : true,
       configurable : false,
       writable     : false
     }
    });
  }

  if (!this.instance) {
    this.instance = new SimpleView(containerID);
  } else {
    console.log("An instance of SimpleView already exists.");
  }

  return this.instance;

});<|endoftext|>


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

goog.provide('unisubs.RequestDialog');

/**
 * @constructor
 * @param {string} videoID
 */
unisubs.RequestDialog = function(videoID) {
    goog.ui.Dialog.call(this, 'unisubs-modal-lang', true);
    this.setButtonSet(null);
    this.setDisposeOnHide(true);
    this.videoID_ = videoID;
    this.langMenuCount_ = 0;

    // Stores the languages of the user
    this.myLanguages_ = [];
    // Stores all availalbe languages for requesting subtitles.
    this.allLanguages_ = [];
    // Stores languages being requested
    this.requestLanguages_ = [];
    // Stores if the request should be tracked by the user
    this.track_ = true;
    // Stores the description for the request
    this.description_ = null;
    /**
     * Placeholder language option
     * @const
     * @type {string}
     */
    this.EMPTY_LANG_ = 'Select a language';
    /**
     * Message shown to user if they don't select a language
     * @const
     * @type {string}
     */
    this.EMPTY_LANG_WARNING_ = 'Please select a language to continue';
    /**
     * Message shown to user if they don't enter a description
     * @const
     * @type {string}
     */
    this.EMPTY_DESC_WARNING_ = 'Please provide a reason for your request';
    /**
     * Label for tracking request checkbox
     * @const
     * @type {string}
     */
    this.TRACK_REQUEST_LABEL_ = 'Subscribe to updates about this video';
    /**
     * The default content of request description text area
     * @const
     * @type {string}
     */
    this.DESCRIPTION_INITIAL_ = 'Tell us why you\'re requesting these subtitles';
    /**
     * Displayed on a successfull request submission
     * @const
     * @type {string}
     */
    this.SUBMISSION_CONFIRM_ = 'Your request has been submitted. Thanks!';
    /**
     * Error to be shown when the response from server is negetive
     * @const
     * @type {string}
     */
    this.SUBMIT_ERROR_ = 'We weren\'t able to process your request. Please try again.';
};
goog.inherits(unisubs.RequestDialog, goog.ui.Dialog);

unisubs.RequestDialog.prototype.createDom = function() {
    unisubs.RequestDialog.superClass_.createDom.call(this);
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());
    var el = this.getContentElement();
    this.headingDiv_ = $d('h3', null, 'Request subtitles');
    this.loadingDiv_ = $d('p', null, 'Loading...')
    this.contentDiv_ = $d('div', {'className':'unisubs-request-div'}, this.loadingDiv_);
    goog.dom.append(el, this.headingDiv_, this.contentDiv_);
};

unisubs.RequestDialog.prototype.enterDocument = function() {
    unisubs.RequestDialog.superClass_.enterDocument.call(this);
    this.connectEvents_();
};

unisubs.RequestDialog.prototype.setVisible = function(visible) {
    unisubs.startdialog.Dialog.superClass_.setVisible.call(this, visible);
    if (visible)
        unisubs.Rpc.call(
            'fetch_request_dialog_contents',
            { 'video_id': this.videoID_ },
            goog.bind(this.responseReceived_, this));
};

/**
 * Create a language select dropdown
 */
unisubs.RequestDialog.prototype.makeDropdown_ = function($d){
    var options = [];
    contents = this.allLanguages_
    options.push($d('option', {'value': ''}, this.EMPTY_LANG_));
    for (var i = 0; i < contents.length; i++){
         options.push($d('option', {'value': contents[i][0]}, contents[i][1]));
    }
    return $d('select', {'id':'unisubs-requestlang-'+ ++this.langMenuCount_}, options);
};

/**
 * Adds two dropdown to the dialog contents.
 * Each call creats two dropdowns.
 */
unisubs.RequestDialog.prototype.addDropdowns_ = function($d){
    goog.dom.append(this.langDiv_, this.makeDropdown_($d));
};

/**
 * Add the rest of the fields (tracking request, description) to the
 * form.
 */
unisubs.RequestDialog.prototype.addMetaForm_ = function($d){
    this.metaDiv_ = $d('div');
    this.checkBox_ = $d('input', {'type':'checkbox', 'checked':true, 'id':'unisubs-request-track'});
    this.checkBoxLabel_ = $d('label', {'for':'unisubs-request-track'}, this.TRACK_REQUEST_LABEL_);
    this.descriptionText_ = $d('textarea', { 'id':'unisubs-request-description' }, this.DESCRIPTION_INITIAL_);
    goog.dom.append(this.metaDiv_, this.descriptionText_,
                    this.checkBox_, this.checkBoxLabel_);
    goog.dom.append(this.contentDiv_, this.metaDiv_);
}

unisubs.RequestDialog.prototype.responseReceived_ = function(jsonResult) {
    this.fetchCompleted_ = true;

    //The data required to create the form
    this.myLanguages_ = jsonResult['my_languages'];
    this.allLanguages_ = jsonResult['all_languages'];
    //Filter out duplicates from myLanguages list
    goog.array.removeDuplicates(this.myLanguages_);
    this.myLanguages_ = goog.array.filter(
        this.myLanguages_, function(l) {
            return !!unisubs.languageNameForCode(l);
        });

    // Create a Request object which will store the request relevent info.
    goog.dom.removeChildren(this.contentDiv_);
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());

    // Create the form
    this.warningElem_ = $d('p', 'warning');
    this.langDiv_ = $d('div', {'class':'unisubs-request-langs'}, $d('p', null, 'Your request will be submitted to our community of volunteers.'));
    this.addLangButton_ =
    $d('a',
           {'href':'#',
            'className': "unisubs-request-addlang"},
            'Add another language');
    this.okButton_ =
    $d('a',
           {'href':'#',
            'className': "unisubs-green-button unisubs-big",
            'style':'clear:both;'},
           'Request');
    this.closeButton_ =
    $d('a',
           {'href':'#',
            'className': "unisubs-green-button unisubs-big",
            'style':'clear:both;'},
           'Close');

    goog.dom.append(this.contentDiv_, this.warningElem_);
    goog.dom.append(this.contentDiv_, this.langDiv_);
    goog.style.showElement(this.warningElem_, false);
    this.addDropdowns_($d);
    goog.dom.append(this.contentDiv_, this.addLangButton_);
    this.addMetaForm_($d);
    goog.dom.append(this.contentDiv_, this.okButton_);
    this.clearDiv = $d('div');
    unisubs.style.setProperty(this.clearDiv, 'clear', 'both');
    this.clearDiv.innerHTML = " ";
    this.contentDiv_.appendChild(this.clearDiv);
    this.reposition();
    this.connectEvents_();
};

unisubs.RequestDialog.prototype.connectEvents_ = function() {
    if (!this.isInDocument() || !this.fetchCompleted_)
        return;
    this.getHandler().
        listen(
            this.okButton_,
            goog.events.EventType.CLICK,
            this.okClicked_).
        listen(
            this.addLangButton_,
            goog.events.EventType.CLICK,
            this.addLangClicked_).
        listen(
            this.closeButton_,
            goog.events.EventType.CLICK,
            this.closeClicked_);
};

unisubs.RequestDialog.prototype.okClicked_ = function(e) {
    e.preventDefault();
    if (this.okHasBeenClicked_)
        goog.style.showElement(this.warningElem_, false);

    this.okHasBeenClicked_ = true;

    // Stores the languages selected from the select box in the model
    for (i = 1; i <= this.langMenuCount_; i++){
        var e = document.getElementById('unisubs-requestlang-' + i);
        var lang = e.options[e.selectedIndex].value
        if (lang){
            this.requestLanguages_.push(lang);
        }
    }

    // Submit the request if at least one language is there
    if (this.requestLanguages_.length > 0){
        var track = document.getElementById('unisubs-request-track').checked;
        var description = document.getElementById('unisubs-request-description').value;
        this.track_ = track;
        if (description != this.DESCRIPTION_INITIAL_){
            this.description_ = description;
            this.submitRequest(goog.bind(this.requestCallback_,
                                  this));
        } else {
            goog.dom.setTextContent(this.warningElem_, this.EMPTY_DESC_WARNING_);
            goog.style.showElement(this.warningElem_, true);
        }
    }
    else{
        goog.dom.setTextContent(this.warningElem_, this.EMPTY_LANG_WARNING_);
        goog.style.showElement(this.warningElem_, true);
    }
};

/**
 * Add more languages to the form
 */
unisubs.RequestDialog.prototype.addLangClicked_ = function(e) {
    e.preventDefault();
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());
    this.addDropdowns_($d);
    this.reposition();
};

/**
 * Close the request dialog
 */
unisubs.RequestDialog.prototype.closeClicked_ = function(e) {
    e.preventDefault();
    this.setVisible(false);
};

/**
 * Callback after a request has been posted.
 * Notifies about successful or unsuccessful request
 */
unisubs.RequestDialog.prototype.requestCallback_ = function(jsonResult) {
    // If response has a key status, set to true, hide the dialog
    if (jsonResult["status"]){
        // Recreate the dialog with thank you message
        var $d = goog.bind(this.getDomHelper().createDom,
                           this.getDomHelper());
        goog.dom.removeChildren(this.contentDiv_);
        this.confirmDiv_ = $d('p', null, this.SUBMISSION_CONFIRM_);
        this.volunteerDiv_ = $d('p', null, 'Want to pitch in yourself? Visit our ',
                                $d('a', {"href": unisubs.siteURL() + '/volunteer/requested/' },
                                   "requests page"), '!');

        this.contentDiv_.appendChild(this.confirmDiv_);
        this.contentDiv_.appendChild(this.volunteerDiv_);
        this.contentDiv_.appendChild(this.closeButton_);
        this.contentDiv_.appendChild(this.clearDiv);
    }
    else{
        goog.dom.setTextContent(this.warningElem_, this.SUBMIT_ERROR_);
        goog.style.showElement(this.warningElem_, true);
    }
};

/**
 * Submit the request data generated by the form to the server.
 */
unisubs.RequestDialog.prototype.submitRequest = function(){
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());
    goog.dom.removeChildren(this.contentDiv_);
    this.contentDiv_.appendChild($d('div', {'className':'unisubs-request-div'}, this.loadingDiv_));

    unisubs.Rpc.call(
            'submit_subtitle_request',
            {
                'video_id':this.videoID_,
                'request_languages':this.requestLanguages_,
                'track_request':this.track_,
                'description':this.description_
            },
            goog.bind(this.requestCallback_, this));
};
<commit_msg>Fixed user facing ordering in request sub dialog, for https://www.pivotaltracker.com/story/show/17506947<commit_after>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2010 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('unisubs.RequestDialog');

/**
 * @constructor
 * @param {string} videoID
 */
unisubs.RequestDialog = function(videoID) {
    goog.ui.Dialog.call(this, 'unisubs-modal-lang', true);
    this.setButtonSet(null);
    this.setDisposeOnHide(true);
    this.videoID_ = videoID;
    this.langMenuCount_ = 0;

    // Stores the languages of the user
    this.myLanguages_ = [];
    // Stores all availalbe languages for requesting subtitles.
    this.allLanguages_ = [];
    // Stores languages being requested
    this.requestLanguages_ = [];
    // Stores if the request should be tracked by the user
    this.track_ = true;
    // Stores the description for the request
    this.description_ = null;
    /**
     * Placeholder language option
     * @const
     * @type {string}
     */
    this.EMPTY_LANG_ = 'Select a language';
    /**
     * Message shown to user if they don't select a language
     * @const
     * @type {string}
     */
    this.EMPTY_LANG_WARNING_ = 'Please select a language to continue';
    /**
     * Message shown to user if they don't enter a description
     * @const
     * @type {string}
     */
    this.EMPTY_DESC_WARNING_ = 'Please provide a reason for your request';
    /**
     * Label for tracking request checkbox
     * @const
     * @type {string}
     */
    this.TRACK_REQUEST_LABEL_ = 'Subscribe to updates about this video';
    /**
     * The default content of request description text area
     * @const
     * @type {string}
     */
    this.DESCRIPTION_INITIAL_ = 'Tell us why you\'re requesting these subtitles';
    /**
     * Displayed on a successfull request submission
     * @const
     * @type {string}
     */
    this.SUBMISSION_CONFIRM_ = 'Your request has been submitted. Thanks!';
    /**
     * Error to be shown when the response from server is negetive
     * @const
     * @type {string}
     */
    this.SUBMIT_ERROR_ = 'We weren\'t able to process your request. Please try again.';
};
goog.inherits(unisubs.RequestDialog, goog.ui.Dialog);

unisubs.RequestDialog.prototype.createDom = function() {
    unisubs.RequestDialog.superClass_.createDom.call(this);
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());
    var el = this.getContentElement();
    this.headingDiv_ = $d('h3', null, 'Request subtitles');
    this.loadingDiv_ = $d('p', null, 'Loading...')
    this.contentDiv_ = $d('div', {'className':'unisubs-request-div'}, this.loadingDiv_);
    goog.dom.append(el, this.headingDiv_, this.contentDiv_);
};

unisubs.RequestDialog.prototype.enterDocument = function() {
    unisubs.RequestDialog.superClass_.enterDocument.call(this);
    this.connectEvents_();
};

unisubs.RequestDialog.prototype.setVisible = function(visible) {
    unisubs.startdialog.Dialog.superClass_.setVisible.call(this, visible);
    if (visible)
        unisubs.Rpc.call(
            'fetch_request_dialog_contents',
            { 'video_id': this.videoID_ },
            goog.bind(this.responseReceived_, this));
};

/**
 * Create a language select dropdown
 */
unisubs.RequestDialog.prototype.makeDropdown_ = function($d){
    var options = [];
    contents = this.allLanguages_
    options.push($d('option', {'value': ''}, this.EMPTY_LANG_));
    for (var i = 0; i < contents.length; i++){
         options.push($d('option', {'value': contents[i][0]}, contents[i][1]));
    }
    return $d('select', {'id':'unisubs-requestlang-'+ ++this.langMenuCount_}, options);
};

/**
 * Adds two dropdown to the dialog contents.
 * Each call creats two dropdowns.
 */
unisubs.RequestDialog.prototype.addDropdowns_ = function($d){
    goog.dom.append(this.langDiv_, this.makeDropdown_($d));
};

/**
 * Add the rest of the fields (tracking request, description) to the
 * form.
 */
unisubs.RequestDialog.prototype.addMetaForm_ = function($d){
    this.metaDiv_ = $d('div');
    this.checkBox_ = $d('input', {'type':'checkbox', 'checked':true, 'id':'unisubs-request-track'});
    this.checkBoxLabel_ = $d('label', {'for':'unisubs-request-track'}, this.TRACK_REQUEST_LABEL_);
    this.descriptionText_ = $d('textarea', { 'id':'unisubs-request-description' }, this.DESCRIPTION_INITIAL_);
    goog.dom.append(this.metaDiv_, this.descriptionText_,
                    this.checkBox_, this.checkBoxLabel_);
    goog.dom.append(this.contentDiv_, this.metaDiv_);
}

unisubs.RequestDialog.prototype.responseReceived_ = function(jsonResult) {
    this.fetchCompleted_ = true;

    //The data required to create the form
    this.myLanguages_ = jsonResult['my_languages'];
    this.allLanguages_ = jsonResult['all_languages'];
    // we need to sort on actul lang name, not lang code
    // .i.e Spanish (es) should come after Danish (da)
    goog.array.sort( this.allLanguages_, function(a,b){
            return goog.array.defaultCompare(a[1], b[1]);
    });
    //Filter out duplicates from myLanguages list
    goog.array.removeDuplicates(this.myLanguages_);
    this.myLanguages_ = goog.array.filter(
        this.myLanguages_, function(l) {
            return !!unisubs.languageNameForCode(l);
        });

    // Create a Request object which will store the request relevent info.
    goog.dom.removeChildren(this.contentDiv_);
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());

    // Create the form
    this.warningElem_ = $d('p', 'warning');
    this.langDiv_ = $d('div', {'class':'unisubs-request-langs'}, $d('p', null, 'Your request will be submitted to our community of volunteers.'));
    this.addLangButton_ =
    $d('a',
           {'href':'#',
            'className': "unisubs-request-addlang"},
            'Add another language');
    this.okButton_ =
    $d('a',
           {'href':'#',
            'className': "unisubs-green-button unisubs-big",
            'style':'clear:both;'},
           'Request');
    this.closeButton_ =
    $d('a',
           {'href':'#',
            'className': "unisubs-green-button unisubs-big",
            'style':'clear:both;'},
           'Close');

    goog.dom.append(this.contentDiv_, this.warningElem_);
    goog.dom.append(this.contentDiv_, this.langDiv_);
    goog.style.showElement(this.warningElem_, false);
    this.addDropdowns_($d);
    goog.dom.append(this.contentDiv_, this.addLangButton_);
    this.addMetaForm_($d);
    goog.dom.append(this.contentDiv_, this.okButton_);
    this.clearDiv = $d('div');
    unisubs.style.setProperty(this.clearDiv, 'clear', 'both');
    this.clearDiv.innerHTML = " ";
    this.contentDiv_.appendChild(this.clearDiv);
    this.reposition();
    this.connectEvents_();
};

unisubs.RequestDialog.prototype.connectEvents_ = function() {
    if (!this.isInDocument() || !this.fetchCompleted_)
        return;
    this.getHandler().
        listen(
            this.okButton_,
            goog.events.EventType.CLICK,
            this.okClicked_).
        listen(
            this.addLangButton_,
            goog.events.EventType.CLICK,
            this.addLangClicked_).
        listen(
            this.closeButton_,
            goog.events.EventType.CLICK,
            this.closeClicked_);
};

unisubs.RequestDialog.prototype.okClicked_ = function(e) {
    e.preventDefault();
    if (this.okHasBeenClicked_)
        goog.style.showElement(this.warningElem_, false);

    this.okHasBeenClicked_ = true;

    // Stores the languages selected from the select box in the model
    for (i = 1; i <= this.langMenuCount_; i++){
        var e = document.getElementById('unisubs-requestlang-' + i);
        var lang = e.options[e.selectedIndex].value
        if (lang){
            this.requestLanguages_.push(lang);
        }
    }

    // Submit the request if at least one language is there
    if (this.requestLanguages_.length > 0){
        var track = document.getElementById('unisubs-request-track').checked;
        var description = document.getElementById('unisubs-request-description').value;
        this.track_ = track;
        if (description != this.DESCRIPTION_INITIAL_){
            this.description_ = description;
            this.submitRequest(goog.bind(this.requestCallback_,
                                  this));
        } else {
            goog.dom.setTextContent(this.warningElem_, this.EMPTY_DESC_WARNING_);
            goog.style.showElement(this.warningElem_, true);
        }
    }
    else{
        goog.dom.setTextContent(this.warningElem_, this.EMPTY_LANG_WARNING_);
        goog.style.showElement(this.warningElem_, true);
    }
};

/**
 * Add more languages to the form
 */
unisubs.RequestDialog.prototype.addLangClicked_ = function(e) {
    e.preventDefault();
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());
    this.addDropdowns_($d);
    this.reposition();
};

/**
 * Close the request dialog
 */
unisubs.RequestDialog.prototype.closeClicked_ = function(e) {
    e.preventDefault();
    this.setVisible(false);
};

/**
 * Callback after a request has been posted.
 * Notifies about successful or unsuccessful request
 */
unisubs.RequestDialog.prototype.requestCallback_ = function(jsonResult) {
    // If response has a key status, set to true, hide the dialog
    if (jsonResult["status"]){
        // Recreate the dialog with thank you message
        var $d = goog.bind(this.getDomHelper().createDom,
                           this.getDomHelper());
        goog.dom.removeChildren(this.contentDiv_);
        this.confirmDiv_ = $d('p', null, this.SUBMISSION_CONFIRM_);
        this.volunteerDiv_ = $d('p', null, 'Want to pitch in yourself? Visit our ',
                                $d('a', {"href": unisubs.siteURL() + '/volunteer/requested/' },
                                   "requests page"), '!');

        this.contentDiv_.appendChild(this.confirmDiv_);
        this.contentDiv_.appendChild(this.volunteerDiv_);
        this.contentDiv_.appendChild(this.closeButton_);
        this.contentDiv_.appendChild(this.clearDiv);
    }
    else{
        goog.dom.setTextContent(this.warningElem_, this.SUBMIT_ERROR_);
        goog.style.showElement(this.warningElem_, true);
    }
};

/**
 * Submit the request data generated by the form to the server.
 */
unisubs.RequestDialog.prototype.submitRequest = function(){
    var $d = goog.bind(this.getDomHelper().createDom,
                       this.getDomHelper());
    goog.dom.removeChildren(this.contentDiv_);
    this.contentDiv_.appendChild($d('div', {'className':'unisubs-request-div'}, this.loadingDiv_));

    unisubs.Rpc.call(
            'submit_subtitle_request',
            {
                'video_id':this.videoID_,
                'request_languages':this.requestLanguages_,
                'track_request':this.track_,
                'description':this.description_
            },
            goog.bind(this.requestCallback_, this));
};
<|endoftext|>


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

goog.provide('mirosubs.widget.Widget');

/**
 * @constructor
 * @param {Object} widgetConfig parameter documentation is currenty in embed.js.
 */
mirosubs.widget.Widget = function(widgetConfig) {
    goog.ui.Component.call(this);

    /**
     * @type {string}
     */
    this.videoURL_ = widgetConfig['video_url'];
    this.alternateVideoURLs_ = widgetConfig['alternate_video_urls'];
    this.forceFormat_ = !!widgetConfig['force_format'];
    this.videoConfig_ = widgetConfig['video_config'];
    /**
     * If true, this is the equivalent of clicking on "Add subtitles"
     * if base state is null, or equivalent of clicking on "Improve
     * these subtitles" if base state is not null.
     * @type {boolean}
     */
    this.subtitleImmediately_ =
        !!widgetConfig['subtitle_immediately'];
    /**
     * If true, this is the equivalent of clicking on
     * "Add New Translation"
     * @type {boolean}
     */
    this.translateImmediately_ =
        !!widgetConfig['translate_immediately'];
    var baseState = widgetConfig['base_state'];
    if (baseState)
        this.baseState_ = new mirosubs.widget.BaseState(baseState);
};
goog.inherits(mirosubs.widget.Widget, goog.ui.Component);

mirosubs.widget.Widget.prototype.createDom = function() {
    mirosubs.widget.Widget.superClass_.createDom.call(this);
    this.addWidget_(this.getElement());
};

/**
 * @param {HTMLDivElement} el Just a blank div with class mirosubs-widget.
 */
mirosubs.widget.Widget.prototype.decorateInternal = function(el) {
    mirosubs.widget.Widget.superClass_.decorateInternal.call(this, el);
    this.addWidget_(el);
};

mirosubs.widget.Widget.prototype.createVideoPlayer_ = function(videoSource) {
    this.videoPlayer_ = videoSource.createPlayer();
    this.addChildAt(this.videoPlayer_, 0, true);
    this.setVideoDimensions_();
};

mirosubs.widget.Widget.prototype.findVideoSource_ = function() {
    if (this.alternateVideoURLs_ && this.alternateVideoURLs_.length > 0) {
        var mainVideoSpec = this.videoURL_;
        if (this.videoConfig_)
            mainVideoSpec = { 'url': this.videoURL_,
                              'config': this.videoConfig_ };
        return mirosubs.video.VideoSource.bestVideoSource(
            goog.array.concat(mainVideoSpec, this.alternateVideoURLs_));
    }
    else
        return mirosubs.video.VideoSource.videoSourceForURL(
            this.videoURL_, this.videoConfig_);
};

mirosubs.widget.Widget.prototype.isVideoSourceImmediatelyUsable_ =
    function()
{
    if (this.videoSource_ instanceof mirosubs.video.BlipTVPlaceholder)
        return false;
    if (this.forceFormat_ || goog.isDefAndNotNull(this.alternateVideoURLs_))
        return true;
    else {
        return (!(this.videoSource_ instanceof mirosubs.video.Html5VideoSource)
                || mirosubs.video.supportsVideo());
    }
};

mirosubs.widget.Widget.prototype.addVideoLoadingPlaceholder_ =
    function(el)
{
    this.videoPlaceholder_ = this.getDomHelper().createDom(
        'div', 'mirosubs-videoLoading', 'Loading...');
    goog.dom.appendChild(el, this.videoPlaceholder_);
};

mirosubs.widget.Widget.prototype.addWidget_ = function(el) {
    try {
        this.videoSource_ = this.findVideoSource_();
    }
    catch (err) {
        // TODO: format this more.
        el.innerHTML = err.message;
        return;
    }
    if (this.isVideoSourceImmediatelyUsable_())
        this.createVideoPlayer_(this.videoSource_);
    else
        this.addVideoLoadingPlaceholder_(el);
    this.videoTab_ = new mirosubs.widget.VideoTab();
    var videoTabContainer = new goog.ui.Component();
    this.addChild(videoTabContainer, true);
    videoTabContainer.addChild(this.videoTab_, true);
    videoTabContainer.getElement().className =
        'mirosubs-videoTab-container';
    this.videoTab_.showLoading();
    var args = {
        'video_url': this.videoURL_,
        'is_remote': mirosubs.isFromDifferentDomain()
    };
    if (this.baseState_)
        args['base_state'] = this.baseState_.ORIGINAL_PARAM;
    mirosubs.Rpc.call(
        'show_widget', args,
        goog.bind(this.initializeState_, this),
        goog.bind(this.showWidgetError_, this));
};

mirosubs.widget.Widget.prototype.showWidgetError_ = function() {
    // call to show_widget timed out.
    if (!this.isVideoSourceImmediatelyUsable_()) {
        // waiting for video source from server.
        if (this.videoSource_ instanceof mirosubs.video.BlipTVPlaceholder) {
            // out of luck.

        }
        else {
            this.createVideoPlayer_(this.videoSource_);
        }
    }
    this.videoTab_.showError();
};

mirosubs.widget.Widget.prototype.initializeState_ = function(result) {
    if (!this.isVideoSourceImmediatelyUsable_()) {
        goog.dom.removeNode(this.videoPlaceholder_);
        var videoSource = mirosubs.video.VideoSource.bestVideoSource(
            result['video_urls']);
        if (goog.typeOf(videoSource) == goog.typeOf(this.videoSource_) &&
            this.videoConfig_)
            videoSource.setVideoConfig(this.videoConfig_);
        this.videoSource_ = videoSource;
        this.createVideoPlayer_(this.videoSource_);
    }

    this.controller_ = new mirosubs.widget.WidgetController(
        this.videoURL_, this.videoPlayer_, this.videoTab_);
    this.controller_.initializeState(result);

    var subController = this.controller_.getSubtitleController();

    if (this.subtitleImmediately_)
        goog.Timer.callOnce(
            goog.bind(subController.openSubtitleDialog, subController));
    else if (this.translateImmediately_)
        goog.Timer.callOnce(
            goog.bind(subController_.openNewLanguageDialog,
                      subController_));
};

mirosubs.widget.Widget.prototype.enterDocument = function() {
    mirosubs.widget.Widget.superClass_.enterDocument.call(this);
    this.setVideoDimensions_();
};

mirosubs.widget.Widget.prototype.setVideoDimensions_ = function() {
    if (!this.isInDocument() || !this.videoPlayer_)
        return;
    if (this.videoPlayer_.areDimensionsKnown())
        this.videoDimensionsKnown_();
    else
        this.getHandler().listen(
            this.videoPlayer_,
            mirosubs.video.AbstractVideoPlayer.EventType.DIMENSIONS_KNOWN,
            this.videoDimensionsKnown_);
};

mirosubs.widget.Widget.prototype.videoDimensionsKnown_ = function() {
    this.getElement().style.width =
        Math.round(this.videoPlayer_.getVideoSize().width) + 'px';
};

/**
 * Select a menu item. Either called by selecting
 * a menu item or programmatically by js on the page.
 */
mirosubs.widget.Widget.prototype.selectMenuItem = function(selection, opt_languageCode) {
    var s = mirosubs.widget.DropDown.Selection;
    var subController = this.controller_.getSubtitleController();
    var playController = this.controller_.getPlayController();
    if (selection == s.ADD_LANGUAGE)
        subController.openNewLanguageDialog();
    else if (selection == s.IMPROVE_SUBTITLES)
        subController.openSubtitleDialog();
    else if (selection == s.SUBTITLE_HOMEPAGE)
        alert('subtitle homepage');
    else if (selection == s.SUBTITLES_OFF)
        playController.turnOffSubs();
    else if (selection == s.LANGUAGE_SELECTED)
        playController.languageSelected(opt_languageCode);
};
mirosubs.widget.Widget.prototype.playAt = function(time) {
    this.videoPlayer_.setPlayheadTime(time);
    this.videoPlayer_.play();
};<commit_msg>#15491, removed unnecessary braces<commit_after>// Universal Subtitles, universalsubtitles.org
//
// Copyright (C) 2010 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

goog.provide('mirosubs.widget.Widget');

/**
 * @constructor
 * @param {Object} widgetConfig parameter documentation is currenty in embed.js.
 */
mirosubs.widget.Widget = function(widgetConfig) {
    goog.ui.Component.call(this);

    /**
     * @type {string}
     */
    this.videoURL_ = widgetConfig['video_url'];
    this.alternateVideoURLs_ = widgetConfig['alternate_video_urls'];
    this.forceFormat_ = !!widgetConfig['force_format'];
    this.videoConfig_ = widgetConfig['video_config'];
    /**
     * If true, this is the equivalent of clicking on "Add subtitles"
     * if base state is null, or equivalent of clicking on "Improve
     * these subtitles" if base state is not null.
     * @type {boolean}
     */
    this.subtitleImmediately_ =
        !!widgetConfig['subtitle_immediately'];
    /**
     * If true, this is the equivalent of clicking on
     * "Add New Translation"
     * @type {boolean}
     */
    this.translateImmediately_ =
        !!widgetConfig['translate_immediately'];
    var baseState = widgetConfig['base_state'];
    if (baseState)
        this.baseState_ = new mirosubs.widget.BaseState(baseState);
};
goog.inherits(mirosubs.widget.Widget, goog.ui.Component);

mirosubs.widget.Widget.prototype.createDom = function() {
    mirosubs.widget.Widget.superClass_.createDom.call(this);
    this.addWidget_(this.getElement());
};

/**
 * @param {HTMLDivElement} el Just a blank div with class mirosubs-widget.
 */
mirosubs.widget.Widget.prototype.decorateInternal = function(el) {
    mirosubs.widget.Widget.superClass_.decorateInternal.call(this, el);
    this.addWidget_(el);
};

mirosubs.widget.Widget.prototype.createVideoPlayer_ = function(videoSource) {
    this.videoPlayer_ = videoSource.createPlayer();
    this.addChildAt(this.videoPlayer_, 0, true);
    this.setVideoDimensions_();
};

mirosubs.widget.Widget.prototype.findVideoSource_ = function() {
    if (this.alternateVideoURLs_ && this.alternateVideoURLs_.length > 0) {
        var mainVideoSpec = this.videoURL_;
        if (this.videoConfig_)
            mainVideoSpec = { 'url': this.videoURL_,
                              'config': this.videoConfig_ };
        return mirosubs.video.VideoSource.bestVideoSource(
            goog.array.concat(mainVideoSpec, this.alternateVideoURLs_));
    }
    else
        return mirosubs.video.VideoSource.videoSourceForURL(
            this.videoURL_, this.videoConfig_);
};

mirosubs.widget.Widget.prototype.isVideoSourceImmediatelyUsable_ =
    function()
{
    if (this.videoSource_ instanceof mirosubs.video.BlipTVPlaceholder)
        return false;
    if (this.forceFormat_ || goog.isDefAndNotNull(this.alternateVideoURLs_))
        return true;
    else {
        return !(this.videoSource_ instanceof mirosubs.video.Html5VideoSource)
                || mirosubs.video.supportsVideo();
    }
};

mirosubs.widget.Widget.prototype.addVideoLoadingPlaceholder_ =
    function(el)
{
    this.videoPlaceholder_ = this.getDomHelper().createDom(
        'div', 'mirosubs-videoLoading', 'Loading...');
    goog.dom.appendChild(el, this.videoPlaceholder_);
};

mirosubs.widget.Widget.prototype.addWidget_ = function(el) {
    try {
        this.videoSource_ = this.findVideoSource_();
    }
    catch (err) {
        // TODO: format this more.
        el.innerHTML = err.message;
        return;
    }
    if (this.isVideoSourceImmediatelyUsable_())
        this.createVideoPlayer_(this.videoSource_);
    else
        this.addVideoLoadingPlaceholder_(el);
    this.videoTab_ = new mirosubs.widget.VideoTab();
    var videoTabContainer = new goog.ui.Component();
    this.addChild(videoTabContainer, true);
    videoTabContainer.addChild(this.videoTab_, true);
    videoTabContainer.getElement().className =
        'mirosubs-videoTab-container';
    this.videoTab_.showLoading();
    var args = {
        'video_url': this.videoURL_,
        'is_remote': mirosubs.isFromDifferentDomain()
    };
    if (this.baseState_)
        args['base_state'] = this.baseState_.ORIGINAL_PARAM;
    mirosubs.Rpc.call(
        'show_widget', args,
        goog.bind(this.initializeState_, this),
        goog.bind(this.showWidgetError_, this));
};

mirosubs.widget.Widget.prototype.showWidgetError_ = function() {
    // call to show_widget timed out.
    if (!this.isVideoSourceImmediatelyUsable_()) {
        // waiting for video source from server.
        if (this.videoSource_ instanceof mirosubs.video.BlipTVPlaceholder) {
            // out of luck.

        }
        else {
            this.createVideoPlayer_(this.videoSource_);
        }
    }
    this.videoTab_.showError();
};

mirosubs.widget.Widget.prototype.initializeState_ = function(result) {
    if (!this.isVideoSourceImmediatelyUsable_()) {
        goog.dom.removeNode(this.videoPlaceholder_);
        var videoSource = mirosubs.video.VideoSource.bestVideoSource(
            result['video_urls']);
        if (goog.typeOf(videoSource) == goog.typeOf(this.videoSource_) &&
            this.videoConfig_)
            videoSource.setVideoConfig(this.videoConfig_);
        this.videoSource_ = videoSource;
        this.createVideoPlayer_(this.videoSource_);
    }

    this.controller_ = new mirosubs.widget.WidgetController(
        this.videoURL_, this.videoPlayer_, this.videoTab_);
    this.controller_.initializeState(result);

    var subController = this.controller_.getSubtitleController();

    if (this.subtitleImmediately_)
        goog.Timer.callOnce(
            goog.bind(subController.openSubtitleDialog, subController));
    else if (this.translateImmediately_)
        goog.Timer.callOnce(
            goog.bind(subController_.openNewLanguageDialog,
                      subController_));
};

mirosubs.widget.Widget.prototype.enterDocument = function() {
    mirosubs.widget.Widget.superClass_.enterDocument.call(this);
    this.setVideoDimensions_();
};

mirosubs.widget.Widget.prototype.setVideoDimensions_ = function() {
    if (!this.isInDocument() || !this.videoPlayer_)
        return;
    if (this.videoPlayer_.areDimensionsKnown())
        this.videoDimensionsKnown_();
    else
        this.getHandler().listen(
            this.videoPlayer_,
            mirosubs.video.AbstractVideoPlayer.EventType.DIMENSIONS_KNOWN,
            this.videoDimensionsKnown_);
};

mirosubs.widget.Widget.prototype.videoDimensionsKnown_ = function() {
    this.getElement().style.width =
        Math.round(this.videoPlayer_.getVideoSize().width) + 'px';
};

/**
 * Select a menu item. Either called by selecting
 * a menu item or programmatically by js on the page.
 */
mirosubs.widget.Widget.prototype.selectMenuItem = function(selection, opt_languageCode) {
    var s = mirosubs.widget.DropDown.Selection;
    var subController = this.controller_.getSubtitleController();
    var playController = this.controller_.getPlayController();
    if (selection == s.ADD_LANGUAGE)
        subController.openNewLanguageDialog();
    else if (selection == s.IMPROVE_SUBTITLES)
        subController.openSubtitleDialog();
    else if (selection == s.SUBTITLE_HOMEPAGE)
        alert('subtitle homepage');
    else if (selection == s.SUBTITLES_OFF)
        playController.turnOffSubs();
    else if (selection == s.LANGUAGE_SELECTED)
        playController.languageSelected(opt_languageCode);
};
mirosubs.widget.Widget.prototype.playAt = function(time) {
    this.videoPlayer_.setPlayheadTime(time);
    this.videoPlayer_.play();
};<|endoftext|>


<commit_before>(function($) {
    'use strict';

    // Create the demos slider
    var $list = $('.home-demos-list');
    if ($list.length) {
        $list.owlCarousel({
            lazyLoad: true
        });
        $list.css('height', 'auto');
    }

})(jQuery);
<commit_msg>Bug 1137020: Track homepage search with Optimizely<commit_after>(function($) {
    'use strict';

    // Create the demos slider
    var $list = $('.home-demos-list');
    if ($list.length) {
        $list.owlCarousel({
            lazyLoad: true
        });
        $list.css('height', 'auto');
    }

    // Track search submissions with Optimizely
    var $centerSearchBox = $('#home-search-form');
    if ($centerSearchBox) {
        $centerSearchBox.submit(function() {
            mdn.optimizely.push(['trackEvent', 'submit-homepage-search-form']);
        });
    }

})(jQuery);
<|endoftext|>


<commit_before>module("uce.file_upload", {teardown: function() {
    $('#files_uploaded').fileupload('destroy');
}});

test("create basic structure", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    ok($('#files_uploaded').hasClass('ui-widget'), 'class ui-widget');
    ok($('#files_uploaded').hasClass('ui-fileupload'), 'class ui-fileupload');
    equals($('#files_uploaded').find('.ui-fileupload-list').size(), 1);
    equals($('#files_uploaded').find('.ui-fileupload-list').children().size(), 0);
    equals($('#files_uploaded').find('.ui-fileupload-all').children().size(), 2);
    equals($('#files_uploaded > div .ui-fileupload-add').size(), 1);
    equals($('#files_uploaded').find('.ui-fileupload-preview').children().size(), 3);
    equals($('#files_uploaded').find('.ui-preview-toolbar').children().size(), 4);
    equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'block');
    equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'none');
});

test("destroy everything", function() {
    $('#files_uploaded').fileupload();
    $('#files_uploaded').fileupload("destroy");
    equals($('#files_uploaded').children().size(), 0);
    ok(!$('#files_uploaded').hasClass('ui-widget'), 'class ui-widget');
    ok(!$('#files_uploaded').hasClass('ui-fileupload'), 'class ui-fileupload');
});

jackTest("handle new file upload", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded')
        .fileupload({ucemeeting: ucemeeting})
        .fileupload('triggerUceEvent', Factories.createFileEvent({id : 'norris_pop_12.pdf',
                                                                   name : 'norris_pop.pdf',
                                                                   datetime : timestamp}));
    equals($('#files_uploaded ul > li').size(), 1);
    equals($('#files_uploaded ul > li:eq(0)').text(), 'norris_pop.pdf ' + date + ' by test_userDownload');
});

jackTest("handle new image upload", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded')
        .fileupload({ucemeeting: ucemeeting})
        .fileupload('triggerUceEvent', Factories.createFileEvent({id : 'norris_pop_12.jpg',
                                                                   name : 'norris_pop.jpg',
                                                                   mime : 'image/jpeg',
                                                                   datetime : timestamp}));
    equals($('#files_uploaded ul > li').size(), 1);
    equals($('#files_uploaded ul > li:eq(0)').text(), 'norris_pop.jpg ' + date + ' by test_userDownload | Open in the viewer');
});

jackTest("handle 2 files upload", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $([Factories.createFileEvent({datetime: timestamp}),
       Factories.createFileEvent({id: 'lee.pdf', name: 'lee.pdf', datetime: timestamp})]).each(function(i, item) {

        $('#files_uploaded').fileupload('triggerUceEvent', item);
    });
    equals($('#files_uploaded').find('ul > li').size(), 2);
    equals($('#files_uploaded').find('ul > li:eq(0)').text(), 'norris.pdf ' + date + ' by test_userDownload');
    equals($('#files_uploaded').find('ul > li:eq(1)').text(), 'lee.pdf ' + date + ' by test_userDownload');
});

test("handle conversion done event", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $([Factories.createFileEvent({eventId: "id_upload_event", datetime: timestamp}),
       Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: {"0": "page_1.jpg"}}),
       Factories.createFileEvent({id: "page_1.jpg", name: "page_1.jpg", from: "document"})]).each(function(i, item) {
           $('#files_uploaded').fileupload('triggerUceEvent', item);
    });
    equals($('#files_uploaded').find('ul > li:eq(0)').text(), 'norris.pdf ' + date + ' by test_userDownload | Open in the viewer | Share');
    equals($('#files_uploaded').find('ul > li:eq(1)').text(), '');
});

jackTest("when clicking the share link, fire an event", function() {
    var timestamp = new Date().getTime();
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event", datetime: timestamp}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg"]}),
         Factories.createFileEvent({id: "page_1.jpg", name: "page_1.jpg", from: "document", datetime: timestamp})];

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    jack.expect("ucemeeting.push")
        .exactly("1 time")
        .returnValue('#');

    $('#files_uploaded').find('ul > li a.ui-fileupload.ui-share-link').click();
});

test("when clicking the view link, launch preview", function() {
    var timestamp = new Date().getTime();
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event", datetime: timestamp}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg"]}),
         Factories.createFileEvent({id: "page_1.jpg", name: "page_1.jpg", from: "document", datetime: timestamp})];

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    $('#files_uploaded').find('ul > li a.ui-fileupload.ui-view-link').click(function() {
        equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'none');
        equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'block');
    });
});

test("can hide upload button", function() {
    $('#files_uploaded').fileupload({upload: false});
    equals($('#files_uploaded .ui-fileupload-add').size(), 0);
});

test("can hide upload button after init", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    equals($('#files_uploaded .ui-fileupload-add').size(), 1);
    $('#files_uploaded').fileupload("option", "upload", false);
    equals($('#files_uploaded .ui-fileupload-add').css('display'), 'none');
    $('#files_uploaded').fileupload("option", "upload", true);
    equals($('#files_uploaded .ui-fileupload-add').css('display'), 'block');
});

test("clear file to share", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('toto');
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $('#files_uploaded').fileupload('triggerUceEvent', Factories.createFileEvent());
    $('#files_uploaded').fileupload("clear");
    equals($('#files_uploaded').find('ul > li').size(), 0);
});

test("view all", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $('#files_uploaded').fileupload("viewAll");
    equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'block');
    equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'none');
});

test("view preview", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $('#files_uploaded').fileupload("viewPreview");
    equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'none');
    equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'block');
});

jackTest("handle roster delete event", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileUploadUrl', 'getFileDownloadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event"}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg",
                                                                                "page_2.jpg"]}),
         Factories.createFileEvent({id: "page_1.jpg", name: "page_1.jpg", from: "document"}),
         Factories.createFileEvent({id: "page_2.jpg", name: "page_2.jpg", from: "document"})];

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    $('#files_uploaded').fileupload('triggerUceEvent', Factories.createDocumentShareStartEvent({id : 'norris.pdf'}));
    $('#files_uploaded').fileupload('triggerUceEvent', Factories.createRosterDeleteEvent({id : 'chuck_in_roster_deletion'}));
    equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'block');
    equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'none');
});

jackTest("when click on next, go to the right preview page", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileUploadUrl', 'getFileDownloadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event"}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg",
                                                                                "page_2.jpg"]})]
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    $('#files_uploaded .ui-preview-link').click();
    $('#files_uploaded .ui-button-next').click();

    equals($('#files_uploaded .ui-fileupload.ui-selector-current').text(), "2", "The current page");
});

test("when click on previous, go to the right preview page", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileUploadUrl', 'getFileDownloadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event"}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg",
                                                                                "page_2.jpg",
                                                                                "page_3.jpg"]})]
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    $('#files_uploaded .ui-preview-link').click();
    $('#files_uploaded .ui-button-next').click();
    $('#files_uploaded .ui-button-next').click();
    $('#files_uploaded .ui-button-previous').click();

    equals($('#files_uploaded .ui-fileupload.ui-selector-current').text(), "2", "The current page");
});

test("when click on stop, hide preview", function() {
    $('#files_uploaded .ui-button-stop').click();

});

<commit_msg>File Upload: Remove a junk test.<commit_after>module("uce.file_upload", {teardown: function() {
    $('#files_uploaded').fileupload('destroy');
}});

test("create basic structure", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    ok($('#files_uploaded').hasClass('ui-widget'), 'class ui-widget');
    ok($('#files_uploaded').hasClass('ui-fileupload'), 'class ui-fileupload');
    equals($('#files_uploaded').find('.ui-fileupload-list').size(), 1);
    equals($('#files_uploaded').find('.ui-fileupload-list').children().size(), 0);
    equals($('#files_uploaded').find('.ui-fileupload-all').children().size(), 2);
    equals($('#files_uploaded > div .ui-fileupload-add').size(), 1);
    equals($('#files_uploaded').find('.ui-fileupload-preview').children().size(), 3);
    equals($('#files_uploaded').find('.ui-preview-toolbar').children().size(), 4);
    equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'block');
    equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'none');
});

test("destroy everything", function() {
    $('#files_uploaded').fileupload();
    $('#files_uploaded').fileupload("destroy");
    equals($('#files_uploaded').children().size(), 0);
    ok(!$('#files_uploaded').hasClass('ui-widget'), 'class ui-widget');
    ok(!$('#files_uploaded').hasClass('ui-fileupload'), 'class ui-fileupload');
});

jackTest("handle new file upload", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded')
        .fileupload({ucemeeting: ucemeeting})
        .fileupload('triggerUceEvent', Factories.createFileEvent({id : 'norris_pop_12.pdf',
                                                                   name : 'norris_pop.pdf',
                                                                   datetime : timestamp}));
    equals($('#files_uploaded ul > li').size(), 1);
    equals($('#files_uploaded ul > li:eq(0)').text(), 'norris_pop.pdf ' + date + ' by test_userDownload');
});

jackTest("handle new image upload", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded')
        .fileupload({ucemeeting: ucemeeting})
        .fileupload('triggerUceEvent', Factories.createFileEvent({id : 'norris_pop_12.jpg',
                                                                   name : 'norris_pop.jpg',
                                                                   mime : 'image/jpeg',
                                                                   datetime : timestamp}));
    equals($('#files_uploaded ul > li').size(), 1);
    equals($('#files_uploaded ul > li:eq(0)').text(), 'norris_pop.jpg ' + date + ' by test_userDownload | Open in the viewer');
});

jackTest("handle 2 files upload", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $([Factories.createFileEvent({datetime: timestamp}),
       Factories.createFileEvent({id: 'lee.pdf', name: 'lee.pdf', datetime: timestamp})]).each(function(i, item) {

        $('#files_uploaded').fileupload('triggerUceEvent', item);
    });
    equals($('#files_uploaded').find('ul > li').size(), 2);
    equals($('#files_uploaded').find('ul > li:eq(0)').text(), 'norris.pdf ' + date + ' by test_userDownload');
    equals($('#files_uploaded').find('ul > li:eq(1)').text(), 'lee.pdf ' + date + ' by test_userDownload');
});

test("handle conversion done event", function() {
    var timestamp = new Date().getTime();
    var date = $.strftime('%m-%d-%y', timestamp);
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $([Factories.createFileEvent({eventId: "id_upload_event", datetime: timestamp}),
       Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: {"0": "page_1.jpg"}}),
       Factories.createFileEvent({id: "page_1.jpg", name: "page_1.jpg", from: "document"})]).each(function(i, item) {
           $('#files_uploaded').fileupload('triggerUceEvent', item);
    });
    equals($('#files_uploaded').find('ul > li:eq(0)').text(), 'norris.pdf ' + date + ' by test_userDownload | Open in the viewer | Share');
    equals($('#files_uploaded').find('ul > li:eq(1)').text(), '');
});

jackTest("when clicking the share link, fire an event", function() {
    var timestamp = new Date().getTime();
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event", datetime: timestamp}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg"]}),
         Factories.createFileEvent({id: "page_1.jpg", name: "page_1.jpg", from: "document", datetime: timestamp})];

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    jack.expect("ucemeeting.push")
        .exactly("1 time")
        .returnValue('#');

    $('#files_uploaded').find('ul > li a.ui-fileupload.ui-share-link').click();
});

test("when clicking the view link, launch preview", function() {
    var timestamp = new Date().getTime();
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event", datetime: timestamp}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg"]}),
         Factories.createFileEvent({id: "page_1.jpg", name: "page_1.jpg", from: "document", datetime: timestamp})];

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    $('#files_uploaded').find('ul > li a.ui-fileupload.ui-view-link').click(function() {
        equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'none');
        equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'block');
    });
});

test("can hide upload button", function() {
    $('#files_uploaded').fileupload({upload: false});
    equals($('#files_uploaded .ui-fileupload-add').size(), 0);
});

test("can hide upload button after init", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    equals($('#files_uploaded .ui-fileupload-add').size(), 1);
    $('#files_uploaded').fileupload("option", "upload", false);
    equals($('#files_uploaded .ui-fileupload-add').css('display'), 'none');
    $('#files_uploaded').fileupload("option", "upload", true);
    equals($('#files_uploaded .ui-fileupload-add').css('display'), 'block');
});

test("clear file to share", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('toto');
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $('#files_uploaded').fileupload('triggerUceEvent', Factories.createFileEvent());
    $('#files_uploaded').fileupload("clear");
    equals($('#files_uploaded').find('ul > li').size(), 0);
});

test("view all", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $('#files_uploaded').fileupload("viewAll");
    equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'block');
    equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'none');
});

test("view preview", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileDownloadUrl', 'getFileUploadUrl']);
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});
    $('#files_uploaded').fileupload("viewPreview");
    equals($("#files_uploaded").find(".ui-fileupload-all").css('display'), 'none');
    equals($("#files_uploaded").find(".ui-fileupload-preview").css('display'), 'block');
});

jackTest("when click on next, go to the right preview page", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileUploadUrl', 'getFileDownloadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event"}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg",
                                                                                "page_2.jpg"]})]
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    $('#files_uploaded .ui-preview-link').click();
    $('#files_uploaded .ui-button-next').click();

    equals($('#files_uploaded .ui-fileupload.ui-selector-current').text(), "2", "The current page");
});

test("when click on previous, go to the right preview page", function() {
    var ucemeeting = jack.create("ucemeeting", ['bind', 'getFileUploadUrl', 'getFileDownloadUrl', 'push']);
    var events =
        [Factories.createFileEvent({eventId: "id_upload_event"}),
         Factories.createConversionDoneEvent({parent: 'id_upload_event', pages: ["page_1.jpg",
                                                                                "page_2.jpg",
                                                                                "page_3.jpg"]})]
    $('#files_uploaded').fileupload({ucemeeting: ucemeeting});

    jack.expect("ucemeeting.getFileDownloadUrl")
        .atLeast("1 time")
        .returnValue('#');

    $(events).each(function(index, event) {
           $('#files_uploaded').fileupload('triggerUceEvent', event);
    });

    $('#files_uploaded .ui-preview-link').click();
    $('#files_uploaded .ui-button-next').click();
    $('#files_uploaded .ui-button-next').click();
    $('#files_uploaded .ui-button-previous').click();

    equals($('#files_uploaded .ui-fileupload.ui-selector-current').text(), "2", "The current page");
});

test("when click on stop, hide preview", function() {
    $('#files_uploaded .ui-button-stop').click();

});

<|endoftext|>