<commit_before>$(function() {
  var once = false;

  var img = "";
  // RAILS 3.0 USERS -> Please delete the above line and uncomment the bottom line
  // ensure that the image directory matches
  // var img = "";

  var navbar = $(".pagination.alpha a");
  // Pick the handler list: just a quick check for the jQuery version (see here: http://bugs.jquery.com/ticket/10589)
  var handlers = navbar.data ? navbar.data('events') : jQuery._data(navbar[0], 'events');

  if (!handlers || -1 !== $.inArray(onNavbarClick, handlers.click)) {
      $(document).on("click", ".pagination.alpha a", onNavbarClick);
  }

  function onNavbarClick(e) {
      e.preventDefault();
      var url = location.href,
      letter = $(this).data("letter");
      if (/letter/.test(url)) {
          url = url.replace(/letter=[^&]*/, "letter=" + letter);
      }
      else {
          if (/\?/.test(url)) {
              url += "&letter=" + letter;
          }
          else {
              url += "?letter=" + letter;
          }
      }
      $(".pagination").html(img);
      //$.load(url + " #pagination_table");
      $.get(url, function(result) {
          $(".pagination").html($(".pagination", result).html());
          $("#pagination_table").html($("#pagination_table", result).html());
      });
      history.pushState(null, document.title, url);
  }

   // let navigate the browser throught the ajax history
  $(window).bind("popstate", function() {
    if (once) {
      $(".pagination").html(img);
      $.get(location.href, function(result) {
        $(".pagination").html($(".pagination", result).html());
          $("#pagination_table").html($("#pagination_table", result).html());
        });
      } else {
        once = true;
      }
  });

});
<commit_msg>Make the history binding happen only once<commit_after>$(function() {
  var once = false;

  var img = "";
  // RAILS 3.0 USERS -> Please delete the above line and uncomment the bottom line
  // ensure that the image directory matches
  // var img = "";

  var navbar = $(".pagination.alpha a");
  // Pick the handler list: just a quick check for the jQuery version (see here: http://bugs.jquery.com/ticket/10589)
  var handlers = navbar.data ? navbar.data('events') : jQuery._data(navbar[0], 'events');

  if (!handlers || -1 !== $.inArray(onNavbarClick, handlers.click)) {
      $(document).on("click", ".pagination.alpha a", onNavbarClick);
      bindPopState();
  }

  function onNavbarClick(e) {
      e.preventDefault();
      var url = location.href,
      letter = $(this).data("letter");
      if (/letter/.test(url)) {
          url = url.replace(/letter=[^&]*/, "letter=" + letter);
      }
      else {
          if (/\?/.test(url)) {
              url += "&letter=" + letter;
          }
          else {
              url += "?letter=" + letter;
          }
      }
      $(".pagination").html(img);
      //$.load(url + " #pagination_table");
      $.get(url, function(result) {
          $(".pagination").html($(".pagination", result).html());
          $("#pagination_table").html($("#pagination_table", result).html());
      });
      history.pushState(null, document.title, url);
  }

  // let navigate the browser throught the ajax history
  function bindPopState(){
    $(window).bind("popstate", function() {
      if (once) {
        $(".pagination").html(img);
        $.get(location.href, function(result) {
          $(".pagination").html($(".pagination", result).html());
            $("#pagination_table").html($("#pagination_table", result).html());
          });
        } else {
          once = true;
        }
    });
  }

});
<|endoftext|>


<commit_before>var _ = require('lodash'),
    expect = require('expect.js'),
    QueryParam = require('../../').QueryParam,
    rawQueryStrings = require('../fixtures/index').rawQueryStrings;

