<commit_before>describe('MagicLamp', function() {
  var subject;
  beforeEach(function() {
    subject = MagicLamp;
  });

  it('is an object', function() {
    expect(subject).to.be.a('object');
  });

  describe('#initialize', function() {
    beforeEach(function() {
      subject.initialize();
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('sets genie to a new genie instance', function() {
      expect(subject.genie).to.be.an.instanceof(subject.Genie);
    });
  });

  describe('#fixtureNames', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'fixtureNames', true);
      subject.fixtureNames();
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('passes through to its genie instance', function() {
      expect(subject.genie.fixtureNames).to.have.been.calledOnce;
    });

    it('returns the genie instance\'s return value', function() {
      expect(subject.fixtureNames()).to.equal(true);
    });
  });

  describe('#globalize', function() {
    beforeEach(function() {
      subject.globalize();
    });

    afterEach(function() {
      _(['load', 'preload', 'clean']).each(function(method) {
        delete window[method];
      });
    });

    it('puts #load on window', function() {
      expect(window.load).to.be.a('function');
    });

    it('binds #load', function() {
      stub(subject, 'load', true);
      load('orders/foo');
      expect(subject.load).to.have.been.calledWith('orders/foo');
    });

    it('puts #clean on window', function() {
      expect(window.clean).to.be.a('function');
    });

    it('binds #clean', function() {
      stub(subject, 'clean', true);
      clean();
      expect(subject.clean).to.have.been.calledOnce;
    });
  });

  describe('#load', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'load', true);
      subject.load('foo', 'bar', 'baz');
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('passes through to its genie instance', function() {
      expect(subject.genie.load).to.have.been.calledWith('foo', 'bar', 'baz');
    });
  });

  describe('#preload', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'preload', true);
      subject.preload('foo', 'bar', 'baz');
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('passes through to its genie instance', function() {
      expect(subject.genie.preload).to.have.been.calledWith('foo', 'bar', 'baz');
    });
  });

  describe('#clean', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'removeFixtureContainer', true);
      subject.clean();
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('calls removeFixtureContainer on its genie instance', function() {
      expect(subject.genie.removeFixtureContainer).to.have.been.calledOnce;
    });
  });

  describe('aliases', function() {
    it('preload as "massage"', function() {
      expect(subject.massage).to.equal(subject.preload);
    });

    it('preload as "wishForMoreWishes"', function() {
      expect(subject.wishForMoreWishes).to.equal(subject.preload);
    });

    it('load as "rub"', function() {
      expect(subject.rub).to.equal(subject.load);
    });

    it('load as "wish"', function() {
      expect(subject.wish).to.equal(subject.load);
    });

    it('clean as "polish"', function() {
      expect(subject.polish).to.equal(subject.clean);
    });
  });

  describe('integration', function() {
    beforeEach(function() {
      subject.initialize();
    });

    afterEach(function() {
      subject.clean();
      delete subject.genie;
    });

    it('can load the foo template and clean up', function() {
      expect(testFixtureContainer()).to.be.undefined;
      subject.load('orders/foo');
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
      subject.clean();
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('can preload the templates and clean up', function() {
      subject.preload();
      expect(testFixtureContainer()).to.be.undefined;
      _(2).times(function() { subject.load('orders/foo'); });
      expect(document.getElementsByClassName('magic-lamp').length).to.equal(1);
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
      subject.clean();
      expect(testFixtureContainer()).to.be.undefined;
      subject.load('orders/bar');
      expect(testFixtureContainer().innerHTML).to.equal('bar\n');
      _(3).times(function() { subject.clean(); });
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('can specify the class used for the fixture container', function() {
      var newClass = subject.class = 'the-eye';
      subject.load('orders/foo');
      expect(testFixtureContainer()).to.be.undefined;
      expect(findByClassName(newClass)).to.exist;
      expect(findByClassName(newClass).innerHTML).to.equal('foo\n');
      subject.clean();
      expect(findByClassName(newClass)).to.not.exist;
      delete subject.class;
    });

    it('throws an error when it cannot find the template', function() {
      expect(function() {
        subject.load('not/gonna/happen');
      }).to.throw(/'not\/gonna\/happen' is not a registered fixture$/);
      _(3).times(function() { subject.clean(); });
      subject.clean();
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('throws an error when it cannot find the preloaded template', function() {
      subject.preload();
      expect(function() {
        subject.load('still/not/gonna/happen');
      }).to.throw();
      _(3).times(function() { subject.clean(); });
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('can load fixtures with specified names', function() {
      subject.load('custom_name');
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
    });

    it('can load fixtures with extensions', function() {
      subject.load('orders/needs_extending');
      expect(testFixtureContainer().innerHTML).to.equal('Stevenson\nPaulson\n');
    });

    it('can load fixtures with specified names and controllers', function() {
      subject.load('orders/super_specified')
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
    });

    it('can load fixtures deeply nested in define blocks', function() {
      subject.load('arbitrary/orders/other_admin_extending');
      expect(testFixtureContainer().innerHTML).to.equal('Stevenson\nPeterson\n');

      subject.load('arbitrary/orders/admin_extending');
      expect(testFixtureContainer().innerHTML).to.equal('Stevenson\nPaulson\n');
    });
  });
});
<commit_msg>added an integration test around loading multiple fixtures at once<commit_after>describe('MagicLamp', function() {
  var subject;
  beforeEach(function() {
    subject = MagicLamp;
  });

  it('is an object', function() {
    expect(subject).to.be.a('object');
  });

  describe('#initialize', function() {
    beforeEach(function() {
      subject.initialize();
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('sets genie to a new genie instance', function() {
      expect(subject.genie).to.be.an.instanceof(subject.Genie);
    });
  });

  describe('#fixtureNames', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'fixtureNames', true);
      subject.fixtureNames();
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('passes through to its genie instance', function() {
      expect(subject.genie.fixtureNames).to.have.been.calledOnce;
    });

    it('returns the genie instance\'s return value', function() {
      expect(subject.fixtureNames()).to.equal(true);
    });
  });

  describe('#globalize', function() {
    beforeEach(function() {
      subject.globalize();
    });

    afterEach(function() {
      _(['load', 'preload', 'clean']).each(function(method) {
        delete window[method];
      });
    });

    it('puts #load on window', function() {
      expect(window.load).to.be.a('function');
    });

    it('binds #load', function() {
      stub(subject, 'load', true);
      load('orders/foo');
      expect(subject.load).to.have.been.calledWith('orders/foo');
    });

    it('puts #clean on window', function() {
      expect(window.clean).to.be.a('function');
    });

    it('binds #clean', function() {
      stub(subject, 'clean', true);
      clean();
      expect(subject.clean).to.have.been.calledOnce;
    });
  });

  describe('#load', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'load', true);
      subject.load('foo', 'bar', 'baz');
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('passes through to its genie instance', function() {
      expect(subject.genie.load).to.have.been.calledWith('foo', 'bar', 'baz');
    });
  });

  describe('#preload', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'preload', true);
      subject.preload('foo', 'bar', 'baz');
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('passes through to its genie instance', function() {
      expect(subject.genie.preload).to.have.been.calledWith('foo', 'bar', 'baz');
    });
  });

  describe('#clean', function() {
    beforeEach(function() {
      subject.initialize();
      stub(subject.genie, 'removeFixtureContainer', true);
      subject.clean();
    });

    afterEach(function() {
      delete subject.genie;
    });

    it('calls removeFixtureContainer on its genie instance', function() {
      expect(subject.genie.removeFixtureContainer).to.have.been.calledOnce;
    });
  });

  describe('aliases', function() {
    it('preload as "massage"', function() {
      expect(subject.massage).to.equal(subject.preload);
    });

    it('preload as "wishForMoreWishes"', function() {
      expect(subject.wishForMoreWishes).to.equal(subject.preload);
    });

    it('load as "rub"', function() {
      expect(subject.rub).to.equal(subject.load);
    });

    it('load as "wish"', function() {
      expect(subject.wish).to.equal(subject.load);
    });

    it('clean as "polish"', function() {
      expect(subject.polish).to.equal(subject.clean);
    });
  });

  describe('integration', function() {
    beforeEach(function() {
      subject.initialize();
    });

    afterEach(function() {
      subject.clean();
      delete subject.genie;
    });

    it('can load the foo template and clean up', function() {
      expect(testFixtureContainer()).to.be.undefined;
      subject.load('orders/foo');
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
      subject.clean();
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('can preload the templates and clean up', function() {
      subject.preload();
      expect(testFixtureContainer()).to.be.undefined;
      _(2).times(function() { subject.load('orders/foo'); });
      expect(document.getElementsByClassName('magic-lamp').length).to.equal(1);
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
      subject.clean();
      expect(testFixtureContainer()).to.be.undefined;
      subject.load('orders/bar');
      expect(testFixtureContainer().innerHTML).to.equal('bar\n');
      _(3).times(function() { subject.clean(); });
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('can specify the class used for the fixture container', function() {
      var newClass = subject.class = 'the-eye';
      subject.load('orders/foo');
      expect(testFixtureContainer()).to.be.undefined;
      expect(findByClassName(newClass)).to.exist;
      expect(findByClassName(newClass).innerHTML).to.equal('foo\n');
      subject.clean();
      expect(findByClassName(newClass)).to.not.exist;
      delete subject.class;
    });

    it('throws an error when it cannot find the template', function() {
      expect(function() {
        subject.load('not/gonna/happen');
      }).to.throw(/'not\/gonna\/happen' is not a registered fixture$/);
      _(3).times(function() { subject.clean(); });
      subject.clean();
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('throws an error when it cannot find the preloaded template', function() {
      subject.preload();
      expect(function() {
        subject.load('still/not/gonna/happen');
      }).to.throw();
      _(3).times(function() { subject.clean(); });
      expect(testFixtureContainer()).to.be.undefined;
    });

    it('can load fixtures with specified names', function() {
      subject.load('custom_name');
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
    });

    it('can load fixtures with extensions', function() {
      subject.load('orders/needs_extending');
      expect(testFixtureContainer().innerHTML).to.equal('Stevenson\nPaulson\n');
    });

    it('can load fixtures with specified names and controllers', function() {
      subject.load('orders/super_specified')
      expect(testFixtureContainer().innerHTML).to.equal('foo\n');
    });

    it('can load fixtures deeply nested in define blocks', function() {
      subject.load('arbitrary/orders/other_admin_extending');
      expect(testFixtureContainer().innerHTML).to.equal('Stevenson\nPeterson\n');

      subject.load('arbitrary/orders/admin_extending');
      expect(testFixtureContainer().innerHTML).to.equal('Stevenson\nPaulson\n');
    });

    it('can load multiple fixtures', function() {
      subject.load('arbitrary/orders/admin_extending', 'orders/foo');
      expect(testFixtureContainer().innerHTML).to.equal('Stevenson\nPaulson\nfoo\n');
    });
  });
});
<|endoftext|>


<commit_before>(function($) {

    $.filePicker = {
        conf: {
            url: '',
            urls: '',
        }
    };

    // constructor
    function FilePicker(root, conf) {

        // current instance
        var self = this,
            tabs = null;

        root.append($('
').addClass('file-picker'));
        root = root.find('.file-picker');

        // methods
        $.extend(self, {

            getConf: function() {
                return conf;
            },

            getRoot: function() {
                return root;
            },

            load: function() {
                tabs.tabs('div.panes > div');
                tabs.tabs().onClick(function(e, index) {
                    self.tabClick(e, index);
                });
                $.get(conf.url, function(response) {
                    conf.urls = response.urls;
                    self.getFiles();
                });
            },

            tabClick: function(e, index) {
                if (index == 1) {
                    /*
                    var pane = root.find('.file-picker-upload');
                    pane.empty();
                    pane.append($('
').attr('id', 'filelist'));
                    var browse = $('').text('Select Files').attr({
                        'href': '#',
                        'id': 'pickfiles',
                    });
                    pane.append(browse);
                    var uploaded = $('').text('Upload Files').attr({
                        'href': '#',
                        'id': 'uploadfiles',
                    });
                    pane.append(uploaded);
                    */
                    self.getForm();
                    self.setupUpload();
                }
            },

            getForm: function(data){
                if (!data) {
                    data = {};
                }
                $.get(conf.urls.upload.file, data, function(response){
                    self.displayForm(response);
                });
            },

            displayForm: function(data){
                var pane = root.find('.file-picker-upload');
                pane.empty();
                pane.append($('
').attr('id', 'filelist'));
                var browse = $('').text('Select Files').attr({
                    'href': '#',
                    'id': 'pickfiles',
                });
                pane.append(browse);
                var uploaded = $('').text('Upload Files').attr({
                    'href': '#',
                    'id': 'uploadfiles',
                });
                pane.append(uploaded);
                var form = $('form').attr({'method': 'post'}).html(data.form);
                form.append($('<input>').attr({'type': 'submit', 'value': 'Sumbit'}));
                pane.append(form);
            },

            getFiles: function(data) {
                if (!data) {
                    data = {};
                }
                $.get(conf.urls.browse.files, data, function(response) {
                    self.displayFiles(response);
                });
            },

            setupUpload: function() {
                var uploader = new plupload.Uploader({
                    runtimes : 'html5',//'gears,html5,flash,silverlight,browserplus',
                    browse_button : 'pickfiles',
                    max_file_size : '10mb',
                    url : conf.urls.upload.file,
                    resize : {width : 320, height : 240, quality : 90},
                    //flash_swf_url : '/media/js/plupload.flash.swf',
                    //silverlight_xap_url : '/media/js/plupload.silverlight.xap',
                    filters : [
                        {title : "Image files", extensions : "jpg,gif,png"},
                        {title : "Zip files", extensions : "zip"}
                    ]
                });
                uploader.bind('Init', function(up, params) {
                    $('#filelist').html("
Current runtime: " + params.runtime + "
");
                });

                uploader.bind('FilesAdded', function(up, files) {
                    $.each(files, function(i, file) {
                        $('#filelist').append(
                            '
' +
                            file.name + ' (' + plupload.formatSize(file.size) + ') ' +
                        '
');
                    });
                });

                uploader.bind('UploadProgress', function(up, file) {
                    $('#' + file.id + " b").html(file.percent + "%");
                });

                $('#uploadfiles').click(function(e) {
                    uploader.start();
                    e.preventDefault();
                });
                uploader.init();
            },

            displayFiles: function(data) {
                var container = root.find('#file-picker-browse');

                var files = data.result;
                container.empty();
                var table = $('
');
                var tr = $('
');
                var form = $('<form>').attr({
                     'action': "",
                     'method': 'get'
                });
                form.append(
                    $('<input>').attr({ 'type': 'text', 'id':'search','name':'search'}).val(data.search)
                );
                form.append(
                    $('<input>').attr({ 'type': 'submit', 'value':'Search'}).click(
                    function(e) {
                        e.preventDefault();
                        self.getFiles({'search': $('#search').val() });
                    })
                );
                var tr = $('
');
                tr.append($('').text('Thumbnail'));
                tr.append($('').text('Name'));
                table.append(tr);
                $.each(files, function(idx, file) {
                    var tr = $('
');
                    var a = $('').click(function(e) {
                        $(self).trigger("onImageClick", [file.insert]);
                    });
                    var img = $('').attr({
                        'alt': file.name,
                        'src': file.thumb.url,
                        'width': file.thumb.width,
                        'height': file.thumb.height
                    });
                    a.append(img);

                    tr.append($('').append(a));
                    tr.append($('').text(file.name));
                    table.append(tr);
                });
                var div = $('
').attr({'class': 'scrollable'});
                container.append(form);
                container.append(div.append(table));
                var footer = $('
').attr('id', 'footer');
                var next = $('').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Next')
                if (data.has_next) {
                    next.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page + 1, 'search': $('#search').val()});
                    });
                } else {
                    next.css('color', '#bbb');
                }
                var previous = $('').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Previous ')
                if (data.has_previous) {
                    previous.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page - 1, 'search': $('#search').val()});
                    });
                } else {
                    previous.css('color', '#bbb');
                }
                footer.append(previous);
                $.each(data.pages, function(index, value){
                        var list = $('').attr({
                            'title': value,
                            'href': '#'
                        }).text(value+' ')
                        if (data.page==value) {
                            list.css('color', '#bbb');
                        } else {
                            list.click(function(e) {
                                e.preventDefault();
                                self.getFiles({'page': value, 'search': $('#search').val()});
                            });
                        }
                        footer.append(list);
                });
                footer.append(next);
                container.append(footer);
            },
        });

        // callbacks
        $.each(['onImageClick',], function(i, name) {
            // configuration
            if ($.isFunction(conf[name])) {
                $(self).bind(name, conf[name]);
            }
            self[name] = function(fn) {
                $(self).bind(name, fn);
                return self;
            };
        });

        // setup tabs
        var tabs = $('
').addClass('css-tabs').addClass('file-picker-tabs');
        tabs.append($('
').append($('').attr('href', '#').text('Browse')));
        tabs.append($('
').append($('').attr('href', '#').text('Upload')));
        var panes = $('
').addClass('panes');
        panes.append($('
').attr('id', 'file-picker-browse'));
        panes.append($('
').addClass('file-picker-upload'));
        root.append(tabs);
        root.append(panes);
    }

    // jQuery plugin implementation
    $.fn.filePicker = function(conf) {
        // already constructed --> return API
        var el = this.data("filePicker");
        if (el) { return el; }

        conf = $.extend({}, $.filePicker.conf, conf);

        this.each(function() {
            el = new FilePicker($(this), conf);
            $(this).data("filePicker", el);
        });

        return conf.api ? el: this;
    };

})(jQuery);

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    } else if (br == "ff") strPos = txtarea.selectionStart;
    var front = (txtarea.value).substring(0,strPos);
    var back = (txtarea.value).substring(strPos,txtarea.value.length);
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    } else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}
<commit_msg>Fixed upload missing variable still have double form<commit_after>(function($) {

    $.filePicker = {
        conf: {
            url: '',
            urls: '',
        }
    };

    // constructor
    function FilePicker(root, conf) {

        // current instance
        var self = this,
            tabs = null;

        root.append($('
').addClass('file-picker'));
        root = root.find('.file-picker');

        // methods
        $.extend(self, {

            getConf: function() {
                return conf;
            },

            getRoot: function() {
                return root;
            },

            load: function() {
                tabs.tabs('div.panes > div');
                tabs.tabs().onClick(function(e, index) {
                    self.tabClick(e, index);
                });
                $.get(conf.url, function(response) {
                    conf.urls = response.urls;
                    self.getFiles();
                });
            },

            tabClick: function(e, index) {
                console.log(index);
                if (index == 1) {
                    self.getForm();
                }
            },

            getForm: function(data){
                if (!data) {
                    data = {};
                }
                $.get(conf.urls.upload.file, data, function(response){
                    self.displayForm(response);
                    self.setupUpload();
                });
            },

            displayForm: function(data){
                console.log(data);
                var pane = root.find('.file-picker-upload');
                pane.empty();
                pane.append($('
').attr('id', 'filelist'));
                var browse = $('').text('Select Files').attr({
                    'href': '#',
                    'id': 'pickfiles',
                });
                pane.append(browse);
                var uploaded = $('').text('Upload Files').attr({
                    'href': '#',
                    'id': 'uploadfiles',
                });
                pane.append(uploaded);
                var form = $('form').attr({'method': 'post'})
                form.html(data.form);
                form.append($('<input>').attr({'type': 'submit', 'value': 'Sumbit'}));
                pane.append(form);
            },

            getFiles: function(data) {
                if (!data) {
                    data = {};
                }
                $.get(conf.urls.browse.files, data, function(response) {
                    self.displayFiles(response);
                });
            },

            setupUpload: function() {
                var uploader = new plupload.Uploader({
                    runtimes : 'html5',//'gears,html5,flash,silverlight,browserplus',
                    browse_button : 'pickfiles',
                    max_file_size : '10mb',
                    url : conf.urls.upload.file,
                    resize : {width : 320, height : 240, quality : 90},
                    //flash_swf_url : '/media/js/plupload.flash.swf',
                    //silverlight_xap_url : '/media/js/plupload.silverlight.xap',
                    filters : [
                        {title : "Image files", extensions : "jpg,gif,png"},
                        {title : "Zip files", extensions : "zip"}
                    ]
                });
                uploader.bind('Init', function(up, params) {
                    $('#filelist').html("
Current runtime: " + params.runtime + "
");
                });

                uploader.bind('FilesAdded', function(up, files) {
                    $.each(files, function(i, file) {
                        $('#filelist').append(
                            '
' +
                            file.name + ' (' + plupload.formatSize(file.size) + ') ' +
                        '
');
                    });
                });

                uploader.bind('UploadProgress', function(up, file) {
                    $('#' + file.id + " b").html(file.percent + "%");
                });

                $('#uploadfiles').click(function(e) {
                    uploader.start();
                    e.preventDefault();
                });
                uploader.init();
            },

            displayFiles: function(data) {
                var container = root.find('#file-picker-browse');

                var files = data.result;
                container.empty();
                var table = $('
');
                var tr = $('
');
                var form = $('<form>').attr({
                     'action': "",
                     'method': 'get'
                });
                form.append(
                    $('<input>').attr({ 'type': 'text', 'id':'search','name':'search'}).val(data.search)
                );
                form.append(
                    $('<input>').attr({ 'type': 'submit', 'value':'Search'}).click(
                    function(e) {
                        e.preventDefault();
                        self.getFiles({'search': $('#search').val() });
                    })
                );
                var tr = $('
');
                tr.append($('').text('Thumbnail'));
                tr.append($('').text('Name'));
                table.append(tr);
                $.each(files, function(idx, file) {
                    var tr = $('
');
                    var a = $('').click(function(e) {
                        $(self).trigger("onImageClick", [file.insert]);
                    });
                    var img = $('').attr({
                        'alt': file.name,
                        'src': file.thumb.url,
                        'width': file.thumb.width,
                        'height': file.thumb.height
                    });
                    a.append(img);

                    tr.append($('').append(a));
                    tr.append($('').text(file.name));
                    table.append(tr);
                });
                var div = $('
').attr({'class': 'scrollable'});
                container.append(form);
                container.append(div.append(table));
                var footer = $('
').attr('id', 'footer');
                var next = $('').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Next')
                if (data.has_next) {
                    next.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page + 1, 'search': $('#search').val()});
                    });
                } else {
                    next.css('color', '#bbb');
                }
                var previous = $('').attr({
                        'title': 'Next',
                        'href': '#'
                    }).text('Previous ')
                if (data.has_previous) {
                    previous.click(function(e) {
                        e.preventDefault();
                        self.getFiles({'page': data.page - 1, 'search': $('#search').val()});
                    });
                } else {
                    previous.css('color', '#bbb');
                }
                footer.append(previous);
                $.each(data.pages, function(index, value){
                        var list = $('').attr({
                            'title': value,
                            'href': '#'
                        }).text(value+' ')
                        if (data.page==value) {
                            list.css('color', '#bbb');
                        } else {
                            list.click(function(e) {
                                e.preventDefault();
                                self.getFiles({'page': value, 'search': $('#search').val()});
                            });
                        }
                        footer.append(list);
                });
                footer.append(next);
                container.append(footer);
            },
        });

        // callbacks
        $.each(['onImageClick',], function(i, name) {
            // configuration
            if ($.isFunction(conf[name])) {
                $(self).bind(name, conf[name]);
            }
            self[name] = function(fn) {
                $(self).bind(name, fn);
                return self;
            };
        });

        // setup tabs
        var tabs = $('
').addClass('css-tabs').addClass('file-picker-tabs');
        tabs.append($('
').append($('').attr('href', '#').text('Browse')));
        tabs.append($('
').append($('').attr('href', '#').text('Upload')));
        var panes = $('
').addClass('panes');
        panes.append($('
').attr('id', 'file-picker-browse'));
        panes.append($('
').addClass('file-picker-upload'));
        root.append(tabs);
        root.append(panes);
    }

    // jQuery plugin implementation
    $.fn.filePicker = function(conf) {
        // already constructed --> return API
        var el = this.data("filePicker");
        if (el) { return el; }

        conf = $.extend({}, $.filePicker.conf, conf);

        this.each(function() {
            el = new FilePicker($(this), conf);
            $(this).data("filePicker", el);
        });

        return conf.api ? el: this;
    };

})(jQuery);

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    } else if (br == "ff") strPos = txtarea.selectionStart;
    var front = (txtarea.value).substring(0,strPos);
    var back = (txtarea.value).substring(strPos,txtarea.value.length);
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    } else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}
<|endoftext|>


<commit_before>window.BookshareUtils = {

	environment: 'LIVE',

	POSITION_TRACKING_EXCLUSIONS: ['html', 'section', 'div'],

	flatten: function(s) {
		return s.replace(/\//g, "%2F");
	},

	makeSyncFunction: function(urlFunction, dataType) {

		return function(method, model, options) {
			var syncUrl = urlFunction(model);

			if(!syncUrl) {
				throw "Cannot sync the model without a valid sync URL.";
			}

			switch (method) {
		        case "read":
		        	$.ajax({
		        		'url': syncUrl,
		        		'dataType': dataType,
						'xhrFields': {
							'withCredentials': true
						},
		        		'crossDomain': true,
		        		'success': function(data, textStatus, jqXHR) { options.success(data); },
		        		'error': function(jqXHR, textStatus, errorThrown) { options.error(jqXHR); }
		        	});
		            break;
		        case "create":
		            throw "Not yet implemented";
		            break;
		        case "update":
		            throw "Not yet implemented";
		            break;
		        case "delete":
		            throw "Not yet implemented";
		            break;
		    }

		    return null;
		}
	},

	resolveUrl: function(u) {
		var normalized;
		if (u.substring(0,3) == "../") {
			normalized = u.substring(3);
		} else {
			normalized = u;
		}

		normalized = BookshareUtils.flatten(normalized);

		var manifest = window._epub.packageDocument.get('manifest');
		var item = manifest.find(function(i) { var uu = new URI(i.get('href')); return (uu.path.indexOf(normalized) > -1);});
		if (item == null) {
			return null;
		} else {
			return item.get('href');
		}
	},

	setEnvironment: function(href) {
		BookshareUtils.http = 'https://';
		var match = /(?:http|https)\:\/\/reader(\.\w*?){0,1}\.bookshare\.org(:8080){0,1}\/viewer\.html/.exec(href);
		if (match != null) {
			if (match[1] == '.qa') { BookshareUtils.environment = 'QA'; }
			else if (match[1] == '.staging') { BookshareUtils.environment = 'STAGING'; }
			else if (match[1] == '.dev') {
				BookshareUtils.environment = 'DEV';
				BookshareUtils.http = 'http://';
			}
		}
	},

	resolveEnvironment: function(href) {
		var uri = new URI(href);

		if (uri.authority == 'www.bookshare.org') {
			if (BookshareUtils.environment == 'QA') {
				uri.authority = 'public.qa.bookshare.org';
			} else if (BookshareUtils.environment == 'STAGING') {
				uri.authority = 'public.staging.bookshare.org';
			} else if (BookshareUtils.environment == 'DEV') {
				uri.authority = 'public.dev.bookshare.org:8080';
			}
		}

		return uri.toString();
	},

	raiseSystemAlert: function(key, params) {
		var template = Handlebars.templates[key];
		$('#system-message-content').html(template((params != null) ? params : {}));
		$('#system-message').modal({backdrop: 'static', keyboard: false});
	},

	dismissSystemAlert: function() {
		$('#system-message').modal('hide');
		$('#system-message-content').html('');
	},

	findTopElement: function(viewObject) {
		var contentFrame = viewObject.getFrame();

		if (viewObject.model.epub.get("page_prog_dir") == "rtl") {
			var plumbLine = (2 * parseInt(contentFrame.width.replace('px', ''), 10)) / 3;
		} else {
			var plumbLine = parseInt(contentFrame.width.replace('px', ''), 10) / 3;
		}

		var result = null;
		var height = parseInt(contentFrame.height.replace('px', ''), 10);
		var contentDoc = contentFrame.contentDocument;
		var y = 0;

		result = contentDoc.elementFromPoint(plumbLine, y);
		while (y < height && result != null && this.POSITION_TRACKING_EXCLUSIONS.indexOf(result.tagName.toLowerCase()) > -1) {
			y = y + 10;
			result = contentDoc.elementFromPoint(plumbLine, y);
		}
		return result;
	},

	getSelectorForNearestElementWithId: function(element) {
		var result = null;
		if (element.getAttribute('id') != null) {
			result = element.tagName + '#' + element.getAttribute('id');
		} else {
			// check preceding siblings, then parent
			if (element.previousElementSibling != null) {
				result = this.getSelectorForNearestElementWithId(element.previousElementSibling);
			} else if (element.parentElement != null && this.POSITION_TRACKING_EXCLUSIONS.indexOf(element.parentElement.tagName.toLowerCase()) == -1) {
				result = this.getSelectorForNearestElementWithId(element.parentElement);
			}
		}
		return result;
	},

	getSplitUrl: function(href) {
		return href.match(/([^#]*)(?:#(.*))?/);
	}
};

Readium.Models.PackageDocument.prototype.sync = BookshareUtils.makeSyncFunction(function(m) { return BookshareUtils.resolveEnvironment(BookshareUtils.http + 'www.bookshare.org/getManifest?titleInstanceId=' + m.get('book').get('key'));}, 'xml');
Readium.Models.Toc.prototype.sync = BookshareUtils.makeSyncFunction(function(m) { return m.file_path;}, 'xml');
Readium.Models.SpineItem.prototype.sync = window.BookshareUtils.makeSyncFunction( function(m) {return m.get('href');}, 'xml');

// overrides
Readium.Models.SpineItem.prototype.parse = function(htmlContent) {
	var doc = $(htmlContent);
	doc.find('head [href]').each(function(i, el) { this.setAttribute('href', BookshareUtils.resolveUrl(this.getAttribute('href'))); });
	doc.find('[src]').each(function(i, el) { this.setAttribute('src', BookshareUtils.resolveUrl(this.getAttribute('src'))); });
	doc.find('aside[epub\\\:type=annotation]').each(function(i, el) { el.style.display = "none"; });

	// handle page numbers that use title to store their values
	doc.find('[epub\\\:type=pagebreak]').each(
		function(i, el) {
			$(el).addClass("bksPageNumber");
			// normalize storage of page values
			if (el.textContent == "" && el.getAttribute('title') != "") {
				el.textContent = el.getAttribute('title');
			} else if (el.textContent != "" && el.getAttribute('title') == "") {
				el.setAttribute('title', el.textContent);
			}
		});

	this.content = doc[0].documentElement;
};

Readium.Models.PackageDocument.prototype.resolvePath = function(path) {
	return path;
};

Readium.Models.PackageDocument.prototype.initialize = function(attributes, options) {
	this.uri_obj = new URI(this.get('book').get('publication_root'));
	this.on('change:spine_position', this.onSpinePosChanged);
};

// I don't like this at all; we should have a better matcher than an endsWith
Readium.Models.PackageDocument.prototype.spineIndexFromHref = function(href) {
	var spine = this.get("res_spine");
	var h = new URI(this.resolveUri(href));
	for(var i = 0; i < spine.length; i++) {
		var path = spine.at(i).get("href");
		var p = new URI(this.resolveUri(path));
		var hPath = BookshareUtils.flatten(h.path);
		if (
			h.scheme === p.scheme &&
			h.authority === p.authority &&
			p.path.substring(p.path.length - hPath.length) == hPath
			) {
			return i;
		}
	}
	return -1;
};<commit_msg>READ-12 Added IE9 detection function<commit_after>window.BookshareUtils = {

	environment: 'LIVE',

	POSITION_TRACKING_EXCLUSIONS: ['html', 'section', 'div'],

	flatten: function(s) {
		return s.replace(/\//g, "%2F");
	},

	makeSyncFunction: function(urlFunction, dataType) {

		return function(method, model, options) {
			var syncUrl = urlFunction(model);

			if(!syncUrl) {
				throw "Cannot sync the model without a valid sync URL.";
			}

			switch (method) {
		        case "read":
		        	$.ajax({
		        		'url': syncUrl,
		        		'dataType': dataType,
						'xhrFields': {
							'withCredentials': true
						},
		        		'crossDomain': true,
		        		'success': function(data, textStatus, jqXHR) { options.success(data); },
		        		'error': function(jqXHR, textStatus, errorThrown) { options.error(jqXHR); }
		        	});
		            break;
		        case "create":
		            throw "Not yet implemented";
		            break;
		        case "update":
		            throw "Not yet implemented";
		            break;
		        case "delete":
		            throw "Not yet implemented";
		            break;
		    }

		    return null;
		}
	},

	resolveUrl: function(u) {
		var normalized;
		if (u.substring(0,3) == "../") {
			normalized = u.substring(3);
		} else {
			normalized = u;
		}

		normalized = BookshareUtils.flatten(normalized);

		var manifest = window._epub.packageDocument.get('manifest');
		var item = manifest.find(function(i) { var uu = new URI(i.get('href')); return (uu.path.indexOf(normalized) > -1);});
		if (item == null) {
			return null;
		} else {
			return item.get('href');
		}
	},

	setEnvironment: function(href) {
		BookshareUtils.http = 'https://';
		var match = /(?:http|https)\:\/\/reader(\.\w*?){0,1}\.bookshare\.org(:8080){0,1}\/viewer\.html/.exec(href);
		if (match != null) {
			if (match[1] == '.qa') { BookshareUtils.environment = 'QA'; }
			else if (match[1] == '.staging') { BookshareUtils.environment = 'STAGING'; }
			else if (match[1] == '.dev') {
				BookshareUtils.environment = 'DEV';
				BookshareUtils.http = 'http://';
			}
		}
	},

	resolveEnvironment: function(href) {
		var uri = new URI(href);

		if (uri.authority == 'www.bookshare.org') {
			if (BookshareUtils.environment == 'QA') {
				uri.authority = 'public.qa.bookshare.org';
			} else if (BookshareUtils.environment == 'STAGING') {
				uri.authority = 'public.staging.bookshare.org';
			} else if (BookshareUtils.environment == 'DEV') {
				uri.authority = 'public.dev.bookshare.org:8080';
			}
		}

		return uri.toString();
	},

	raiseSystemAlert: function(key, params) {
		var template = Handlebars.templates[key];
		$('#system-message-content').html(template((params != null) ? params : {}));
		$('#system-message').modal({backdrop: 'static', keyboard: false});
	},

	dismissSystemAlert: function() {
		$('#system-message').modal('hide');
		$('#system-message-content').html('');
	},

	findTopElement: function(viewObject) {
		var contentFrame = viewObject.getFrame();

		if (viewObject.model.epub.get("page_prog_dir") == "rtl") {
			var plumbLine = (2 * parseInt(contentFrame.width.replace('px', ''), 10)) / 3;
		} else {
			var plumbLine = parseInt(contentFrame.width.replace('px', ''), 10) / 3;
		}

		var result = null;
		var height = parseInt(contentFrame.height.replace('px', ''), 10);
		var contentDoc = contentFrame.contentDocument;
		var y = 0;

		result = contentDoc.elementFromPoint(plumbLine, y);
		while (y < height && result != null && this.POSITION_TRACKING_EXCLUSIONS.indexOf(result.tagName.toLowerCase()) > -1) {
			y = y + 10;
			result = contentDoc.elementFromPoint(plumbLine, y);
		}
		return result;
	},

	getSelectorForNearestElementWithId: function(element) {
		var result = null;
		if (element.getAttribute('id') != null) {
			result = element.tagName + '#' + element.getAttribute('id');
		} else {
			// check preceding siblings, then parent
			if (element.previousElementSibling != null) {
				result = this.getSelectorForNearestElementWithId(element.previousElementSibling);
			} else if (element.parentElement != null && this.POSITION_TRACKING_EXCLUSIONS.indexOf(element.parentElement.tagName.toLowerCase()) == -1) {
				result = this.getSelectorForNearestElementWithId(element.parentElement);
			}
		}
		return result;
	},

	getSplitUrl: function(href) {
		return href.match(/([^#]*)(?:#(.*))?/);
	},

	isIE9 : function() {

	    var undef;
	    var v = 3;
	    var div = document.createElement('div');
	    var all = div.getElementsByTagName('i');

	    while (
	        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
	        all[0]
	    );

	    if (v === 9) {
	    	return true;
	    }
	    else {
	    	return false;
	    }
	}
};

Readium.Models.PackageDocument.prototype.sync = BookshareUtils.makeSyncFunction(function(m) { return BookshareUtils.resolveEnvironment(BookshareUtils.http + 'www.bookshare.org/getManifest?titleInstanceId=' + m.get('book').get('key'));}, 'xml');
Readium.Models.Toc.prototype.sync = BookshareUtils.makeSyncFunction(function(m) { return m.file_path;}, 'xml');
Readium.Models.SpineItem.prototype.sync = window.BookshareUtils.makeSyncFunction( function(m) {return m.get('href');}, 'xml');

// overrides
Readium.Models.SpineItem.prototype.parse = function(htmlContent) {
	var doc = $(htmlContent);
	doc.find('head [href]').each(function(i, el) { this.setAttribute('href', BookshareUtils.resolveUrl(this.getAttribute('href'))); });
	doc.find('[src]').each(function(i, el) { this.setAttribute('src', BookshareUtils.resolveUrl(this.getAttribute('src'))); });
	doc.find('aside[epub\\\:type=annotation]').each(function(i, el) { el.style.display = "none"; });

	// handle page numbers that use title to store their values
	doc.find('[epub\\\:type=pagebreak]').each(
		function(i, el) {
			$(el).addClass("bksPageNumber");
			// normalize storage of page values
			if (el.textContent == "" && el.getAttribute('title') != "") {
				el.textContent = el.getAttribute('title');
			} else if (el.textContent != "" && el.getAttribute('title') == "") {
				el.setAttribute('title', el.textContent);
			}
		});

	this.content = doc[0].documentElement;
};

Readium.Models.PackageDocument.prototype.resolvePath = function(path) {
	return path;
};

Readium.Models.PackageDocument.prototype.initialize = function(attributes, options) {
	this.uri_obj = new URI(this.get('book').get('publication_root'));
	this.on('change:spine_position', this.onSpinePosChanged);
};

// I don't like this at all; we should have a better matcher than an endsWith
Readium.Models.PackageDocument.prototype.spineIndexFromHref = function(href) {
	var spine = this.get("res_spine");
	var h = new URI(this.resolveUri(href));
	for(var i = 0; i < spine.length; i++) {
		var path = spine.at(i).get("href");
		var p = new URI(this.resolveUri(path));
		var hPath = BookshareUtils.flatten(h.path);
		if (
			h.scheme === p.scheme &&
			h.authority === p.authority &&
			p.path.substring(p.path.length - hPath.length) == hPath
			) {
			return i;
		}
	}
	return -1;
};<|endoftext|>


<commit_before>define(["sprd/data/SprdDataSource", "js/data/DataSource", "js/data/RestDataSource", "underscore", "sprd/data/SprdModel", "sprd/model/processor/DefaultProcessor", "sprd/model/processor/BasketProcessor", "sprd/model/processor/BasketItemProcessor", "sprd/data/SprdApiQueryComposer", "sprd/model/processor/UploadDesignProcessor", "JSON"],
    function (SprdDataSource, DataSource, RestDataSource, _, SprdModel, DefaultProcessor, BasketProcessor, BasketItemProcessor, SprdApiQueryComposer, UploadDesignProcessor, JSON) {

        var _formatProcessorCache = {},
            REMOTE = 'remote',
            ImageFormatProcessor = DataSource.FormatProcessor.inherit({

                ctor: function(type, format) {
                    this.$type = type;
                    this.$format = format;

                    this.callBase();
                },

                serialize: function(data) {

                    if (this.$format == REMOTE) {
                        return JSON.stringify({
                            href: data.image.src
                        });
                    }

                    var ret = new FormData();
                    ret.append('filedata', data.image.file);
                    return ret;
                },

                getContentType: function() {
                    if (this.$format === REMOTE) {
                        return "application/json";
                    }

                    return false;
                }
            });

        var SprdApiDataSource = SprdDataSource.inherit('sprd.data.SprdApiDataSourceClass', {

            defaults: {
                locale: "en_EU",
                parsePayloadOnCreate: false,
                parsePayloadOnUpdate: false,
                keepRawData: false
            },

            $defaultProcessorFactory: DefaultProcessor,

            $processors: {
                BasketProcessor: BasketProcessor,
                BasketItemProcessor: BasketItemProcessor,
                OrderItemProcessor: BasketItemProcessor,
                UploadDesignProcessor: UploadDesignProcessor
            },

            getQueryParameters: function (method, resource) {
                var ret = _.defaults({
                    mediaType: "json"
                }, this.callBase());

                if (resource.constructor.name.indexOf("Label") > -1) {
                    ret.fullData = true
                }
                return ret;

            },

            getFormatProcessor: function(action, model) {

                if (model && model.factory.prototype.constructor.name == "sprd.model.DesignUpload") {
                    var type = model.$.image.$.type,
                        format = model.$.image.$.file ? "file" : REMOTE,
                        cacheId = type + "_" + format;

                    if (!_formatProcessorCache[cacheId]) {
                        _formatProcessorCache[cacheId] = new ImageFormatProcessor(type, format);
                    }

                    return _formatProcessorCache[cacheId];
                }

                return this.callBase();
            },

            createContext: function (contextModel, properties, parentContext) {
                return new SprdApiDataSource.SprdApiContext(this, contextModel, properties, parentContext);
            },

            getQueryComposer: function () {
                return SprdApiQueryComposer;
            },

            _getContextPath: function (data) {
                var match = /\/api\/v1\/(.*)$/.exec(data[this.$.determinateContextAttribute]);

                if (match) {
                    return match[1];
                }

                return this.callBase();
            },

            _parsePayloadOnUpdate: function (request, xhr) {

                var model = request.model;
                var configuration = this.$dataSourceConfiguration.getConfigurationForModelClass(model.factory);

                if (configuration.$.parseResponse === true) {
                    return true;
                }

                return this.callBase();
            },

            /***
             * returns the context for the shop
             *
             * @param {String} [shopId]
             * @param [locale]
             * @return {RestDataSource.Context}
             */
            shop: function (shopId, locale) {

                shopId = shopId || this.$.shopId;
                locale = locale || this.$.locale;

                var properties = {
                    shopId: shopId
                };

                if (locale) {
                    properties.locale = locale;
                }

                return this.getContext(properties);
            },

            /***
             *
             * returns the context for the user
             *
             * @param [userId]
             * @param [locale]
             * @return {RestDataSource.Context}
             */
            user: function (userId, locale) {
                userId = userId || this.$.shopId;
                locale = locale || this.$.locale;

                var properties = {
                    userId: userId
                };

                if (locale) {
                    properties.locale = locale;
                }

                return this.getContext(properties);
            }

        });

        SprdApiDataSource.SprdApiContext = RestDataSource.RestContext.inherit({
            getQueryParameters: function () {

                var parameter = {
                    mediaType: "json"
                };

                if (this.$properties && this.$properties.locale) {
                    parameter.locale = this.$properties.locale;
                }

                return _.defaults(parameter, this.callBase());
            }
        });

        return SprdApiDataSource;
    });<commit_msg>adjusted extractIdFromLocation method to work with proxy-middlware<commit_after>define(["sprd/data/SprdDataSource", "js/data/DataSource", "js/data/RestDataSource", "underscore", "sprd/data/SprdModel", "sprd/model/processor/DefaultProcessor", "sprd/model/processor/BasketProcessor", "sprd/model/processor/BasketItemProcessor", "sprd/data/SprdApiQueryComposer", "sprd/model/processor/UploadDesignProcessor", "JSON"],
    function (SprdDataSource, DataSource, RestDataSource, _, SprdModel, DefaultProcessor, BasketProcessor, BasketItemProcessor, SprdApiQueryComposer, UploadDesignProcessor, JSON) {

        var _formatProcessorCache = {},
            REMOTE = 'remote',
            rIdExtractor = /\/([^/]+)$/,
            ImageFormatProcessor = DataSource.FormatProcessor.inherit({

                ctor: function(type, format) {
                    this.$type = type;
                    this.$format = format;

                    this.callBase();
                },

                serialize: function(data) {

                    if (this.$format == REMOTE) {
                        return JSON.stringify({
                            href: data.image.src
                        });
                    }

                    var ret = new FormData();
                    ret.append('filedata', data.image.file);
                    return ret;
                },

                getContentType: function() {
                    if (this.$format === REMOTE) {
                        return "application/json";
                    }

                    return false;
                }
            });

        var SprdApiDataSource = SprdDataSource.inherit('sprd.data.SprdApiDataSourceClass', {

            defaults: {
                locale: "en_EU",
                parsePayloadOnCreate: false,
                parsePayloadOnUpdate: false,
                keepRawData: false
            },

            $defaultProcessorFactory: DefaultProcessor,

            $processors: {
                BasketProcessor: BasketProcessor,
                BasketItemProcessor: BasketItemProcessor,
                OrderItemProcessor: BasketItemProcessor,
                UploadDesignProcessor: UploadDesignProcessor
            },

            getQueryParameters: function (method, resource) {
                var ret = _.defaults({
                    mediaType: "json"
                }, this.callBase());

                if (resource.constructor.name.indexOf("Label") > -1) {
                    ret.fullData = true
                }
                return ret;

            },

            getFormatProcessor: function(action, model) {

                if (model && model.factory.prototype.constructor.name == "sprd.model.DesignUpload") {
                    var type = model.$.image.$.type,
                        format = model.$.image.$.file ? "file" : REMOTE,
                        cacheId = type + "_" + format;

                    if (!_formatProcessorCache[cacheId]) {
                        _formatProcessorCache[cacheId] = new ImageFormatProcessor(type, format);
                    }

                    return _formatProcessorCache[cacheId];
                }

                return this.callBase();
            },

            extractIdFromLocation: function(location, request) {
                var param = rIdExtractor.exec(location);

                if (param) {
                    return param[1];
                }

                return null;
            },

            createContext: function (contextModel, properties, parentContext) {
                return new SprdApiDataSource.SprdApiContext(this, contextModel, properties, parentContext);
            },

            getQueryComposer: function () {
                return SprdApiQueryComposer;
            },

            _getContextPath: function (data) {
                var match = /\/api\/v1\/(.*)$/.exec(data[this.$.determinateContextAttribute]);

                if (match) {
                    return match[1];
                }

                return this.callBase();
            },

            _parsePayloadOnUpdate: function (request, xhr) {

                var model = request.model;
                var configuration = this.$dataSourceConfiguration.getConfigurationForModelClass(model.factory);

                if (configuration.$.parseResponse === true) {
                    return true;
                }

                return this.callBase();
            },

            /***
             * returns the context for the shop
             *
             * @param {String} [shopId]
             * @param [locale]
             * @return {RestDataSource.Context}
             */
            shop: function (shopId, locale) {

                shopId = shopId || this.$.shopId;
                locale = locale || this.$.locale;

                var properties = {
                    shopId: shopId
                };

                if (locale) {
                    properties.locale = locale;
                }

                return this.getContext(properties);
            },

            /***
             *
             * returns the context for the user
             *
             * @param [userId]
             * @param [locale]
             * @return {RestDataSource.Context}
             */
            user: function (userId, locale) {
                userId = userId || this.$.shopId;
                locale = locale || this.$.locale;

                var properties = {
                    userId: userId
                };

                if (locale) {
                    properties.locale = locale;
                }

                return this.getContext(properties);
            }

        });

        SprdApiDataSource.SprdApiContext = RestDataSource.RestContext.inherit({
            getQueryParameters: function () {

                var parameter = {
                    mediaType: "json"
                };

                if (this.$properties && this.$properties.locale) {
                    parameter.locale = this.$properties.locale;
                }

                return _.defaults(parameter, this.callBase());
            }
        });

        return SprdApiDataSource;
    });<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'

import { Response } from '../api'
import { setActive } from './actions/Overlay'
import { BodyInput, CaptureCompletion } from './BodyInput'
import { BoostRules } from './Boosts'
import { Results } from './Results'
import Tabs from './Tabs'

const close = ({ closeOverlay }) => (

×

ESC

)

const Close = connect(
  null,
  dispatch => ({ closeOverlay: () => dispatch(setActive(false)) })
)(close)

const logo = ({ closeOverlay, src, alt, className }) => (

)

const Logo = connect(
  null,
  dispatch => ({ closeOverlay: () => dispatch(setActive(false)) })
)(logo)

const overlay = ({ active, children }) => {
  if (!active) {
    return null
  }

  return (

        {children}

  )
}

const Overlay = connect(
  ({ overlay }) => ({ active: overlay.active })
)(overlay)

const DefaultOverlay = ({ tabs, tabsOnChange, defaultTab, logoUrl }) => (
  <Overlay>
    <Close />

      <Logo src={logoUrl} alt='Logo' />
      <BodyInput />
      <BoostRules />

      <Tabs defaultTab={defaultTab} tabs={tabs} onChange={tabsOnChange} />

    <Response>
      <CaptureCompletion />
      <Results />
    </Response>
  </Overlay>
)

export { DefaultOverlay, Overlay, Close, Logo }
<commit_msg>Wrap body input and search when body has changed<commit_after>import React from 'react'
import { connect } from 'react-redux'

import { Response } from '../api'
import { setActive } from './actions/Overlay'
import { BodyInput, CaptureCompletion } from './BodyInput'
import { BoostRules } from './Boosts'
import { Results } from './Results'
import Tabs from './Tabs'
import { triggerSearch } from './actions/Search'

const close = ({ closeOverlay }) => (

×

ESC

)

const Close = connect(
  null,
  dispatch => ({ closeOverlay: () => dispatch(setActive(false)) })
)(close)

const logo = ({ closeOverlay, src, alt, className }) => (

)

const Logo = connect(
  null,
  dispatch => ({ closeOverlay: () => dispatch(setActive(false)) })
)(logo)

const overlay = ({ active, children }) => {
  if (!active) {
    return null
  }

  return (

        {children}

  )
}

const Overlay = connect(
  ({ overlay }) => ({ active: overlay.active })
)(overlay)

class wrappedBodyInput extends React.Component {
  componentDidUpdate() {
    this.props.triggerSearch()
  }

  render() {
    return (
      <BodyInput
        namespace='default'
        prefixBoosts={{
          'title': 0.03
        }}
        containsBoosts={{
          'title': 0.05
        }}
      />
    )
  }
}

const WrappedBodyInput = connect(
  ({ search }) => ({ body: search.body }),
  (dispatch) => ({ triggerSearch: () => dispatch(triggerSearch('default')) })
)(wrappedBodyInput)

const DefaultOverlay = ({ tabs, tabsOnChange, defaultTab, logoUrl }) => (
  <Overlay>
    <Close />

      <Logo src={logoUrl} alt='Logo' />
      <BodyInput />
      <BoostRules />

      <Tabs defaultTab={defaultTab} tabs={tabs} onChange={tabsOnChange} />

    <Response>
      <CaptureCompletion />
      <Results />
    </Response>
  </Overlay>
)

export { DefaultOverlay, Overlay, Close, Logo }
<|endoftext|>


<commit_before>go.app = function() {
    var vumigo = require("vumigo_v02");
    var App = vumigo.App;
    var Choice = vumigo.states.Choice;
    var ChoiceState = vumigo.states.ChoiceState;
    var PaginatedChoiceState = vumigo.states.PaginatedChoiceState;
    var EndState = vumigo.states.EndState;
    var FreeText = vumigo.states.FreeText;

    var GoNDOH = App.extend(function(self) {
        App.call(self, "state_start");
        var $ = self.$;
        // var interrupt = true;

        self.init = function() {
            // init services
        };

        // TIMEOUT HANDLING

        // override normal state adding
        self.add = function(name, creator) {
            self.states.add(name, function(name, opts) {
            /*if (!interrupt || !go.utils.timed_out(self.im))*/
                    return creator(name, opts);

                /*interrupt = false;
                opts = opts || {};
                opts.name = name;
                return self.states.create("state_timed_out", opts);*/
            });
        };

        // timeout 01
        self.states.add("state_timed_out", function(name, creator_opts) {
            return new ChoiceState(name, {
                question: $("You have an incomplete registration. Would you like to continue with this registration?"),
                choices: [
                    new Choice("continue", $("Yes")),
                    new Choice("restart", $("No, start a new registration"))
                ],
                next: function(choice) {
                    if (choice.value === "continue") {
                        return {
                            name: creator_opts.name,
                            creator_opts: creator_opts
                        };
                    } else if (choice.value === "restart") {
                        return "state_start";
                    }
                }
            });
        });

        // START STATE

        self.add("state_start", function(name) {
            self.im.user.answers = {};  // reset answers
            return self.states.create("state_check_PMTCT_registration");
        });

        // interstitial
        self.add("state_check_PMTCT_registration", function(name) {
            // if active PMTCT subscription, route to optout Flow
            // return self.states.create("state_optout_reason_menu")
            // else route to registration flow
            return self.states.create("state_check_MomConnect_registration");
        });

        // interstitial - checks details already saved in db
        self.add("state_check_MomConnect_registration", function(name) {
            return self.states.create("state_consent");
            // msisdn should be registered and active(?) on MomConnect...
            /*.search_by_address({"msisdn": self.im.user.addr}, self.im, null)
                .then(function(search) {
                    // check whether user is already registered
                    if (search.results.length > 0) {  // add necessary conditions to check
                        var identity = search.results[0];
                        console.log(identity);

                        // check if lang, consent and dob already stored and set
                        self.im.set_lang(identity.extra.language_choice);
                        self.im.user.set_answer("consent", identity.extra.consent);
                        self.im.user.set_answer("dob", identity.extra.dob;

                        // !consent_already_given
                        if (self.im.user.consent) {
                            return self.states.create("state_consent", dob_already_stored);
                        }

                        // !dob_already_stored
                        if (self.im.user.dob) {
                            return self.states.create("state_birth_year");
                        }

                        return self.states.create("state_hiv_messages");

                    } else {
                        // if not registered or inactive(?)
                        return self.states.create("state_end_not_registered");
                    }
                });*/
        });

        self.add("state_end_not_registered", function(name) {
            return new EndState(name, {
                text: $("You need to be registered to MomConnect to receive these messages. Please visit the nearest clinic to register."),
                next: "state_start"
            });
        });

        self.add("state_consent", function(name) {
            return new ChoiceState(name, {
                question: $("To register we need to collect, store & use your info. You may also get messages on public holidays & weekends. Do you consent?"),
                // error: ,
                choices: [
                    new Choice("yes", $("Yes")),
                    new Choice("no", $("No"))
                ],
                next: function(choice) {
                    if (choice.value === "yes") {
                        // set consent
                        self.im.user.set_answer("consent", "true");
                        /*if (self.im.user.dob) {
                            return "state_hiv_messages";
                        } else {
                            return "state_birth_year";
                        }*/
                        return "state_birth_year";
                    } else {
                        return "state_end_consent_refused";
                    }
                }
            });
        });

        self.add("state_end_consent_refused", function(name) {
            return new EndState(name, {
                text: $("Unfortunately without your consent, you cannot register to MomConnect. Thank you for using the MomConnect service. Goodbye."),
                next: "state_start"
            });
        });

        self.add("state_birth_year", function(name) {
            return new FreeText(name, {
                question: $("Please enter the year you were born (For example 1981)"),
                /*check: function(content) {
                    return (utils.check_valid_number(content)
                        & utils.check_number_in_range(content, "1900", utils.get_today().year)
                },*/
                next: function(content) {
                    self.im.user.set_answer("dob_year", content);
                    return "state_birth_month";
                }
            });
        });

        self.add("state_birth_month", function(name) {
            return new ChoiceState(name, {
                question: $("In which month were you born?"),
                choices: [
                    new Choice("jan", $("Jan")),
                    new Choice("feb", $("Feb")),
                    new Choice("mar", $("March")),
                    new Choice("apr", $("April")),
                    new Choice("may", $("May")),
                    new Choice("jun", $("June")),
                    new Choice("jul", $("July")),
                    new Choice("aug", $("August")),
                    new Choice("sep", $("Sep")),
                    new Choice("oct", $("Oct")),
                    new Choice("nov", $("Nov")),
                    new Choice("dec", $("Dec"))
                ],
                next: function(content) {
                    self.im.user.set_answer("dob_month", content);
                    return "state_birth_day";
                }
            });
        });

        self.add("state_birth_day", function(name) {
            return new FreeText(name, {
                question: $("Please enter the date of the month you were born (For example 21)"),
                /*check: function(content) {
                    utils.is_valid_date(dob)  // check here or in "next"
                },*/
                next: function(content) {
                    self.im.user.set_answer("dob_day", content);
                    /*self.im.user.set_answer("dob",
                        utils.get_entered_birth_date(self.im.user.dob_year, self.im.user.dob_month, content));*/

                    return "state_hiv_messages";
                }
            });
        });

        self.add("state_hiv_messages", function(name) {
            return new ChoiceState(name, {
                question: $("Would you like to receive messages about keeping your child HIV-negative?"),
                // error: ,
                choices: [
                    new Choice("yes", $("Yes")),
                    new Choice("no", $("No"))
                ],
                next: function(choice) {
                    if (choice.value === "yes") {
                        self.im.user.set_answer("hiv_opt_in", "true");
                        return "state_end_hiv_messages_confirm";
                    } else {
                        self.im.user.set_answer("hiv_opt_in", "false");
                        return "state_end_hiv_messages_declined";
                    }
                }
            });
        });

        self.add("state_end_hiv_messages_confirm", function(name) {
            return new EndState(name, {
                text: $("You will now start receiving messages about keeping your child HIV-negative. Thank you for using the MomConnect service. Goodbye."),
                next: "state_start"
            });
        });

        self.add("state_end_hiv_messages_declined", function(name) {
            return new EndState(name, {
                text: $("You have chosen to not receive messages about keeping your child HIV-negative. Thank you for using the MomConnect service. Goodbye."),
                next: "state_start"
            });
        });

        // start of OPT-OUT flow
        self.add("state_optout_reason_menu", function(name) {
            return new PaginatedChoiceState(name, {
                question: $("Why do you no longer want to receive messages related to keeping your baby HIV-negative?"),
                characters_per_page: 182,
                options_per_page: null,
                more: $('More'),
                back: $('Back'),
                // error: ,
                choices: [
                    new Choice("not_hiv_pos", $("I am not HIV-positive")),
                    new Choice("miscarriage", $("I had a miscarriage")),
                    new Choice("stillbirth", $("My baby was stillborn")),
                    new Choice("babyloss", $("My baby passed away")),
                    new Choice("not_useful", $("The messages are not useful")),
                    new Choice("other", $("Other"))
                ],
                next: function(choice) {
                    if (["not_hiv_pos", "not_useful", "other"].indexOf(choice.value) !== -1) {
                        return "state_end_optout";
                    } else {
                        return "state_loss_messages";
                    }
                }
            });
        });

        self.add("state_end_optout", function(name) {
            return new EndState(name, {
                text: $("Thank you. You will no longer receive PMTCT messages. You will still receive the MomConnect messages. To stop receiving these messages as well, please dial into *134*550*1#."),
                next: "state_start"
                // only opt user out of the PMTCT message set NOT MomConnect
            });
        });

        self.add("state_loss_messages", function(name) {
            return new ChoiceState(name, {
                question: $("We are sorry for your loss. Would you like to receive a small set of free messages from MomConnect that could help you in this difficult time?"),
                // error: ,
                choices: [
                    new Choice("yes", $("Yes")),
                    new Choice("no", $("No"))
                ],
                next: function(choice) {
                    if (choice.value === "yes") {
                        return "state_end_loss_optin";
                    } else {
                        return "state_end_loss_optout";
                    }
                }
            });
        });

        self.add("state_end_loss_optout", function(name) {
            return new EndState(name, {
                text: $("Thank you. You will no longer receive any messages from MomConnect. If you have any medical concerns, please visit your nearest clinic."),
                next: "state_start"
                // opt user out of the PMTCT & MomConnect message sets
            });
        });

        self.add("state_end_loss_optin", function(name) {
            return new EndState(name, {
                text: $("Thank you. You will receive support messages from MomConnect in the coming weeks."),
                next: "state_start"
                // opt user out of PMTCT & main MomConnect messages sets
                // opt user in to MomConnect loss support message set
            });
        });

    });

    return {
        GoNDOH: GoNDOH
    };
}();
<commit_msg>label bigger functionality placeholders<commit_after>go.app = function() {
    var vumigo = require("vumigo_v02");
    var App = vumigo.App;
    var Choice = vumigo.states.Choice;
    var ChoiceState = vumigo.states.ChoiceState;
    var PaginatedChoiceState = vumigo.states.PaginatedChoiceState;
    var EndState = vumigo.states.EndState;
    var FreeText = vumigo.states.FreeText;

    var GoNDOH = App.extend(function(self) {
        App.call(self, "state_start");
        var $ = self.$;
        // var interrupt = true;

        self.init = function() {
            // init services
        };

        // TIMEOUT HANDLING

        // override normal state adding
        self.add = function(name, creator) {
            self.states.add(name, function(name, opts) {
            /*if (!interrupt || !go.utils.timed_out(self.im))*/
                    return creator(name, opts);

                /*interrupt = false;
                opts = opts || {};
                opts.name = name;
                return self.states.create("state_timed_out", opts);*/
            });
        };

        // timeout 01
        self.states.add("state_timed_out", function(name, creator_opts) {
            return new ChoiceState(name, {
                question: $("You have an incomplete registration. Would you like to continue with this registration?"),
                choices: [
                    new Choice("continue", $("Yes")),
                    new Choice("restart", $("No, start a new registration"))
                ],
                next: function(choice) {
                    if (choice.value === "continue") {
                        return {
                            name: creator_opts.name,
                            creator_opts: creator_opts
                        };
                    } else if (choice.value === "restart") {
                        return "state_start";
                    }
                }
            });
        });

        // START STATE

        self.add("state_start", function(name) {
            self.im.user.answers = {};  // reset answers
            return self.states.create("state_check_PMTCT_subscription");
        });

        // interstitial
        self.add("state_check_PMTCT_subscription", function(name) {
            // functionality pseudo-logic:
            // if active PMTCT subscription, route to optout Flow
                // check identity  (get_identity)
                // check subscription (..? )
                // return self.states.create("state_optout_reason_menu")
            // else route to registration flow
            return self.states.create("state_check_MomConnect_registration");
        });

        // interstitial - checks details already saved in db
        self.add("state_check_MomConnect_registration", function(name) {
            return self.states.create("state_consent");
            // functionality pseudo-logic:
            // (msisdn should be registered and active(?) on MomConnect...)
            // get_identity_by_address / list_by_address
            // if registered/active
                // check/set lang, consent, dob
                // if consent not already given
                    // return state_consent
                // if dob not already captured
                    // return state_birth_year

                // return state_hiv_messages
            // else
                // return state_end_not_registered

            /*.search_by_address({"msisdn": self.im.user.addr}, self.im, null)
                .then(function(search) {
                    // check whether user is already registered
                    if (search.results.length > 0) {  // add necessary conditions to check
                        var identity = search.results[0];
                        console.log(identity);

                        // check if lang, consent and dob already stored and set
                        self.im.set_lang(identity.extra.language_choice);
                        self.im.user.set_answer("consent", identity.extra.consent);
                        self.im.user.set_answer("dob", identity.extra.dob;

                        // !consent_already_given
                        if (self.im.user.consent) {
                            return self.states.create("state_consent", dob_already_stored);
                        }

                        // !dob_already_stored
                        if (self.im.user.dob) {
                            return self.states.create("state_birth_year");
                        }

                        return self.states.create("state_hiv_messages");

                    } else {
                        // if not registered or inactive(?)
                        return self.states.create("state_end_not_registered");
                    }
                });*/
        });

        self.add("state_end_not_registered", function(name) {
            return new EndState(name, {
                text: $("You need to be registered to MomConnect to receive these messages. Please visit the nearest clinic to register."),
                next: "state_start"
            });
        });

        self.add("state_consent", function(name) {
            return new ChoiceState(name, {
                question: $("To register we need to collect, store & use your info. You may also get messages on public holidays & weekends. Do you consent?"),
                // error: ,
                choices: [
                    new Choice("yes", $("Yes")),
                    new Choice("no", $("No"))
                ],
                next: function(choice) {
                    if (choice.value === "yes") {
                        // set consent
                        self.im.user.set_answer("consent", "true");
                        // functionality pseudo-logic:
                        /*if (self.im.user.dob) {
                            return "state_hiv_messages";
                        } else {
                            return "state_birth_year";
                        }*/
                        return "state_birth_year";
                    } else {
                        return "state_end_consent_refused";
                    }
                }
            });
        });

        self.add("state_end_consent_refused", function(name) {
            return new EndState(name, {
                text: $("Unfortunately without your consent, you cannot register to MomConnect. Thank you for using the MomConnect service. Goodbye."),
                next: "state_start"
            });
        });

        self.add("state_birth_year", function(name) {
            return new FreeText(name, {
                question: $("Please enter the year you were born (For example 1981)"),
                /*check: function(content) {
                    return (utils.check_valid_number(content)
                        & utils.check_number_in_range(content, "1900", utils.get_today().year)
                },*/
                next: function(content) {
                    self.im.user.set_answer("dob_year", content);
                    return "state_birth_month";
                }
            });
        });

        self.add("state_birth_month", function(name) {
            return new ChoiceState(name, {
                question: $("In which month were you born?"),
                choices: [
                    new Choice("jan", $("Jan")),
                    new Choice("feb", $("Feb")),
                    new Choice("mar", $("March")),
                    new Choice("apr", $("April")),
                    new Choice("may", $("May")),
                    new Choice("jun", $("June")),
                    new Choice("jul", $("July")),
                    new Choice("aug", $("August")),
                    new Choice("sep", $("Sep")),
                    new Choice("oct", $("Oct")),
                    new Choice("nov", $("Nov")),
                    new Choice("dec", $("Dec"))
                ],
                next: function(content) {
                    self.im.user.set_answer("dob_month", content);
                    return "state_birth_day";
                }
            });
        });

        self.add("state_birth_day", function(name) {
            return new FreeText(name, {
                question: $("Please enter the date of the month you were born (For example 21)"),
                /*check: function(content) {
                    utils.is_valid_date(dob)  // check here or in "next"
                },*/
                next: function(content) {
                    self.im.user.set_answer("dob_day", content);
                    /*self.im.user.set_answer("dob",
                        utils.get_entered_birth_date(self.im.user.dob_year, self.im.user.dob_month, content));*/

                    return "state_hiv_messages";
                }
            });
        });

        self.add("state_hiv_messages", function(name) {
            return new ChoiceState(name, {
                question: $("Would you like to receive messages about keeping your child HIV-negative?"),
                // error: ,
                choices: [
                    new Choice("yes", $("Yes")),
                    new Choice("no", $("No"))
                ],
                next: function(choice) {
                    if (choice.value === "yes") {
                        self.im.user.set_answer("hiv_opt_in", "true");
                        return "state_end_hiv_messages_confirm";
                    } else {
                        self.im.user.set_answer("hiv_opt_in", "false");
                        return "state_end_hiv_messages_declined";
                    }
                }
            });
        });

        self.add("state_end_hiv_messages_confirm", function(name) {
            return new EndState(name, {
                text: $("You will now start receiving messages about keeping your child HIV-negative. Thank you for using the MomConnect service. Goodbye."),
                next: "state_start"
            });
        });

        self.add("state_end_hiv_messages_declined", function(name) {
            return new EndState(name, {
                text: $("You have chosen to not receive messages about keeping your child HIV-negative. Thank you for using the MomConnect service. Goodbye."),
                next: "state_start"
            });
        });

        // start of OPT-OUT flow
        self.add("state_optout_reason_menu", function(name) {
            return new PaginatedChoiceState(name, {
                question: $("Why do you no longer want to receive messages related to keeping your baby HIV-negative?"),
                characters_per_page: 182,
                options_per_page: null,
                more: $('More'),
                back: $('Back'),
                // error: ,
                choices: [
                    new Choice("not_hiv_pos", $("I am not HIV-positive")),
                    new Choice("miscarriage", $("I had a miscarriage")),
                    new Choice("stillbirth", $("My baby was stillborn")),
                    new Choice("babyloss", $("My baby passed away")),
                    new Choice("not_useful", $("The messages are not useful")),
                    new Choice("other", $("Other"))
                ],
                next: function(choice) {
                    if (["not_hiv_pos", "not_useful", "other"].indexOf(choice.value) !== -1) {
                        return "state_end_optout";
                    } else {
                        return "state_loss_messages";
                    }
                }
            });
        });

        self.add("state_end_optout", function(name) {
            return new EndState(name, {
                text: $("Thank you. You will no longer receive PMTCT messages. You will still receive the MomConnect messages. To stop receiving these messages as well, please dial into *134*550*1#."),
                next: "state_start"
                // only opt user out of the PMTCT message set NOT MomConnect
            });
        });

        self.add("state_loss_messages", function(name) {
            return new ChoiceState(name, {
                question: $("We are sorry for your loss. Would you like to receive a small set of free messages from MomConnect that could help you in this difficult time?"),
                // error: ,
                choices: [
                    new Choice("yes", $("Yes")),
                    new Choice("no", $("No"))
                ],
                next: function(choice) {
                    if (choice.value === "yes") {
                        return "state_end_loss_optin";
                    } else {
                        return "state_end_loss_optout";
                    }
                }
            });
        });

        self.add("state_end_loss_optout", function(name) {
            return new EndState(name, {
                text: $("Thank you. You will no longer receive any messages from MomConnect. If you have any medical concerns, please visit your nearest clinic."),
                next: "state_start"
                // opt user out of the PMTCT & MomConnect message sets
            });
        });

        self.add("state_end_loss_optin", function(name) {
            return new EndState(name, {
                text: $("Thank you. You will receive support messages from MomConnect in the coming weeks."),
                next: "state_start"
                // opt user out of PMTCT & main MomConnect messages sets
                // opt user in to MomConnect loss support message set
            });
        });

    });

    return {
        GoNDOH: GoNDOH
    };
}();
<|endoftext|>


<commit_before>'use strict';

var assert = require('chai').assert;
var config = require('../server/config');
var helper = require('../server/helper');
var items = require('../server/data/items');
var leagues = require('../server/data/leagues');
var competitions = require('../server/data/competitions');

describe('Data intergrity', () => {
    items.forEach(item => {
        describe(item.name, () => {
            config.years.availables.forEach(year => {
                describe(year, () => {
                    if (item.code != competitions.championsLeague.code && item.code != competitions.europaLeague.code) {
                        testTableData(item.code, year);
                    }

                    if (year == config.years.current) {
                        testScorersData(item.code, year);
                        testAssistsData(item.code, year);
                    }
                });
            });
        });
    });
});

function testTableData(code, year) {
    var tableData = helper.readJsonFile(helper.stringFormat(config.paths.tableData, code, year));

    it('Table should have the right number of teams', () => {
        var expectedNumber = code == leagues.bundesliga.code ? 18 : 20;
        assert.equal(expectedNumber, tableData.length);
    });
}

function testScorersData(code, year) {
    var scorersData = helper.readJsonFile(helper.stringFormat(config.paths.scorersData, code, year));

    it('Scorers should have the right number of players', () => {
        assert.equal(20, scorersData.length);
    });
}

function testAssistsData(code, year) {
    var assistsData = helper.readJsonFile(helper.stringFormat(config.paths.assistsData, code, year));

    it('Assists should have the right number of players', () => {
        assert.equal(20, assistsData.length);
    });
}<commit_msg>Add test to avoid empty data<commit_after>'use strict';

var assert = require('chai').assert;
var config = require('../server/config');
var helper = require('../server/helper');
var items = require('../server/data/items');
var leagues = require('../server/data/leagues');
var competitions = require('../server/data/competitions');

describe('Data intergrity', () => {
    items.forEach(item => {
        describe(item.name, () => {
            config.years.availables.forEach(year => {
                describe(year, () => {
                    if (item.code != competitions.championsLeague.code && item.code != competitions.europaLeague.code) {
                        testTableData(item.code, year);
                    }

                    if (year == config.years.current) {
                        testScorersData(item.code, year);
                        testAssistsData(item.code, year);
                    }
                });
            });
        });
    });
});

function testTableData(code, year) {
    var data = helper.readJsonFile(helper.stringFormat(config.paths.tableData, code, year));

    it('Table should have the right number of teams', () => {
        var expectedNumber = code == leagues.bundesliga.code ? 18 : 20;
        assert.lengthOf(data, expectedNumber);
    });

    testDataNotEmpty('Table', data);
}

function testScorersData(code, year) {
    var data = helper.readJsonFile(helper.stringFormat(config.paths.scorersData, code, year));

    it('Scorers should have the right number of players', () => {
        assert.lengthOf(data, 20);
    });

    testDataNotEmpty('Scorers', data);
}

function testAssistsData(code, year) {
    var data = helper.readJsonFile(helper.stringFormat(config.paths.assistsData, code, year));

    it('Assists should have the right number of players', () => {
        assert.lengthOf(data, 20);
    });

    testDataNotEmpty('Assists', data);
}

function testDataNotEmpty(dataName, data) {
    it(dataName + ' should not have empty data', () => {
        data.forEach((item, index) => {
            for (var key in item) {
                assert.notEqual('', item[key], 'Key "' + key + '" is empty for item ' + index);
            }
        });
    });
}<|endoftext|>