/* global describe, it */
describe('QueryParam', function () {
    describe('construction', function () {
        var qp = new QueryParam({
            key: null,
            value: null
        });

        expect(qp).to.be.ok();
        expect(qp).to.have.property('key', null);
        expect(qp).to.have.property('value', null);

        expect(qp.toString()).to.be('');
    });

    rawQueryStrings.forEach(function (rawQueryString) {
        describe(rawQueryString, function () {
            it('should be parsed properly', function () {
                var params = QueryParam.parse(rawQueryString);
                expect(params.length).to.be(4);
            });

            it('should be unparsed properly', function () {
                var params = QueryParam.parse(rawQueryString),
                    paramStr = QueryParam.unparse(params);
                expect(paramStr).to.eql(rawQueryString);
            });
        });
    });

    it('should not url encode by default', function () {
        var rawQueryString = 'x=y%z',
            params = QueryParam.parse(rawQueryString),
            paramStr = QueryParam.unparse(params);
        expect(paramStr).to.eql(rawQueryString);
    });

    it('should url encode if explicitly asked to', function () {
        var rawQueryString = 'x=y%z',
            params = QueryParam.parse(rawQueryString),
            paramStr = QueryParam.unparse(params, { encode: true });
        expect(paramStr).to.eql('x=y%25z');
    });

    it('should be able to unparse when values are given as an object', function () {
        var params = {
            a: 'a',
            b: 'b'
        };

        expect(QueryParam.unparse(params)).to.eql('a=a&b=b');
    });

    describe('integrity', function () {
        // key is what the string representation should be, value is the parsed representation.
        var testCases = {
            'a=b&c': [
                { key: 'a', value: 'b' },
                { key: 'c', value: null }
            ],
            'a=b&c=': [
                { key: 'a', value: 'b' },
                { key: 'c', value: '' }
            ],
            'a=b&c=&d=e': [
                { key: 'a', value: 'b' },
                { key: 'c', value: '' },
                { key: 'd', value: 'e' }
            ],
            'a=b&c&d=e': [
                { key: 'a', value: 'b' },
                { key: 'c', value: null },
                { key: 'd', value: 'e' }
            ],
            'a=b&a=c': [
                { key: 'a', value: 'b' },
                { key: 'a', value: 'c' }
            ],
            'a=b&a': [
                { key: 'a', value: 'b' },
                { key: 'a', value: null }
            ],
            'a=b&=cd': [
                { key: 'a', value: 'b' },
                { key: '', value: 'cd' }
            ],
            'a=b&=&': [
                { key: 'a', value: 'b' },
                { key: '', value: '' },
                { key: '', value: null }
            ],
            'a=b&&': [
                { key: 'a', value: 'b' },
                { key: null, value: null },
                { key: '', value: null }
            ],
            'a=b&&c=d': [
                { key: 'a', value: 'b' },
                { key: null, value: null },
                { key: 'c', value: 'd' }
            ]
        };

        _.forOwn(testCases, function (array, string) {
            describe(string, function () {
                it('parse', function () {
                    expect(QueryParam.parse(string)).to.eql(array);
                });

                it('unparse', function () {
                    expect(QueryParam.unparse(array)).to.eql(string);
                });
            });
        });
    });

    describe('encoding', function () {
        it('a=b{{c}}', function () {
            var parsed = [
                { key: 'a', value: 'c{{b}}' },
                { key: 'c', value: 'd' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=c{{b}}&c=d');
        });

        it('a=обязательный&c=d', function () {
            var parsed = [
                { key: 'a', value: 'обязательный' },
                { key: 'c', value: 'd' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=%D0%BE%D0%B1%D1%8F%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9&c=d');
        });

        it('email=foo+bar-xyz@gmail.com', function () {
            var parsed = [
                { key: 'email', value: 'foo+bar-xyz@gmail.com' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('email=foo+bar-xyz@gmail.com');
        });

        it('pre encoded text( must avoid double encoding) - "email=foo%2Bbar%40domain.com"', function () {
            var parsed = [
                { key: 'email', value: 'foo%2Bbar%40domain.com' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('email=foo%2Bbar%40domain.com');
        });

        it('multibyte character - "multibyte=𝌆"', function () {
            var parsed = [
                { key: 'multibyte', value: '𝌆' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('multibyte=%F0%9D%8C%86');
        });

        it('pre-encoded multibyte character - "multibyte=%F0%9D%8C%86"', function () {
            var parsed = [
                { key: 'multibyte', value: '%F0%9D%8C%86' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('multibyte=%F0%9D%8C%86');
        });

        it('encoding percentage - "charwithPercent=%foo"', function () {
            var parsed = [
                { key: 'multibyte', value: '%foo' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('multibyte=%25foo');
        });

        it('a[0]=foo&a[1]=bar', function () {
            var parsed = [
                { key: 'a[0]', value: 'foo' },
                { key: 'a[1]', value: 'bar' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('a[0]=foo&a[1]=bar');
        });

        it('encodes ( and )- "a=foo(a)"', function () {
            var parsed = [
                { key: 'a', value: 'foo(a)' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=foo%28a%29');
        });

        it('Russian - "a=Привет Почтальон"', function () {
            var parsed = [
                { key: 'a', value: 'Привет Почтальон' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be(
                'a=%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD'
            );
        });

        it('Chinese- "a=你好"', function () {
            var parsed = [
                { key: 'a', value: '你好' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=%E4%BD%A0%E5%A5%BD');
        });

        it('Japanese- "a=ハローポストマン"', function () {
            var parsed = [
                { key: 'a', value: 'ハローポストマン' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=%E3%83%8F%E3%83%AD%E3%83%BC%E3%83%9D%E3%82%B9%E3%83%88%E3%83%9E%E3%83%B3');
        });

        it('Partial Russian - "a=Hello Почтальон"', function () {
            var parsed = [
                { key: 'a', value: 'Hello Почтальон' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD');
        });

        it('pre encoded russian text - a=Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD', function () {
            var parsed = [
                { key: 'a', value: 'Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD');
        });
    });
});
<commit_msg>test(unit): Added QueryParam unit tests :white_check_mark:<commit_after>var _ = require('lodash'),
    expect = require('expect.js'),
    QueryParam = require('../../').QueryParam,
    rawQueryStrings = require('../fixtures/index').rawQueryStrings;

/* global describe, it */
describe('QueryParam', function () {
    describe('construction', function () {
        it('should handle null keys and values correctly', function () {
            var qp = new QueryParam({
                key: null,
                value: null
            });

            expect(qp).to.be.ok();
            expect(qp).to.have.property('key', null);
            expect(qp).to.have.property('value', null);

            expect(qp.toString()).to.be('');
            expect(qp.valueOf()).to.be('');
        });

        it('should handle string input correctly', function () {
            var qp = new QueryParam('foo=bar');

            expect(qp).to.be.ok();
            expect(qp).to.have.property('key', 'foo');
            expect(qp).to.have.property('value', 'bar');
        });
    });

    describe('static helpers', function () {
        describe('.parse', function () {
            it('should return an empty array for non string arguments', function () {
                expect(QueryParam.parse()).to.eql([]);
                expect(QueryParam.parse([])).to.eql([]);
                expect(QueryParam.parse({})).to.eql([]);
                expect(QueryParam.parse(null)).to.eql([]);
            });
        });

        describe('.parseSingle', function () {
            it('should return null as a value if the query param string does not contain `=`', function () {
                var result = QueryParam.parseSingle({
                    value: 'foo',
                    substr: function () {
                        return this.value;
                    }
                });

                expect(result).to.eql({
                    key: 'foo',
                    value: null
                });
            });
        });

        describe('.unparse', function () {
            it('should bail out of the provided set of params is falsy', function () {
                expect(QueryParam.unparse()).to.be('');
            });
        });

        describe('.unparseSingle', function () {
            it('should return an empty string for non object arguments', function () {
                expect(QueryParam.unparseSingle()).to.be('');
                expect(QueryParam.unparseSingle([])).to.be('');
            });

            it('should return an empty string for undefined values', function () {
                expect(QueryParam.unparseSingle({})).to.be('');
                expect(QueryParam.unparseSingle({ key: 'foo' })).to.be('');
            });

            it('should encode keys when value is null and encode is true', function () {
                expect(QueryParam.unparseSingle({ key: ' ', value: null }, true)).to.be('%20');
                expect(QueryParam.unparseSingle({ key: 'foo', value: null }, true)).to.be('foo');
            });
        });
    });

    rawQueryStrings.forEach(function (rawQueryString) {
        describe(rawQueryString, function () {
            it('should be parsed properly', function () {
                var params = QueryParam.parse(rawQueryString);
                expect(params.length).to.be(4);
            });

            it('should be unparsed properly', function () {
                var params = QueryParam.parse(rawQueryString),
                    paramStr = QueryParam.unparse(params);
                expect(paramStr).to.eql(rawQueryString);
            });
        });
    });

    it('should not url encode by default', function () {
        var rawQueryString = 'x=y%z',
            params = QueryParam.parse(rawQueryString),
            paramStr = QueryParam.unparse(params);
        expect(paramStr).to.eql(rawQueryString);
    });

    it('should url encode if explicitly asked to', function () {
        var rawQueryString = 'x=y%z',
            params = QueryParam.parse(rawQueryString),
            paramStr = QueryParam.unparse(params, { encode: true });
        expect(paramStr).to.eql('x=y%25z');
    });

    it('should be able to unparse when values are given as an object', function () {
        var params = {
            a: 'a',
            b: 'b'
        };

        expect(QueryParam.unparse(params)).to.eql('a=a&b=b');
    });

    describe('integrity', function () {
        // key is what the string representation should be, value is the parsed representation.
        var testCases = {
            'a=b&c': [
                { key: 'a', value: 'b' },
                { key: 'c', value: null }
            ],
            'a=b&c=': [
                { key: 'a', value: 'b' },
                { key: 'c', value: '' }
            ],
            'a=b&c=&d=e': [
                { key: 'a', value: 'b' },
                { key: 'c', value: '' },
                { key: 'd', value: 'e' }
            ],
            'a=b&c&d=e': [
                { key: 'a', value: 'b' },
                { key: 'c', value: null },
                { key: 'd', value: 'e' }
            ],
            'a=b&a=c': [
                { key: 'a', value: 'b' },
                { key: 'a', value: 'c' }
            ],
            'a=b&a': [
                { key: 'a', value: 'b' },
                { key: 'a', value: null }
            ],
            'a=b&=cd': [
                { key: 'a', value: 'b' },
                { key: '', value: 'cd' }
            ],
            'a=b&=&': [
                { key: 'a', value: 'b' },
                { key: '', value: '' },
                { key: '', value: null }
            ],
            'a=b&&': [
                { key: 'a', value: 'b' },
                { key: null, value: null },
                { key: '', value: null }
            ],
            'a=b&&c=d': [
                { key: 'a', value: 'b' },
                { key: null, value: null },
                { key: 'c', value: 'd' }
            ]
        };

        _.forOwn(testCases, function (array, string) {
            describe(string, function () {
                it('parse', function () {
                    expect(QueryParam.parse(string)).to.eql(array);
                });

                it('unparse', function () {
                    expect(QueryParam.unparse(array)).to.eql(string);
                });
            });
        });
    });

    describe('encoding', function () {
        it('a=b{{c}}', function () {
            var parsed = [
                { key: 'a', value: 'c{{b}}' },
                { key: 'c', value: 'd' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=c{{b}}&c=d');
        });

        it('a=обязательный&c=d', function () {
            var parsed = [
                { key: 'a', value: 'обязательный' },
                { key: 'c', value: 'd' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=%D0%BE%D0%B1%D1%8F%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9&c=d');
        });

        it('email=foo+bar-xyz@gmail.com', function () {
            var parsed = [
                { key: 'email', value: 'foo+bar-xyz@gmail.com' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('email=foo+bar-xyz@gmail.com');
        });

        it('pre encoded text( must avoid double encoding) - "email=foo%2Bbar%40domain.com"', function () {
            var parsed = [
                { key: 'email', value: 'foo%2Bbar%40domain.com' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('email=foo%2Bbar%40domain.com');
        });

        it('multibyte character - "multibyte=𝌆"', function () {
            var parsed = [
                { key: 'multibyte', value: '𝌆' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('multibyte=%F0%9D%8C%86');
        });

        it('pre-encoded multibyte character - "multibyte=%F0%9D%8C%86"', function () {
            var parsed = [
                { key: 'multibyte', value: '%F0%9D%8C%86' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('multibyte=%F0%9D%8C%86');
        });

        it('encoding percentage - "charwithPercent=%foo"', function () {
            var parsed = [
                { key: 'multibyte', value: '%foo' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('multibyte=%25foo');
        });

        it('a[0]=foo&a[1]=bar', function () {
            var parsed = [
                { key: 'a[0]', value: 'foo' },
                { key: 'a[1]', value: 'bar' }
            ];
            expect(QueryParam.unparse(parsed)).to.be('a[0]=foo&a[1]=bar');
        });

        it('encodes ( and )- "a=foo(a)"', function () {
            var parsed = [
                { key: 'a', value: 'foo(a)' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=foo%28a%29');
        });

        it('Russian - "a=Привет Почтальон"', function () {
            var parsed = [
                { key: 'a', value: 'Привет Почтальон' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be(
                'a=%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD'
            );
        });

        it('Chinese- "a=你好"', function () {
            var parsed = [
                { key: 'a', value: '你好' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=%E4%BD%A0%E5%A5%BD');
        });

        it('Japanese- "a=ハローポストマン"', function () {
            var parsed = [
                { key: 'a', value: 'ハローポストマン' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=%E3%83%8F%E3%83%AD%E3%83%BC%E3%83%9D%E3%82%B9%E3%83%88%E3%83%9E%E3%83%B3');
        });

        it('Partial Russian - "a=Hello Почтальон"', function () {
            var parsed = [
                { key: 'a', value: 'Hello Почтальон' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD');
        });

        it('pre encoded russian text - a=Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD', function () {
            var parsed = [
                { key: 'a', value: 'Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD' }
            ];
            expect(QueryParam.unparse(parsed, {
                encode: true
            })).to.be('a=Hello%20%D0%9F%D0%BE%D1%87%D1%82%D0%B0%D0%BB%D1%8C%D0%BE%D0%BD');
        });
    });
});
<|endoftext|>


<commit_before>/*global
 $,
 jQuery,
 error,
 success,
 endless,
 ajax,
 templateHelper,
 Routing,
 appLocale,
 exports,
 module,
 require,
 define
 */
/*jslint nomen: true */                 /* Tolerate dangling _ in identifiers */
/*jslint vars: true */           /* Tolerate many var statements per function */
/*jslint white: true */                       /* tolerate messy whithe spaces */
/*jslint browser: true */
/*jslint devel: true */                         /* Assume console, alert, ... */
/*jslint windows: true */               /* Assume window object (for browsers)*/

/*******************************************************************************
 * Class dependencies:                                                         *
 *      jquery > 1.8.3                                                         *
 *      isotope                                                                *
 *      jsrender                                                               *
 *      jsviews                                                                *
 * external dependencies:                                                      *
 *      templateHelper                                                         *
 *      base genericAction                                                     *
 *      ExposeTranslation                                                      *
 *      FOS Routing                                                            *
 ******************************************************************************/

$(document).ready(function () {
    "use strict";
    var pluginName = "fwHomeGallery";
    var defaults = {
        videoCategory: null,
        videoFeed: Routing.generate(appLocale + '_home_ajaxfilter'),
        imteStyle: {
            'width': '16%',
            'height': '160px',
            'margin-top': '5px',
            'margin-bottom': '5px',
            'border': '1px solid #333',
            'border-radius': '4px',
            'overflow': 'hidden'
        },
        itemSelector: '.video',
        feedSource: '',
        feedfilter: {}
    };
    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype = {
        init: function () {
            var that = this;
            var self = $(that.element);
            self.bind("destroyed", $.proxy(that.teardown, that));
            self.addClass(that._name);

            return true;
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
            return true;
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            that.unbind();
            that.element = null;
            return that.element;
        },
        bind: function() { },
        unbind: function() { }
    };
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };
});

$(document).ready(function () {
    "use strict";
    var pluginName = "fwHomeThumbs";
    var defaults = {
        videoCategory: null,
        videoFeed: Routing.generate(appLocale + '_home_ajaxfilter'),
        page: 1,
        block: null
    };
    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype = {
        init: function () {
            var that = this;
            var self = $(that.element);
            self.bind("destroyed", $.proxy(that.teardown, that));
            self.addClass(that._name);
            self.empty();
            that.appendThumbs();

            $('section.' + that.options.block + ' > .add-more').on('click', function(event){
                that.options.page += 1;
                var button = $(this);
                button.addClass('rotate');
                $.when(that.appendThumbs()).then(function(response){
                    button.removeClass('rotate');
                });
            });
            return true;
        },
        appendThumbs: function() {
            var that = this;
            var i = 0;
            var deferred = new jQuery.Deferred();
            console.log("adding thumbs")
            $.ajax({
                url: that.options.videoFeed,
                data: {
                    paginate:{
                        page: that.options.page,
                        block: that.options.block,
                        vc: that.options.videoCategory
                    }
                }
            }).then(function(response) {
                for(i in response.videos) {
                    if (response.videos.hasOwnProperty(i)) {
                        var video = response.videos[i];
                        $.when(templateHelper.htmlTemplate('video-home_element', video))
                            .then(function(response){
                                var $thumb = $(response).clone();
                                $(that.element).append($thumb);
                            });
                    }
                }
                return response.videos;
            }).done(function(videos){
                deferred.resolve(videos);
            }).fail(function(error){
                deferred.reject(new Error(error));
            });
            return deferred.promise();
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
            return true;
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            that.unbind();
            that.element = null;
            return that.element;
        },
        bind: function() { },
        unbind: function() { }
    };
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };
});
//Attach plugin to all matching element
$(document).ready(function () {
    "use strict";
    //$('section.highlights').fwHomeGallery({});
    $('section.popular > .videos-container').fwHomeThumbs({
        videoCategory: $('.filter-home').find('.active').attr('data-category-id'),
        block: 'popular'
    })

    $('section.followed > .videos-container').fwHomeThumbs({
        videoCategory: $('.filter-home').find('.active').attr('data-category-id'),
        block: 'followed'
    })
});

$(document).ready(function () {

    var $container = $('section.highlights');

    function appendFollowed(videoCategory) {
        var i = 0;
        var cnt = 0;
        var $container = $('section.followed > .videos-container');
        $container.empty();
        var feed = Routing.generate(appLocale + '_home_ajaxfilter');
        $.ajax({url: feed, data: {'vc': videoCategory}}).then(function(response){
            for(i in response.followed) {
                if (response.followed.hasOwnProperty(i)) {
                    var video = response.followed[i];
                    $thumb = $('

');
                    $.when(templateHelper.htmlTemplate('video-home_element', video))
                        .then(function(response){
                            $thumb = $(response).clone();
                            $container.append($thumb);
                        });
                }
            }
        });
    }

    function appendPopular(videoCategory) {
        var i = 0;
        var cnt = 0;
        var $container = $('section.popular > .videos-container');
        $container.empty();
        var feed = Routing.generate(appLocale + '_home_ajaxfilter');
        $.ajax({url: feed, data: {'vc': videoCategory}}).then(function(response){
            for(i in response.popular) {
                if (response.popular.hasOwnProperty(i)) {
                    var video = response.popular[i];
                    //console.log(video);
                    $thumb = $('

');
                    $.when(templateHelper.htmlTemplate('video-home_element', video))
                        .then(function(response){
                            $thumb = $(response).clone();
                            $container.append($thumb);;
                    });
                }
            }
        });
    }

    function makePackery(videoCategory) {
        var i = 0;
        var cnt = 0;
        var container = document.querySelector('section.highlights');
        var packery = new Packery( container, {
            itemSelector: '.video',
//            gutter: '25px',
            gutter: ".gutter-sizer",
            columnWidth: ".grid-sizer"
//            columnWidth: container.querySelector('.grid-sizer')
        });

        window.packery = packery;
        // ajax.genericAction('home_ajaxfilter', {paginate:{'page':1, 'block':'popular','vc': 6}}, function(r){console.log(r);});
        // $.ajax({url: Routing.generate('es_home_ajaxfilter'), data: {'vc': 1}}).then(function(r){console.log(r)})
        var feed = Routing.generate(appLocale + '_home_ajaxfilter');
        $.ajax({url: feed, data: {'vc': videoCategory}}).then(function(response){
            for(i in response.highlighted) {
                if (response.highlighted.hasOwnProperty(i)) {
                    var video = response.highlighted[i];

                    var thumb = document.createElement('article');
                    thumb.classList.add('video');

                    var image = document.createElement('img');

                    $thumb = $('

');

                    $.when(templateHelper.htmlTemplate('video-home_element', video))
                    .then(function(response){
                        $thumb = $(response).clone();

                        $thumb.addClass('video');
                        if(cnt === 1) {
                            $thumb.addClass('double');
                        }
                        cnt += 1;

                        $('section.highlights').append($thumb);
                        packery.appended($thumb);
                        packery.layout();
                    });
                }
            }
        });
    }

    function makeTags(channel, filter, page) {
        $.ajax({
            url: Routing.generate(appLocale + '_tag_ajaxgetusedinvideos'),
            data: {
                channel: channel,
                filter: filter,
                page: page
            }
        }).then(function(response){
            var i = 0;
            var tags = response.tags;
            var container = $('section.'+filter+'-tags > ul'); //$('section.followed-tags > ul');
            $(container).empty();
            for(i in tags){
                if (tags.hasOwnProperty(i)) {
                    $(container).append("
"+tags[i].title+"
");
                    if(i >= 4) {
                        break;
                    }
                }
            }
        })
    }

    var videoCategory = $('.filter-home').find('.active').attr('data-category-id');
    makePackery(videoCategory);
    //appendFollowed(videoCategory);
    //appendPopular(videoCategory);
    makeTags(videoCategory, 'popular', 1);
    makeTags(videoCategory, 'followed', 1);

    $('section.followed > .add-more').on('click', function(event){

        /*
        Routing.generate(appLocale + '_home_ajaxfilter')
        $.ajax({url: Routing.generate(appLocale + '_home_ajaxfilter'), data: {'vc': 6}}).then(function(response){console.log(response)})

        ajax.genericAction('home_ajaxfilter', {paginate:{'page':1, 'block':'popular','vc': 6}}, function(r){console.log(r);});

        $.ajax({url: Routing.generate(appLocale + '_home_ajaxfilter'), data: {paginate:{'page':1, 'block':'popular','vc': 6}}}).then(function(response){console.log(response)})

        */

    });
});<commit_msg>boton carga mas y pluginizado<commit_after>/*global
 $,
 jQuery,
 error,
 success,
 endless,
 ajax,
 templateHelper,
 Routing,
 appLocale,
 exports,
 module,
 require,
 define
 */
/*jslint nomen: true */                 /* Tolerate dangling _ in identifiers */
/*jslint vars: true */           /* Tolerate many var statements per function */
/*jslint white: true */                       /* tolerate messy whithe spaces */
/*jslint browser: true */
/*jslint devel: true */                         /* Assume console, alert, ... */
/*jslint windows: true */               /* Assume window object (for browsers)*/

/*******************************************************************************
 * Class dependencies:                                                         *
 *      jquery > 1.8.3                                                         *
 *      isotope                                                                *
 *      jsrender                                                               *
 *      jsviews                                                                *
 * external dependencies:                                                      *
 *      templateHelper                                                         *
 *      base genericAction                                                     *
 *      ExposeTranslation                                                      *
 *      FOS Routing                                                            *
 ******************************************************************************/

$(document).ready(function () {
    "use strict";
    var pluginName = "fwHomeGallery";
    var defaults = {
        videoCategory: null,
        videoFeed: Routing.generate(appLocale + '_home_ajaxfilter'),
        imteStyle: {
            'width': '16%',
            'height': '160px',
            'margin-top': '5px',
            'margin-bottom': '5px',
            'border': '1px solid #333',
            'border-radius': '4px',
            'overflow': 'hidden'
        },
        itemSelector: '.video',
        feedSource: '',
        feedfilter: {}
    };
    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype = {
        init: function () {
            var that = this;
            var self = $(that.element);
            self.bind("destroyed", $.proxy(that.teardown, that));
            self.addClass(that._name);

            return true;
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
            return true;
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            that.unbind();
            that.element = null;
            return that.element;
        },
        bind: function() { },
        unbind: function() { }
    };
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };
});

$(document).ready(function () {
    "use strict";
    var pluginName = "fwHomeThumbs";
    var defaults = {
        videoCategory: null,
        videoFeed: Routing.generate(appLocale + '_home_ajaxfilter'),
        page: 1,
        block: null
    };
    function Plugin(element, options) {
        this.element = element;
        this.options = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }
    Plugin.prototype = {
        init: function () {
            var that = this;
            var self = $(that.element);
            self.bind("destroyed", $.proxy(that.teardown, that));
            self.addClass(that._name);
            self.empty();
            that.appendThumbs();

            $('section.' + that.options.block + ' > .add-more').on('click', function(event){
                that.options.page += 1;
                var button = $(this);
                button.addClass('rotate');
                $.when(that.appendThumbs()).then(function(response){
                    button.removeClass('rotate');
                });
            });
            return true;
        },
        appendThumbs: function() {
            var that = this;
            var i = 0;
            var deferred = new jQuery.Deferred();
            console.log("adding thumbs")
            $.ajax({
                url: that.options.videoFeed,
                data: {
                    paginate:{
                        page: that.options.page,
                        block: that.options.block,
                        vc: that.options.videoCategory
                    }
                }
            }).then(function(response) {
                for(i in response.videos) {
                    if (response.videos.hasOwnProperty(i)) {
                        var video = response.videos[i];
                        $.when(templateHelper.htmlTemplate('video-home_element', video))
                        .then(function(response){
                            var $thumb = $(response).clone();
                            $thumb.hide().appendTo(that.element).fadeIn();
                        });
                    }
                }
                return response.videos;
            }).done(function(videos){
                deferred.resolve(videos);
            }).fail(function(error){
                deferred.reject(new Error(error));
            });
            return deferred.promise();
        },
        destroy: function() {
            var that = this;
            $(that.element).unbind("destroyed", that.teardown);
            that.teardown();
            return true;
        },
        teardown: function() {
            var that = this;
            $.removeData($(that.element)[0], that._name);
            $(that.element).removeClass(that._name);
            that.unbind();
            that.element = null;
            return that.element;
        },
        bind: function() { },
        unbind: function() { }
    };
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new Plugin(this, options));
            }
        });
    };
});
//Attach plugin to all matching element
$(document).ready(function () {
    "use strict";
    $('section.popular > .videos-container').fwHomeThumbs({
        videoCategory: $('.filter-home').find('.active').attr('data-category-id'),
        block: 'popular'
    })

    $('section.followed > .videos-container').fwHomeThumbs({
        videoCategory: $('.filter-home').find('.active').attr('data-category-id'),
        block: 'followed'
    })
});

$(document).ready(function () {

    var $container = $('section.highlights');

    function makePackery(videoCategory) {
        var i = 0;
        var cnt = 0;
        var container = document.querySelector('section.highlights');
        var packery = new Packery( container, {
            itemSelector: '.video',
//            gutter: '25px',
            gutter: ".gutter-sizer",
            columnWidth: ".grid-sizer"
//            columnWidth: container.querySelector('.grid-sizer')
        });

        window.packery = packery;
        // ajax.genericAction('home_ajaxfilter', {paginate:{'page':1, 'block':'popular','vc': 6}}, function(r){console.log(r);});
        // $.ajax({url: Routing.generate('es_home_ajaxfilter'), data: {'vc': 1}}).then(function(r){console.log(r)})
        var feed = Routing.generate(appLocale + '_home_ajaxfilter');
        $.ajax({url: feed, data: {'vc': videoCategory}}).then(function(response){
            for(i in response.highlighted) {
                if (response.highlighted.hasOwnProperty(i)) {
                    var video = response.highlighted[i];

                    var thumb = document.createElement('article');
                    thumb.classList.add('video');

                    var image = document.createElement('img');

                    $thumb = $('

');

                    $.when(templateHelper.htmlTemplate('video-home_element', video))
                    .then(function(response){
                        $thumb = $(response).clone();

                        $thumb.addClass('video');
                        if(cnt === 1) {
                            $thumb.addClass('double');
                        }
                        cnt += 1;

                        $('section.highlights').append($thumb);
                        packery.appended($thumb);
                        packery.layout();
                    });
                }
            }
        });
    }

    function makeTags(channel, filter, page) {
        $.ajax({
            url: Routing.generate(appLocale + '_tag_ajaxgetusedinvideos'),
            data: {
                channel: channel,
                filter: filter,
                page: page
            }
        }).then(function(response){
            var i = 0;
            var tags = response.tags;
            var container = $('section.'+filter+'-tags > ul'); //$('section.followed-tags > ul');
            $(container).empty();
            for(i in tags){
                if (tags.hasOwnProperty(i)) {
                    $(container).append("
"+tags[i].title+"
");
                    if(i >= 4) {
                        break;
                    }
                }
            }
        })
    }

    var videoCategory = $('.filter-home').find('.active').attr('data-category-id');
    makePackery(videoCategory);
    //appendFollowed(videoCategory);
    //appendPopular(videoCategory);
    makeTags(videoCategory, 'popular', 1);
    makeTags(videoCategory, 'followed', 1);

    $('section.followed > .add-more').on('click', function(event){

        /*
        Routing.generate(appLocale + '_home_ajaxfilter')
        $.ajax({url: Routing.generate(appLocale + '_home_ajaxfilter'), data: {'vc': 6}}).then(function(response){console.log(response)})

        ajax.genericAction('home_ajaxfilter', {paginate:{'page':1, 'block':'popular','vc': 6}}, function(r){console.log(r);});

        $.ajax({url: Routing.generate(appLocale + '_home_ajaxfilter'), data: {paginate:{'page':1, 'block':'popular','vc': 6}}}).then(function(response){console.log(response)})

        */

    });
});<|endoftext|>


<commit_before>const R = require('ramda')

const fileStr = lines => R.filter(R.identity, lines).join("\n")
const reactImports = [
  `import * as React from 'react'`,
  `import * as R     from 'ramda'`,
]

module.exports = {

  'index.tsx': c => fileStr(R.concat(reactImports, [
    c.hasStyles && `import * as classnames from 'classnames'\n`,
    c.hasStyles && `const s = require('./style.css')\n`,
    `export const ${c.moduleName.camel} = (props) => (`,
    `  <div></div>`,
    `)\n`,
  ])),

  'index.test.tsx': c => fileStr(R.concat(reactImports, [
    `import { mount  } from 'enzyme'`,
    `import { expect } from 'chai'`,
    c.hasStyles && `import { klass  } from '~/helpers/TestHelper'\n`,
    c.hasStyles && `const s = require('./style.css')\n`,
    `describe('<${c.moduleName.camel} />', () => {`,
    `  beforeEach(() => {`,
    `  }\n`,
    `  it('TODO')`,
    `})`,
  ])),

  'style.css': c => fileStr([
    `@import 'app/styles/colors.css';`,
    `@import 'app/styles/typefaces.css';`,
  ]),
}
<commit_msg>Update index.test.tsx module template<commit_after>const R = require('ramda')

const fileStr = lines => R.filter(R.identity, lines).join("\n")
const reactImports = [
  `import * as React from 'react'`,
  `import * as R     from 'ramda'`,
]

module.exports = {

  'index.tsx': c => fileStr(R.concat(reactImports, [
    c.hasStyles && `import * as classnames from 'classnames'\n`,
    c.hasStyles && `const s = require('./style.css')\n`,
    `export const ${c.moduleName.camel} = (props) => (`,
    `  <div></div>`,
    `)`,
  ])),

  'index.test.tsx': c => fileStr(R.concat(reactImports, [
    `import { mount  } from 'enzyme'`,
    `import { expect } from 'chai'`,
    c.hasStyles && `import { klass  } from '~/helpers/TestHelper'`,
    `\nimport { ${c.moduleName.camel} } from './index'\n`,
    c.hasStyles && `const s = require('./style.css')\n`,
    `describe('<${c.moduleName.camel} />', () => {\n`,
    `  beforeEach(() => {`,
    `  })\n`,
    `  it('TODO', () => {`,
    `  })\n`,
    `})`,
  ])),

  'style.css': c => fileStr([
    `@import 'app/styles/colors.css';`,
    `@import 'app/styles/typefaces.css';`,
  ]),
}
<|endoftext|>


<commit_before>/*
 *
 * Home
 *
 */

import React from 'react';
import Helmet from 'react-helmet';
import SignIn from 'components/SignIn';
import { Link } from 'react-router-dom';

import './style.css';
import './styleM.css';

export default class Home extends React.PureComponent {
  constructor() {
    super();
    this.state = {
      signIn:false
    }
  }

  handleSignIn = () => {
    this.setState({
      signIn:!this.state.signIn
    })
  }

  renderSignIn = () => {
    if(this.state.signIn === true) {
      return (
        <SignIn/>
      )
    }
  }

  render() {
    return (

        <Helmet title="Home" meta={[ { name: 'description', content: 'Description of Home' }]}/>
          {this.renderSignIn()}

Welcome to Job Weasel

A place to find your next job or your next employee.

              <Link to="/SignUp" className="sign-up">Sign-Up</Link>
              <input type="submit" className="sign-in" value="Sign-in" onClick={this.handleSignIn}/>

    );
  }
}

Home.contextTypes = {
  router: React.PropTypes.object
};
<commit_msg>Something<commit_after>/*
 *
 * Home
 *
 */

import React from 'react';
import Helmet from 'react-helmet';
import SignIn from 'components/SignIn';
import { Link } from 'react-router-dom';

import './style.css';
import './styleM.css';

export default class Home extends React.PureComponent {
  constructor() {
    super();
    this.state = {
      signIn:false
    }
  }

  handleSignIn = () => {
    this.setState({
      signIn:!this.state.signIn
    })
  }

  renderSignIn = () => {
    if(this.state.signIn === true) {
      return (
        <SignIn/>
      )
    }
  }
  /* Hi My head fell off*/
  render() {
    return (

        <Helmet title="Home" meta={[ { name: 'description', content: 'Description of Home' }]}/>
          {this.renderSignIn()}

Welcome to Job Weasel

A place to find your next job or your next employee.

              <Link to="/SignUp" className="sign-up">Sign-Up</Link>
              <input type="submit" className="sign-in" value="Sign-in" onClick={this.handleSignIn}/>

    );
  }
}

Home.contextTypes = {
  router: React.PropTypes.object
};
<|endoftext|>


<commit_before>(function (window) {
  var TIMEOUT = 10000;

  tryAndFindMarty(1);

  function tryAndFindMarty(time) {
    if (window.Marty) {
      listenToMarty(window.Marty);
    } else {
      if (time > TIMEOUT) {
        postMessage('PAGE_LOADED', {
          martyFound: false
        });
        return;
      }

      setTimeout(function () {
        tryAndFindMarty(time * 2);
      }, time);
    }
  }

  function listenToMarty(Marty) {
    postMessage('PAGE_LOADED', {
      martyFound: true,
      stores: Marty.serializeState().toJSON()
    });

    Marty.addStoreChangeListener(onStoreChanged);
    Marty.Dispatcher.register(onActionDispatched);

    function onActionDispatched(action) {
      postMessage('ACTION_DISPATCHED', action.toJSON());
    }

    function onStoreChanged(state, store) {
      if (store.serialize) {
        state = store.serialize();
      }

      postMessage('STORE_CHANGED', {
        displayName: store.displayName,
        state: state
      });
    }
  }

  function postMessage(type, payload) {
    window.postMessage(message(type, payload), '*');
  }

  function message(type, payload) {
    return {
      type: type,
      payload: payload || {},
      source: 'marty-extension'
    };
  }
})(window);<commit_msg>tell marty that devtools is enabled<commit_after>(function (window) {
  var TIMEOUT = 10000;

  tryAndFindMarty(1);

  function tryAndFindMarty(time) {
    if (window.Marty) {
      listenToMarty(window.Marty);
    } else {
      if (time > TIMEOUT) {
        postMessage('PAGE_LOADED', {
          martyFound: false
        });
        return;
      }

      setTimeout(function () {
        tryAndFindMarty(time * 2);
      }, time);
    }
  }

  function listenToMarty(Marty) {
    Marty.Diagostics.devtoolsEnabled = true;

    postMessage('PAGE_LOADED', {
      martyFound: true,
      stores: Marty.serializeState().toJSON()
    });

    Marty.addStoreChangeListener(onStoreChanged);
    Marty.Dispatcher.register(onActionDispatched);

    function onActionDispatched(action) {
      postMessage('ACTION_DISPATCHED', action.toJSON());
    }

    function onStoreChanged(state, store) {
      if (store.serialize) {
        state = store.serialize();
      }

      postMessage('STORE_CHANGED', {
        displayName: store.displayName,
        state: state
      });
    }
  }

  function postMessage(type, payload) {
    window.postMessage(message(type, payload), '*');
  }

  function message(type, payload) {
    return {
      type: type,
      payload: payload || {},
      source: 'marty-extension'
    };
  }
})(window);<|endoftext|>


<commit_before>module('Testimonial slide tests');
var dataForSlide = {
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com/AlekseyLeshko',
  fotoSrc: 'http://2.gravatar.com/avatar/027ed55733da6f7037335e0af0c46591?s=146',
  fullName: 'Aleksey Leshko',
  quote: 'quote'
};

var emptydata = {
  authorHref: '',
  company: '',
  companyHref: '',
  fotoSrc: '',
  fullName: '',
  quote: ''
};

function compareSlideData(x, y) {
  ok(x.authorHref === y.authorHref, '');
  ok(x.company === y.company, '');
  ok(x.companyHref === y.companyHref, '');
  ok(x.fotoSrc === y.fotoSrc, '');
  ok(x.fullName === y.fullName, '');
  ok(x.quote === y.quote, '');
}

// test('Create slide with correct data', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   compareSlideData(slide.data, dataForSlide);
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Create slide with empty data', function() {
//   var slide = new TestimonialSlide();
//   ok(slide.data !== undefined, 'Slide has empty data');
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Slide css class', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   ok(slide.$slide.attr('class') === 'testimonial_slide', 'New slide has correct css class');
// });

test('Create slide data of empty data', function() {
  var slideData = TestimonialSlide.prototype.createData();
  ok(slideData !== undefined, 'Slide data not empty');
  compareSlideData(slideData, emptydata);
});

test('Create slide data of correct data', function() {
  var slideData = TestimonialSlide.prototype.createData(dataForSlide);
  compareSlideData(slideData, dataForSlide);
});

test('Create options', function() {
  TestimonialSlide.prototype.createOptions();
  ok(TestimonialSlide.prototype.options.duration === 750, '');
  ok(TestimonialSlide.prototype.options.distance === 250, '');
  ok(TestimonialSlide.prototype.options.cssClass === 'testimonial_slide', '');
});

test('Get DOM node', function() {
  var testId = 'testId';
  var domNode = $('<div />', {
    id: testId
  });
  TestimonialSlide.prototype.$domNode = domNode;
  var $expectedDomNode = TestimonialSlide.prototype.getDomNode();
  ok($expectedDomNode.attr('id') === testId, '');
});

test('Create empty dom node', function() {
  var expectedCssClass = 'testimonial_slide';
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  var cssClass = TestimonialSlide.prototype.$domNode.attr('class');
  ok(cssClass === expectedCssClass, '');
  ok(cssClass === TestimonialSlide.prototype.options.cssClass, '');
});

test('Height dom node', function() {
  var height = 2014;
  var $domNode = $('<div />', {
    height: height
  });
  TestimonialSlide.prototype.$domNode = $domNode;
  ok(TestimonialSlide.prototype.height() === height, '');
});

test('Hide slide', function() {
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();
  var $domNode = TestimonialSlide.prototype.$domNode;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  ok($domNode.css('display') === 'none', '');
  ok($domNode.css('opacity') === '0', '');
  ok($domNode.css('margin-left') === distanceVal, '');
});

asyncTest('Animate show', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = (TestimonialSlide.prototype.options.duration * 2) + 50;
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();

  TestimonialSlide.prototype.animateShow();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;
    ok($domNode.css('display') === '', 'Slide is show');
    ok(parseInt($domNode.css('opacity')) === 1, 'Slide opacity is not 0');
    ok($domNode.css('margin-left') === '0px', 'Slide margin-left is 0');

    start();
  }, duration);
});

asyncTest('Animate show', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = TestimonialSlide.prototype.options.duration + 50;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  TestimonialSlide.prototype.createStandardDomNode();

  TestimonialSlide.prototype.animateHide();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;

    ok($domNode.css('display') === 'none', 'Slidedisplay is none');
    ok($domNode.css('opacity') === '0', 'Slide opacity is 0');
    ok($domNode.css('margin-left') === distanceVal, 'Slide margin-left is ' + distanceVal);
    start();
  }, duration);
});

test('Create dom node with author foto', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $img = TestimonialSlide.prototype.createImgAuthorFoto();
  ok($img.prop('nodeName') === 'IMG', 'Dom node is img');
  ok($img.attr('class') === 'author_foto', 'Css class dom node is correct');
  ok($img.attr('src') === dataForSlide.fotoSrc, 'Src dom node is correct');
});

test('Create link node', function() {
  var href = 'http://test.com';
  var text = 'test text';
  var $link = TestimonialSlide.prototype.createLinkNode(href, text);
  ok($link.prop('nodeName') === 'A', 'Dom node is link');
  ok($link.attr('target') === '_blank', 'link target is blank');
  ok($link.attr('href') === href, 'Link href is correct');
  ok($link.text() === text, 'link text is correct');
});

test('Create company node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createCompanyNode();
  ok($node.prop('nodeName') === 'DIV', 'Company dom node is div');
  ok($node.attr('class') === 'company', 'Css class dom node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in company node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.companyHref, 'Link href is correct');
  ok($link.text() === dataForSlide.company, 'Link text is correct');
});

test('Create author node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createAuthorNode();
  ok($node.prop('nodeName') === 'DIV', 'Author dom node is div');
  ok($node.attr('class') === 'author', 'Css class dom node is correct');
  ok($node.text() === '- ' + dataForSlide.fullName, 'Text in node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in author node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.authorHref, 'Link href is correct');
  ok($link.text() === dataForSlide.fullName, 'Link text is correct');
});

test('Create signature node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createSignatureNode();
  ok($node.prop('nodeName') === 'DIV', 'Signature dom node is div');
  ok($node.attr('class') === 'signature', 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 2, '2 nodes in signature node');
  ok($children.first().attr('class') === 'author', 'Css class first child node is correct');
  ok($children.last().attr('class') === 'company', 'Css class last child node is correct');
});

test('Create quotation mark inverted', function() {
  var $node = TestimonialSlide.prototype.createQuotationMarkInverted();
  ok($node.prop('nodeName') === 'DIV', 'Quotation mark inverted dom node is div');
  ok($node.attr('class') === 'quotation_mark_inverted', 'Css class dom node is correct');
});
<commit_msg>Add test<commit_after>module('Testimonial slide tests');
var dataForSlide = {
  authorHref: 'https://github.com/AlekseyLeshko',
  company: 'Company',
  companyHref: 'https://github.com/AlekseyLeshko',
  fotoSrc: 'http://2.gravatar.com/avatar/027ed55733da6f7037335e0af0c46591?s=146',
  fullName: 'Aleksey Leshko',
  quote: 'quote'
};

var emptydata = {
  authorHref: '',
  company: '',
  companyHref: '',
  fotoSrc: '',
  fullName: '',
  quote: ''
};

function compareSlideData(x, y) {
  ok(x.authorHref === y.authorHref, '');
  ok(x.company === y.company, '');
  ok(x.companyHref === y.companyHref, '');
  ok(x.fotoSrc === y.fotoSrc, '');
  ok(x.fullName === y.fullName, '');
  ok(x.quote === y.quote, '');
}

// test('Create slide with correct data', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   compareSlideData(slide.data, dataForSlide);
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Create slide with empty data', function() {
//   var slide = new TestimonialSlide();
//   ok(slide.data !== undefined, 'Slide has empty data');
//   ok(slide.$slide !== undefined, 'Slide has DOM node');
// });

// test('Slide css class', function() {
//   var slide = new TestimonialSlide(dataForSlide);
//   ok(slide.$slide.attr('class') === 'testimonial_slide', 'New slide has correct css class');
// });

test('Create slide data of empty data', function() {
  var slideData = TestimonialSlide.prototype.createData();
  ok(slideData !== undefined, 'Slide data not empty');
  compareSlideData(slideData, emptydata);
});

test('Create slide data of correct data', function() {
  var slideData = TestimonialSlide.prototype.createData(dataForSlide);
  compareSlideData(slideData, dataForSlide);
});

test('Create options', function() {
  TestimonialSlide.prototype.createOptions();
  ok(TestimonialSlide.prototype.options.duration === 750, '');
  ok(TestimonialSlide.prototype.options.distance === 250, '');
  ok(TestimonialSlide.prototype.options.cssClass === 'testimonial_slide', '');
});

test('Get DOM node', function() {
  var testId = 'testId';
  var domNode = $('<div />', {
    id: testId
  });
  TestimonialSlide.prototype.$domNode = domNode;
  var $expectedDomNode = TestimonialSlide.prototype.getDomNode();
  ok($expectedDomNode.attr('id') === testId, '');
});

test('Create empty dom node', function() {
  var expectedCssClass = 'testimonial_slide';
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  var cssClass = TestimonialSlide.prototype.$domNode.attr('class');
  ok(cssClass === expectedCssClass, '');
  ok(cssClass === TestimonialSlide.prototype.options.cssClass, '');
});

test('Height dom node', function() {
  var height = 2014;
  var $domNode = $('<div />', {
    height: height
  });
  TestimonialSlide.prototype.$domNode = $domNode;
  ok(TestimonialSlide.prototype.height() === height, '');
});

test('Hide slide', function() {
  TestimonialSlide.prototype.createOptions();
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();
  var $domNode = TestimonialSlide.prototype.$domNode;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  ok($domNode.css('display') === 'none', '');
  ok($domNode.css('opacity') === '0', '');
  ok($domNode.css('margin-left') === distanceVal, '');
});

asyncTest('Animate show', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = (TestimonialSlide.prototype.options.duration * 2) + 50;
  TestimonialSlide.prototype.createStandardDomNode();
  TestimonialSlide.prototype.hideSlide();

  TestimonialSlide.prototype.animateShow();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;
    ok($domNode.css('display') === '', 'Slide is show');
    ok(parseInt($domNode.css('opacity')) === 1, 'Slide opacity is not 0');
    ok($domNode.css('margin-left') === '0px', 'Slide margin-left is 0');

    start();
  }, duration);
});

asyncTest('Animate show', function() {
  TestimonialSlide.prototype.createOptions();
  var duration = TestimonialSlide.prototype.options.duration + 50;
  var distanceVal = '-' + TestimonialSlide.prototype.options.distance + 'px';
  TestimonialSlide.prototype.createStandardDomNode();

  TestimonialSlide.prototype.animateHide();
  setTimeout(function() {
    var $domNode = TestimonialSlide.prototype.$domNode;

    ok($domNode.css('display') === 'none', 'Slidedisplay is none');
    ok($domNode.css('opacity') === '0', 'Slide opacity is 0');
    ok($domNode.css('margin-left') === distanceVal, 'Slide margin-left is ' + distanceVal);
    start();
  }, duration);
});

test('Create dom node with author foto', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $img = TestimonialSlide.prototype.createImgAuthorFoto();
  ok($img.prop('nodeName') === 'IMG', 'Dom node is img');
  ok($img.attr('class') === 'author_foto', 'Css class dom node is correct');
  ok($img.attr('src') === dataForSlide.fotoSrc, 'Src dom node is correct');
});

test('Create link node', function() {
  var href = 'http://test.com';
  var text = 'test text';
  var $link = TestimonialSlide.prototype.createLinkNode(href, text);
  ok($link.prop('nodeName') === 'A', 'Dom node is link');
  ok($link.attr('target') === '_blank', 'link target is blank');
  ok($link.attr('href') === href, 'Link href is correct');
  ok($link.text() === text, 'link text is correct');
});

test('Create company node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createCompanyNode();
  ok($node.prop('nodeName') === 'DIV', 'Company dom node is div');
  ok($node.attr('class') === 'company', 'Css class dom node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in company node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.companyHref, 'Link href is correct');
  ok($link.text() === dataForSlide.company, 'Link text is correct');
});

test('Create author node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createAuthorNode();
  ok($node.prop('nodeName') === 'DIV', 'Author dom node is div');
  ok($node.attr('class') === 'author', 'Css class dom node is correct');
  ok($node.text() === '- ' + dataForSlide.fullName, 'Text in node is correct');

  var $link = $node.children().first();
  ok($link.prop('nodeName') === 'A', 'Present link in author node');
  ok($link.attr('target') === '_blank', 'Link target is blank');
  ok($link.attr('href') === dataForSlide.authorHref, 'Link href is correct');
  ok($link.text() === dataForSlide.fullName, 'Link text is correct');
});

test('Create signature node', function() {
  TestimonialSlide.prototype.data = dataForSlide;
  var $node = TestimonialSlide.prototype.createSignatureNode();
  ok($node.prop('nodeName') === 'DIV', 'Signature dom node is div');
  ok($node.attr('class') === 'signature', 'Css class dom node is correct');

  var $children = $node.children();
  ok($children.length === 2, '2 nodes in signature node');
  ok($children.first().attr('class') === 'author', 'Css class first child node is correct');
  ok($children.last().attr('class') === 'company', 'Css class last child node is correct');
});

test('Create quotation mark inverted', function() {
  var $node = TestimonialSlide.prototype.createQuotationMarkInverted();
  ok($node.prop('nodeName') === 'DIV', 'Quotation mark inverted dom node is div');
  ok($node.attr('class') === 'quotation_mark_inverted', 'Css class dom node is correct');
});

test('Create quotation mark', function() {
  var $node = TestimonialSlide.prototype.createQuotationMark();
  ok($node.prop('nodeName') === 'DIV', 'Quotation mark dom node is div');
  ok($node.attr('class') === 'quotation_mark', 'Css class dom node is correct');
});
<|endoftext|>


<commit_before>var model = require('../../services/model');
var dbService = require('../../services/dbservice');
var path = require('path');
var testdir = require('./testdir');
var Sequelize = require('sequelize');
var logger = require('../../services/logger').logger;

var reconfigureDb = function(inMemory){
  inMemory = inMemory !== undefined ? inMemory : (process.env.DOCKER_BUILD || true);
  var storage = inMemory === true ? ":memory:" : path.resolve(testdir.tmpdir, "vogon-nj.sqlite");
  var currentDbService = model.model("sqlite:", {storage: storage, isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE, logging: logger.verbose});
  var promise = dbService.sequelize.close();
  for(var k in currentDbService)
    dbService[k] = currentDbService[k];
  return promise || Sequelize.Promise.resolve();
}

module.exports.reconfigureDb = reconfigureDb;
<commit_msg>Fixed Sequelize logger for tests.<commit_after>var model = require('../../services/model');
var dbService = require('../../services/dbservice');
var path = require('path');
var testdir = require('./testdir');
var Sequelize = require('sequelize');
var logger = require('../../services/logger');

var reconfigureDb = function(inMemory){
  inMemory = inMemory !== undefined ? inMemory : (process.env.DOCKER_BUILD || true);
  var storage = inMemory === true ? ":memory:" : path.resolve(testdir.tmpdir, "vogon-nj.sqlite");
  var currentDbService = model.model("sqlite:", {storage: storage, isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE, logging: logger.sequelizeLogger});
  var promise = dbService.sequelize.close();
  for(var k in currentDbService)
    dbService[k] = currentDbService[k];
  return promise || Sequelize.Promise.resolve();
}

module.exports.reconfigureDb = reconfigureDb;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from 'react';
import {compose} from 'redux';
import {connect} from 'react-redux';
import Drawer from '@material-ui/core/Drawer';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardHeader from '@material-ui/core/CardHeader';
import Typography from '@material-ui/core/Typography';
import {getFeatureRecords} from '../../datastore.js';
import {withStyles} from '@material-ui/core/styles';

const styles = (theme) => ({
  paper: {
    top: 62,
    paddingTop: 20,
    width: 300,
  },
  title: {
    fontWeight: 'bold',
  },
  date: {
    marginTop: -20,
    fontStyle: 'italic',
  },
  key: {
    fontSize: 12,
    marginBlockEnd: '0.2em',
    color: 'gray',
  },
  value: {
    marginBlockStart: '0.2em',
  },
  card: {
    marginBottom: 20,
  },
});

type Props = {
  match: Object,
  records: {
    featureId: String,
    formId: String,
    responses: Array
  },
  classes: Object,
};

class GndFeatureDetails extends React.Component<Props> {
  render() {
    if (!this.props.records) return null;
    const {records, classes} = this.props;
    // eslint-disable-next-line max-len
    const recordsList = Object.entries(records).map(([recordId, record], index) => {
      // eslint-disable-next-line max-len
      const responsesList = Object.entries(record.responses).map(([key, value], idx) => {
        return <Typography key={idx} variant='subheading'>

{key}

{value}

        </Typography>;
      });
      return <Card key={index} classes={{root: classes.card}}>
        <CardHeader title={record.created.user.displayName} classes={{title: classes.title}}/>
        <CardContent>

{record.created.clientTimestamp}

          {responsesList}
        </CardContent>
      </Card>;
    });
    return (
      <Drawer
        anchor="right"
        open={true}
        pullRight={true}
        classes={{paper: classes.paper}}
      >
        {recordsList}
      </Drawer>
    );
  }
}

// start of code change
const mapStateToProps = (store) => ({
  records: getFeatureRecords(store),
});

const enhance = compose(
    connect(
        mapStateToProps
    ),
    withStyles(styles)
);

export default enhance(GndFeatureDetails);
<commit_msg>remove negative value from padding, fix copyright year, remove stray comment<commit_after>/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from 'react';
import {compose} from 'redux';
import {connect} from 'react-redux';
import Drawer from '@material-ui/core/Drawer';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardHeader from '@material-ui/core/CardHeader';
import Typography from '@material-ui/core/Typography';
import {getFeatureRecords} from '../../datastore.js';
import {withStyles} from '@material-ui/core/styles';

const styles = (theme) => ({
  paper: {
    top: 62,
    paddingTop: 20,
    width: 300,
  },
  title: {
    fontWeight: 'bold',
  },
  date: {
    fontStyle: 'italic',
  },
  key: {
    fontSize: 12,
    marginBlockEnd: '0.2em',
    color: 'gray',
  },
  value: {
    marginBlockStart: '0.2em',
  },
  card: {
    marginBottom: 20,
  },
  cardHeaderRoot: {
    paddingBottom: 0,
  },
  cardContentRoot: {
    paddingTop: 0,
  },
});

type Props = {
  match: Object,
  records: {
    featureId: String,
    formId: String,
    responses: Array
  },
  classes: Object,
};

class GndFeatureDetails extends React.Component<Props> {
  render() {
    if (!this.props.records) return null;
    const {records, classes} = this.props;
    // eslint-disable-next-line max-len
    const recordsList = Object.entries(records).map(([recordId, record], index) => {
      // eslint-disable-next-line max-len
      const responsesList = Object.entries(record.responses).map(([key, value], idx) => {
        return <Typography key={idx} variant='subheading'>

{key}

{value}

        </Typography>;
      });
      return <Card key={index} classes={{root: classes.card}}>
        <CardHeader title={record.created.user.displayName} classes={{title: classes.title, root: classes.cardHeaderRoot}}/>
        <CardContent classes={{root: classes.cardContentRoot}}>

{record.created.clientTimestamp}

          {responsesList}
        </CardContent>
      </Card>;
    });
    return (
      <Drawer
        anchor="right"
        open={true}
        pullRight={true}
        classes={{paper: classes.paper}}
      >
        {recordsList}
      </Drawer>
    );
  }
}

const mapStateToProps = (store) => ({
  records: getFeatureRecords(store),
});

const enhance = compose(
    connect(
        mapStateToProps
    ),
    withStyles(styles)
);

export default enhance(GndFeatureDetails);
<|endoftext|>


<commit_before>var ExplorerTabs = Backbone.View.extend({
    tagName : "div",
    triggerRoute : true,
    /**
     * ExplorerTabs constructor
     * @param options
     */
    initialize: function(options) {
        this.tabs = []; //that we are browsing
        this.container = options.container;
        this.dashboard = null;
    },
    /**
     * Grab the layout and call ask for render
     */
    render : function() {
        var self = this;
        require(["text!application/templates/explorer/Tabs.tpl.html"], function(tpl) {
            self.doLayout(tpl);
        });
        return this;
    },
    /**
     * Render the html into the DOM element associated to the view
     * @param tpl
     */
    doLayout: function(tpl) {
        var self = this;
        $(this.el).html(_.template(tpl, {}));
        return this;
    },
    /**
     *  Add a Tab containing a BrowseImageView instance
     *  @idImage : the id of the Image we want to display
     *  @options : some init options we want to pass the the BrowseImageView Instance
     */
    addBrowseImageView : function(idImage, options) {
        var self = this;
        var tab = this.getBrowseImageView(idImage);
        if (tab != null) {
            tab.view.show(options);
            return;
        }

        var tabs = $("#explorer-tab-content");
        var view = new BrowseImageView({
                initCallback : function(){view.show(options)},
                el: tabs
        });
        self.tabs.push({idImage : idImage,view : view});

        new ImageInstanceModel({id : idImage}).fetch({
            success : function(model, response) {
                view.model = model;
                view.render();
                $(".closeTab").on("click",function(e) {
                    var idImage = $(this).attr("data-image");
                    self.removeTab(idImage);
                });
                self.showTab(idImage);

            }
        });
    },
    /**
     * Return the reference to a BrowseImageView instance
     * contained in a tab
     * @param idImage the ID of an Image contained in a BrowseImageView
     */
    getBrowseImageView : function(idImage) {
        var object  = _.detect(this.tabs, function(object) {
            return object.idImage == idImage;
        });
        return object != null ? object : null;
    },
    /**
     * Remove a Tab
     * @param index the identifier of the Tab
     */
    removeTab : function (idImage) {
        var browseImageView = this.getBrowseImageView(idImage);
        browseImageView.view.stopBroadcastingInterval();
        browseImageView.view.stopWatchOnlineUsersInterval();
        var indexOf = this.tabs.indexOf(browseImageView);

        this.tabs.splice(indexOf,1);
        var tabs = $(this.el).children('.nav-tab');
        //Remove Tab
        $('#tabs-image-'+idImage).parent().remove();
        //Remove dropdown
        $('#tabs-image-'+idImage+"-dropdown").parent().remove();
        //Remove content
        $('#tabs-image-'+window.app.status.currentProject+'-'+idImage+'-').remove();
    },
    /**
     * Show a tab
     * @param idImage the identifier of the Tab
     */
    showTab : function(idImage) {
        var tabs = $("#explorer > .browser").find(".nav-tabs");
        window.app.controllers.browse.tabs.triggerRoute = false;
        $('#tabs-image-'+idImage).click();
        window.app.controllers.browse.tabs.triggerRoute = true;
    },
    /**
     * Return the number of opened tabs
     */
    size : function() {
        return _.size(this.tabs);
    },
    /**
     * Close all the Tabs
     */
    closeAll : function() {
        var tabs = $(this.el).children('.tabs');
        this.tabs = [];
        $(this.el).hide();
        $(this.el).parent().find('.noProject').show();
    },
    /**
     * Add a ProjectDashBoardView instance in the first Tab
     * @param dashboard the ProjectDashBoardView instance
     */
    addDashboard : function(dashboard) {
        var self = this;
        this.dashboard = dashboard;
        var tabs = $('#explorer-tab-content');
        $(".nav-tabs").append(_.template("
<a id='dashboardLink-<%= idProject %>' href='#tabs-dashboard-<%= idProject %>' data-toggle='tab'> Dashboard
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-images-<%= idProject %>' data-toggle='tab'> Images
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-annotations-<%= idProject %>' data-toggle='tab'> Annotations
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-algos-<%= idProject %>' data-toggle='tab'> Jobs
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-config-<%= idProject %>' data-toggle='tab'> Configuration
",{ idProject : window.app.status.currentProject}));

        $('a[data-toggle="tab"]').live('show', function (e) {
            var hash = this.href.split("#")[1];
            $("#"+hash).attr('style', 'width:100%;height:500;overflow:hidden;');
            if (self.triggerRoute) window.app.controllers.browse.navigate("#"+hash, self.triggerRoute);
        });

        $("#explorer > .browser").show();
        $("#explorer > .noProject").hide();
    },
    /**
     * Ask to the dashboard view to refresh
     */
    getDashboard : function () {
        return this.dashboard;
    }
});
<commit_msg>CYTO-660<commit_after>var ExplorerTabs = Backbone.View.extend({
    tagName : "div",
    triggerRoute : true,
    /**
     * ExplorerTabs constructor
     * @param options
     */
    initialize: function(options) {
        this.tabs = []; //that we are browsing
        this.container = options.container;
        this.dashboard = null;
    },
    /**
     * Grab the layout and call ask for render
     */
    render : function() {
        var self = this;
        require(["text!application/templates/explorer/Tabs.tpl.html"], function(tpl) {
            self.doLayout(tpl);
        });
        return this;
    },
    /**
     * Render the html into the DOM element associated to the view
     * @param tpl
     */
    doLayout: function(tpl) {
        var self = this;
        $(this.el).html(_.template(tpl, {}));
        return this;
    },
    /**
     *  Add a Tab containing a BrowseImageView instance
     *  @idImage : the id of the Image we want to display
     *  @options : some init options we want to pass the the BrowseImageView Instance
     */
    addBrowseImageView : function(idImage, options) {
        var self = this;
        var tab = this.getBrowseImageView(idImage);
        if (tab != null) {
            tab.view.show(options);
            self.showTab(idImage);
            return;
        }

        var tabs = $("#explorer-tab-content");
        var view = new BrowseImageView({
                initCallback : function(){view.show(options)},
                el: tabs
        });
        self.tabs.push({idImage : idImage,view : view});

        new ImageInstanceModel({id : idImage}).fetch({
            success : function(model, response) {
                view.model = model;
                view.render();
                $(".closeTab").on("click",function(e) {
                    var idImage = $(this).attr("data-image");
                    self.removeTab(idImage);
                });
                self.showTab(idImage);

            }
        });
    },
    /**
     * Return the reference to a BrowseImageView instance
     * contained in a tab
     * @param idImage the ID of an Image contained in a BrowseImageView
     */
    getBrowseImageView : function(idImage) {
        var object  = _.detect(this.tabs, function(object) {
            return object.idImage == idImage;
        });
        return object != null ? object : null;
    },
    /**
     * Remove a Tab
     * @param index the identifier of the Tab
     */
    removeTab : function (idImage) {
        var browseImageView = this.getBrowseImageView(idImage);
        browseImageView.view.stopBroadcastingInterval();
        browseImageView.view.stopWatchOnlineUsersInterval();
        var indexOf = this.tabs.indexOf(browseImageView);

        this.tabs.splice(indexOf,1);
        var tabs = $(this.el).children('.nav-tab');
        //Remove Tab
        $('#tabs-image-'+idImage).parent().remove();
        //Remove dropdown
        $('#tabs-image-'+idImage+"-dropdown").parent().remove();
        //Remove content
        $('#tabs-image-'+window.app.status.currentProject+'-'+idImage+'-').remove();
    },
    /**
     * Show a tab
     * @param idImage the identifier of the Tab
     */
    showTab : function(idImage) {
        var tabs = $("#explorer > .browser").find(".nav-tabs");
        window.app.controllers.browse.tabs.triggerRoute = false;
        $('#tabs-image-'+idImage).click();
        window.app.controllers.browse.tabs.triggerRoute = true;
    },
    /**
     * Return the number of opened tabs
     */
    size : function() {
        return _.size(this.tabs);
    },
    /**
     * Close all the Tabs
     */
    closeAll : function() {
        var tabs = $(this.el).children('.tabs');
        this.tabs = [];
        $(this.el).hide();
        $(this.el).parent().find('.noProject').show();
    },
    /**
     * Add a ProjectDashBoardView instance in the first Tab
     * @param dashboard the ProjectDashBoardView instance
     */
    addDashboard : function(dashboard) {
        var self = this;
        this.dashboard = dashboard;
        var tabs = $('#explorer-tab-content');
        $(".nav-tabs").append(_.template("
<a id='dashboardLink-<%= idProject %>' href='#tabs-dashboard-<%= idProject %>' data-toggle='tab'> Dashboard
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-images-<%= idProject %>' data-toggle='tab'> Images
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-annotations-<%= idProject %>' data-toggle='tab'> Annotations
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-algos-<%= idProject %>' data-toggle='tab'> Jobs
",{ idProject : window.app.status.currentProject}));
        $(".nav-tabs").append(_.template("
<a href='#tabs-config-<%= idProject %>' data-toggle='tab'> Configuration
",{ idProject : window.app.status.currentProject}));

        $('a[data-toggle="tab"]').live('show', function (e) {
            var hash = this.href.split("#")[1];
            $("#"+hash).attr('style', 'width:100%;height:500;overflow:hidden;');
            if (self.triggerRoute) window.app.controllers.browse.navigate("#"+hash, self.triggerRoute);
        });

        $("#explorer > .browser").show();
        $("#explorer > .noProject").hide();
    },
    /**
     * Ask to the dashboard view to refresh
     */
    getDashboard : function () {
        return this.dashboard;
    }
});
<|endoftext|>


<commit_before>'use strict';

/**
 * The Emotion plane controller handles the interactions within the emotion plane.
 * The emotion plane allows a user to click somewhere in a 2d-plane with four emotions in each corner,
 * the application will then create a playlist based on the distance to each emotion.
 */
angular.module('myApp.emotions', ['ngRoute'])

    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/emotions', {
            templateUrl: 'emotions/emotions.html',
            controller: 'EmotionsCtrl'
        });
    }])

    .controller('EmotionsCtrl', ['$scope','Api','SongRequestService','EmotionService',
        function ($scope,Api,SongRequestService,EmotionService) {

            /**
             * Calculate the min-max values of each feature based on the distance between the click and the corners
             * @param x_coord The x-coordinate inside the plane.
             * @param y_coord The y-coordinate inside the plane.
             * @param plane_width The total width of the plane
             * @param plane_height The total height of the plane
             * @returns {Array} An array with each feature's min and max value calculated
             */
            var calcFeatures = function(x_coord, y_coord, plane_width, plane_height){
                var feature_list = [];

                /* Scale the coordinate system to be between -1 and 1 */
                var x =2*((x_coord/plane_width)-0.5);
                var y = 2*(0.5-(y_coord/plane_height));

                /* Interpolate the features based on the distance to each emotion
                   See http://www.speech.kth.se/prod/publications/files/1344.pdf for the algorithm used */
                for(var i = 0; i < $scope.emotions[0].features.length;i++){
                    var tr_max = $scope.topright.features[i].maxvalue;
                    var tl_max = $scope.topleft.features[i].maxvalue;
                    var bl_max = $scope.bottomleft.features[i].maxvalue;
                    var br_max = $scope.bottomright.features[i].maxvalue;

                    var tr_min = $scope.topright.features[i].minvalue;
                    var tl_min = $scope.topleft.features[i].minvalue;
                    var bl_min = $scope.bottomleft.features[i].minvalue;
                    var br_min = $scope.bottomright.features[i].minvalue;

                    var max_val = $scope.feature_variance+Math.round((0.25*y*(x*(tr_max - tl_max - br_max + bl_max) + tr_max + tl_max - br_max - bl_max))
                            + (0.25*((x*(tr_max - tl_max + br_max - bl_max)) + tr_max + tl_max + br_max + bl_max)));

                    var min_val = -$scope.feature_variance+Math.round(0.25*y*(x*(tr_min - tl_min - br_min + bl_min)
                            + tr_min + tl_min - br_min - bl_min) + 0.25*(x*(tr_min - tl_min + br_min - bl_min) + tr_min + tl_min + br_min + bl_min));

                    feature_list.push({"feature":{"id":$scope.emotions[0].features[i].feature}, "minvalue": min_val,"maxvalue": max_val});
                }
                return feature_list;
            };

            /**
             * If the user has previously clicked somewhere, load the values for the previous click
             */
            var loadValues = function(){
                $scope.imgwidth = EmotionService.imgwidth;
                $scope.imgheight = EmotionService.imgheight;
                $scope.imgleft = EmotionService.imgleft;
                $scope.imgtop = EmotionService.imgtop;
            };

            /**
             * planeClick is called whenever a user clicks on the 2d-plane
             * @param event Event
             */
            $scope.planeClick = function(event) {
                var CSS_plane = $('.plane');
                var plane_width = CSS_plane.outerWidth();
                var plane_height = CSS_plane.outerHeight();

                /* Calculate the location of the selection image */
                $scope.imgwidth = 10;
                $scope.imgheight = 10;

                $scope.imgleft = event.pageX-($scope.imgwidth/2);
                $scope.imgtop = event.pageY-($scope.imgheight/2);

                // Save the current variables used for the click
                EmotionService.saveClick($scope.imgleft,$scope.imgtop,$scope.imgwidth,$scope.imgheight);

                /* Calculate the features required to request for music */
                var feature_list = calcFeatures(event.offsetX,event.offsetY,plane_width,plane_height);
                SongRequestService.playMatchingSongs(feature_list);
            };

            /* Controller body starts here */

            $scope.feature_variance = 5;
            //Get labels, initialize select boxes and load existing values
            Api.Labels.emotions().$promise.then(function(data){
                $scope.emotions = data;
                loadValues(data);
                $scope.topleft = data[0];
                $scope.bottomright = data[1];
                $scope.topright = data[2];
                $scope.bottomleft = data[3];
            }, function(err){
                throw "No emotions were returned by query: "+err;
            });

        }]);<commit_msg>Limited min to 0 and max to 100<commit_after>'use strict';

/**
 * The Emotion plane controller handles the interactions within the emotion plane.
 * The emotion plane allows a user to click somewhere in a 2d-plane with four emotions in each corner,
 * the application will then create a playlist based on the distance to each emotion.
 */
angular.module('myApp.emotions', ['ngRoute'])

    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/emotions', {
            templateUrl: 'emotions/emotions.html',
            controller: 'EmotionsCtrl'
        });
    }])

    .controller('EmotionsCtrl', ['$scope','Api','SongRequestService','EmotionService',
        function ($scope,Api,SongRequestService,EmotionService) {

            /**
             * Calculate the min-max values of each feature based on the distance between the click and the corners
             * @param x_coord The x-coordinate inside the plane.
             * @param y_coord The y-coordinate inside the plane.
             * @param plane_width The total width of the plane
             * @param plane_height The total height of the plane
             * @returns {Array} An array with each feature's min and max value calculated
             */
            var calcFeatures = function(x_coord, y_coord, plane_width, plane_height){
                var feature_list = [];

                /* Scale the coordinate system to be between -1 and 1 */
                var x =2*((x_coord/plane_width)-0.5);
                var y = 2*(0.5-(y_coord/plane_height));

                /* Interpolate the features based on the distance to each emotion
                   See http://www.speech.kth.se/prod/publications/files/1344.pdf for the algorithm used */
                for(var i = 0; i < $scope.emotions[0].features.length;i++){
                    var tr_max = $scope.topright.features[i].maxvalue;
                    var tl_max = $scope.topleft.features[i].maxvalue;
                    var bl_max = $scope.bottomleft.features[i].maxvalue;
                    var br_max = $scope.bottomright.features[i].maxvalue;

                    var tr_min = $scope.topright.features[i].minvalue;
                    var tl_min = $scope.topleft.features[i].minvalue;
                    var bl_min = $scope.bottomleft.features[i].minvalue;
                    var br_min = $scope.bottomright.features[i].minvalue;

                    var max_val = Math.round((0.25*y*(x*(tr_max - tl_max - br_max + bl_max) + tr_max + tl_max - br_max - bl_max))
                            + (0.25*((x*(tr_max - tl_max + br_max - bl_max)) + tr_max + tl_max + br_max + bl_max)));
                    max_val = Math.min($scope.feature_variance+max_val,100); // Limit max to 100

                    var min_val = Math.round(0.25*y*(x*(tr_min - tl_min - br_min + bl_min)
                            + tr_min + tl_min - br_min - bl_min) + 0.25*(x*(tr_min - tl_min + br_min - bl_min) + tr_min + tl_min + br_min + bl_min));
                    min_val = Math.max(min_val-$scope.feature_variance,0); // Limit min to 0

                    feature_list.push({"feature":{"id":$scope.emotions[0].features[i].feature}, "minvalue": min_val,"maxvalue": max_val});
                }
                return feature_list;
            };

            /**
             * If the user has previously clicked somewhere, load the values for the previous click
             */
            var loadValues = function(){
                $scope.imgwidth = EmotionService.imgwidth;
                $scope.imgheight = EmotionService.imgheight;
                $scope.imgleft = EmotionService.imgleft;
                $scope.imgtop = EmotionService.imgtop;
            };

            /**
             * planeClick is called whenever a user clicks on the 2d-plane
             * @param event Event
             */
            $scope.planeClick = function(event) {
                var CSS_plane = $('.plane');
                var plane_width = CSS_plane.outerWidth();
                var plane_height = CSS_plane.outerHeight();

                /* Calculate the location of the selection image */
                $scope.imgwidth = 10;
                $scope.imgheight = 10;

                $scope.imgleft = event.pageX-($scope.imgwidth/2);
                $scope.imgtop = event.pageY-($scope.imgheight/2);

                // Save the current variables used for the click
                EmotionService.saveClick($scope.imgleft,$scope.imgtop,$scope.imgwidth,$scope.imgheight);

                /* Calculate the features required to request for music */
                var feature_list = calcFeatures(event.offsetX,event.offsetY,plane_width,plane_height);
                SongRequestService.playMatchingSongs(feature_list);
                $scope.feature_list = feature_list;
            };

            /* Controller body starts here */

            $scope.feature_variance = 5;

            //Get labels, initialize select boxes and load existing values
            Api.Labels.emotions().$promise.then(function(data){
                $scope.emotions = data;
                loadValues(data);
                $scope.topleft = data[0];
                $scope.bottomright = data[1];
                $scope.topright = data[2];
                $scope.bottomleft = data[3];
            }, function(err){
                throw "No emotions were returned by query: "+err;
            });

        }]);<|endoftext|>