<commit_before>function ddg_spice_reddit(re) {

    //console.log(re["data"]["url"]);
    // validity check
    if (re["data"]["display_name"]) {
        if (re["data"]["over18"] === true) {
            // It would be better if over18s showed when safe
            // search is off. How?
            return;
        }

        var content, description, title, subscribers, created, url;
        var converter = Markdown.getSanitizingConverter();

        // removes any html to prevent leakage.
        description = converter.makeHtml(re["data"]["description"]).replace(/\n/gm, "-").replace(/<(?:.|\n)*?>/gm, "");
        description = description.slice(0, 100).replace(/\#+/,'')+"... ";

        url = re["data"]["url"];
        title = "" + re["data"]["title"] + '';
        subscribers = re["data"]["subscribers"];
        created = new Date(re["data"]["created"]*1000); // Shown in user's local time.
        content = "
Title:  " + title  + "
";
        content += "
Description: " + description + "
";
        content += "
Subscribers: " + subscribers + "
";
        content += "
Created: " + created + "
";

        items = new Array();
        items[0] = new Array();
        items[0]["a"] = content  ;
        items[0]["h"] = url;
        items[0]["s"] = "Reddit";
        items[0]["u"] = "http://www.reddit.com" + url;
        items[0]['i'] = "https://icons.duckduckgo.com/i/www.reddit.com.ico";

        //console.log(content);
    }

};

function link_parse(li) {
    if (typeof items == 'undefined') {
        return; // The subreddit is NSFW.
    }
    if (li['data']['children'][0]) {
        //console.log(root["title"]);
        var root = li['data']['children'][0].data;
        var content, title, url, permalink, score, author, date;
        title = root['title'];
        url = root['url'];
        permalink = root['permalink'];
        score = root['score'];
        author = root['author'];
        date = root['date'];

        if (root['over_18'] === true) {
            title += " (NSFW)";
        }

        content = "
Popular Link: ";
        content += ""+title+""+" by \
"+author+" with "+score+" karma. ";
        content += "(Discuss)
";

        items[0]["a"] += content;

    }

    nra(items);

};<commit_msg>made reddit dates more natural<commit_after>function ddg_spice_reddit(re) {
    //console.log(re["data"]["url"]);
    // validity check
    if (re["data"]["display_name"]) {
        if (re["data"]["over18"] === true) {
            // It would be better if over18s showed when safe
            // search is off. How?
            return;
        }

        var content, description, title, subscribers, created, url;
        var converter = Markdown.getSanitizingConverter();

        // removes any html to prevent leakage.
        description = converter.makeHtml(re["data"]["description"]).replace(/\n/gm, "-").replace(/<(?:.|\n)*?>/gm, "");
        description = description.slice(0, 100).replace(/\#+/,'')+"... ";

        url = re["data"]["url"];
        title = "" + re["data"]["title"] + '';
        subscribers = re["data"]["subscribers"];
        created = new Date(re["data"]["created"]*1000); // Shown in user's local time.
        content = "
Title:  " + title  + "
";
        content += "
Description: " + description + "
";
        content += "
Subscribers: " + subscribers + "
";
        content += "
Created: " + created.toDateString() + "
";

        items = new Array();
        items[0] = new Array();
        items[0]["a"] = content  ;
        items[0]["h"] = url;
        items[0]["s"] = "Reddit";
        items[0]["u"] = "http://www.reddit.com" + url;
        items[0]['i'] = "https://icons.duckduckgo.com/i/www.reddit.com.ico";

        //console.log(content);
    }

};

function link_parse(li) {
    if (typeof items == 'undefined') {
        return; // The subreddit is NSFW.
    }
    if (li['data']['children'][0]) {
        //console.log(root["title"]);
        var root = li['data']['children'][0].data;
        var content, title, url, permalink, score, author, created, date;
        var one_day = 1000*60*60*24; // One day in ms.
        var today = new Date();
        title = root['title'];
        url = root['url'];
        permalink = root['permalink'];
        score = root['score'];
        author = root['author'];
        created = new Date(root['created_utc']*1000);
        date = Math.floor((today.getTime()-created.getTime())/(one_day));
        date = (date === 0) ? Math.floor((today.getTime()-created.getTime())/(one_day/24)) + " hours ago" : date + " days ago";
        if (root['over_18'] === true) {
            title += " (NSFW)";
        }

        content = "
Popular Link: ";
        content += ""+title+""+" by \
"+author+" posted "+date+" with "+score+" karma. ";
        content += "(Discuss)
";

        items[0]["a"] += content;

    }

    nra(items);

};<|endoftext|>


<commit_before>var path = require('path'),
    expect = require('chai').expect,
    File = require('vinyl'),
    gutil = require('gulp-util'),
    isWindows = require('is-windows'),
    phpcs = require('../../index.js');

// NOTICE: All path to commands are specified related to the root of the
// project. This is because cwd is "../../" when the tests are run.

// Attach fixture path to PATH env so we could use just commands from fixture.
var sep = isWindows() ? ';' : ':';
process.env.PATH += sep + path.resolve('./test/fixture');

describe('PHPCS', function() {
    describe('CLI command resolver', function() {
        it('should fail if the CLI command cannot be found', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/missed'
            });

            plugin.on('error', function(error) {
                expect(error).to.be.an.instanceof(gutil.PluginError);
                expect(error.message).to.contain('Cannot find');
                expect(error.message).to.contain('./test/fixture/missed');
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command by relative path with win slashes', function(done) {
            var plugin = phpcs({
                bin: '.\\test\\fixture\\zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command by relative path with *nix slashes', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command by relative path without leading dot', function(done) {
            var plugin = phpcs({
                bin: 'test/fixture/zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command in PATH env by its name', function(done) {
            var plugin = phpcs({
                bin: 'zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });
    });

    describe('CLI tool runner', function() {
        it('should ignore empty files', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/error'
            });

            plugin.on('data', function(file) {
                expect(file.isNull()).to.be.true;
                expect(file.phpcsReport).to.be.undefined;

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php'
            }));
        });

        it('should do nothing if PHPCS exists with zero exit-code', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/zero'
            });

            plugin.on('data', function(file) {
                expect(file).to.have.property('phpcsReport');
                expect(file.phpcsReport).to.have.property('error').which.is.false;

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should retrieve stdout "as is" for fixable style errors', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/fixable_style_error'
            });

            plugin.on('data', function(file) {
                expect(file).to.have.property('phpcsReport');
                var report = file.phpcsReport;
                expect(report).to.be.an.instanceof(Object);
                expect(report).to.have.property('error').which.is.true;
                expect(report).to.have.property('output').which.is.a('string');
                expect(report.output).to.match(/Give me these lines\r?\nback!/);
                // File name should be also passed to PHPCS in special format
                expect(report.output).to.match(/^phpcs_input_file: \/src\/bad_file\.php\r?\n/);

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('Give me these lines\nback!')
            }));
        });

        it('should retrieve stdout "as is" for non-fixable style errors', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/style_error'
            });

            plugin.on('data', function(file) {
                expect(file).to.have.property('phpcsReport');
                var report = file.phpcsReport;
                expect(report).to.be.an.instanceof(Object);
                expect(report).to.have.property('error').which.is.true;
                expect(report).to.have.property('output').which.is.a('string');
                expect(report.output).to.match(/Give me these lines\r?\nback!/);
                // File name should be also passed to PHPCS in special format
                expect(report.output).to.match(/^phpcs_input_file: \/src\/bad_file\.php\r?\n/);

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('Give me these lines\nback!')
            }));
        });

        it('should retrieve error "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/error'
            });

            plugin.on('error', function(error) {
                expect(error).to.be.an.instanceof(gutil.PluginError);
                expect(error.message).to.be.equal('Execution of Code Sniffer Failed');
                expect(error).to.have.property('stdout');
                expect(error.stdout).to.contain('This is a test error.');

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });
    });

    describe('options builder', function() {
        var fakeFile = null;

        beforeEach(function() {
            fakeFile = new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            });
        });

        afterEach(function() {
            fakeFile = null;
        });

        it('should use only stdin switch by default', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.be.equal('-');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "severity" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                severity: 0
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--severity=0');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "warningSeverity" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                warningSeverity: 1
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--warning-severity=1');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "errorSeverity" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                errorSeverity: 2
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--error-severity=2');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "standard" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                standard: 'PSR2'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--standard=PSR2');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "encoding" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                encoding: 'utf8'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--encoding=utf8');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "report" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                report: 'summary'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--report=summary');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use "-s" flag if "showSniffCode" option is true', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                showSniffCode: true
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('-s');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "-s" flag if "showSniffCode" option is false', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                showSniffCode: false
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('-s');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "sniffs" option', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                sniffs: ['foo', 'bar', 'baz']
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                // Validate the option.
                expect(output).to.match(/--sniffs=([^\s]+)/);
                // Validate used sniffs.
                var usedSniffs = /--sniffs=([^\s]+)/.exec(output);
                expect(usedSniffs[1].split(',')).to.have.members(['foo', 'bar', 'baz']);

                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--sniffs" option if an empty array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                sniffs: []
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--sniffs');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--sniffs" option if not an array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                sniffs: 'test string'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--sniffs');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "exclude" option', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                exclude: ['foo', 'bar', 'baz']
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                var excludeArgs = /--exclude=([^\s]+)/.exec(output);
                expect(excludeArgs).to.be.not.null;
                expect(excludeArgs[1].split(',')).to.have.members(['foo', 'bar', 'baz']);

                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "ignore" option', function(done) {
          var paths = ['foo', 'bar', 'baz'];

          var plugin = phpcs({
              bin: './test/fixture/args',
              ignore: paths
          });

          plugin.on('data', function(file) {
              var output = file.phpcsReport.output.trim();
              var ignoreArgs = /--ignore=([^\s]+)/.exec(output);
              expect(ignoreArgs).to.be.not.null;
              expect(ignoreArgs[1].split(',')).to.have.members(paths);

              done();
          });

          plugin.write(fakeFile);
      });

        it('should not use "--exclude" option if an empty array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                exclude: []
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--exclude');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--exclude" option if not an array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                exclude: 'test string'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--exclude');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use "--colors" flag if "colors" option is true', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                colors: true
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--colors');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--colors" flag if "colors" option is false', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                colors: false
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--collors');
                done();
            });

            plugin.write(fakeFile);
        });
    });
});
<commit_msg>Added more tests for ignore option<commit_after>var path = require('path'),
    expect = require('chai').expect,
    File = require('vinyl'),
    gutil = require('gulp-util'),
    isWindows = require('is-windows'),
    phpcs = require('../../index.js');

// NOTICE: All path to commands are specified related to the root of the
// project. This is because cwd is "../../" when the tests are run.

// Attach fixture path to PATH env so we could use just commands from fixture.
var sep = isWindows() ? ';' : ':';
process.env.PATH += sep + path.resolve('./test/fixture');

describe('PHPCS', function() {
    describe('CLI command resolver', function() {
        it('should fail if the CLI command cannot be found', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/missed'
            });

            plugin.on('error', function(error) {
                expect(error).to.be.an.instanceof(gutil.PluginError);
                expect(error.message).to.contain('Cannot find');
                expect(error.message).to.contain('./test/fixture/missed');
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command by relative path with win slashes', function(done) {
            var plugin = phpcs({
                bin: '.\\test\\fixture\\zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command by relative path with *nix slashes', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command by relative path without leading dot', function(done) {
            var plugin = phpcs({
                bin: 'test/fixture/zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should find command in PATH env by its name', function(done) {
            var plugin = phpcs({
                bin: 'zero'
            });

            plugin.on('error', function(error) {
                // This should never happen.
                done(error);
            });

            plugin.on('data', function() {
                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });
    });

    describe('CLI tool runner', function() {
        it('should ignore empty files', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/error'
            });

            plugin.on('data', function(file) {
                expect(file.isNull()).to.be.true;
                expect(file.phpcsReport).to.be.undefined;

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php'
            }));
        });

        it('should do nothing if PHPCS exists with zero exit-code', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/zero'
            });

            plugin.on('data', function(file) {
                expect(file).to.have.property('phpcsReport');
                expect(file.phpcsReport).to.have.property('error').which.is.false;

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });

        it('should retrieve stdout "as is" for fixable style errors', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/fixable_style_error'
            });

            plugin.on('data', function(file) {
                expect(file).to.have.property('phpcsReport');
                var report = file.phpcsReport;
                expect(report).to.be.an.instanceof(Object);
                expect(report).to.have.property('error').which.is.true;
                expect(report).to.have.property('output').which.is.a('string');
                expect(report.output).to.match(/Give me these lines\r?\nback!/);
                // File name should be also passed to PHPCS in special format
                expect(report.output).to.match(/^phpcs_input_file: \/src\/bad_file\.php\r?\n/);

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('Give me these lines\nback!')
            }));
        });

        it('should retrieve stdout "as is" for non-fixable style errors', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/style_error'
            });

            plugin.on('data', function(file) {
                expect(file).to.have.property('phpcsReport');
                var report = file.phpcsReport;
                expect(report).to.be.an.instanceof(Object);
                expect(report).to.have.property('error').which.is.true;
                expect(report).to.have.property('output').which.is.a('string');
                expect(report.output).to.match(/Give me these lines\r?\nback!/);
                // File name should be also passed to PHPCS in special format
                expect(report.output).to.match(/^phpcs_input_file: \/src\/bad_file\.php\r?\n/);

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('Give me these lines\nback!')
            }));
        });

        it('should retrieve error "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/error'
            });

            plugin.on('error', function(error) {
                expect(error).to.be.an.instanceof(gutil.PluginError);
                expect(error.message).to.be.equal('Execution of Code Sniffer Failed');
                expect(error).to.have.property('stdout');
                expect(error.stdout).to.contain('This is a test error.');

                done();
            });

            plugin.write(new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            }));
        });
    });

    describe('options builder', function() {
        var fakeFile = null;

        beforeEach(function() {
            fakeFile = new File({
                path: '/src/bad_file.php',
                contents: new Buffer('test')
            });
        });

        afterEach(function() {
            fakeFile = null;
        });

        it('should use only stdin switch by default', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.be.equal('-');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "severity" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                severity: 0
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--severity=0');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "warningSeverity" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                warningSeverity: 1
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--warning-severity=1');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "errorSeverity" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                errorSeverity: 2
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--error-severity=2');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "standard" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                standard: 'PSR2'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--standard=PSR2');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "encoding" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                encoding: 'utf8'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--encoding=utf8');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "report" option "as is"', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                report: 'summary'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--report=summary');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use "-s" flag if "showSniffCode" option is true', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                showSniffCode: true
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('-s');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "-s" flag if "showSniffCode" option is false', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                showSniffCode: false
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('-s');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "sniffs" option', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                sniffs: ['foo', 'bar', 'baz']
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                // Validate the option.
                expect(output).to.match(/--sniffs=([^\s]+)/);
                // Validate used sniffs.
                var usedSniffs = /--sniffs=([^\s]+)/.exec(output);
                expect(usedSniffs[1].split(',')).to.have.members(['foo', 'bar', 'baz']);

                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--sniffs" option if an empty array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                sniffs: []
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--sniffs');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--sniffs" option if not an array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                sniffs: 'test string'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--sniffs');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "ignore" option', function(done) {
            var paths = ['foo', 'bar', 'baz'];

            var plugin = phpcs({
                bin: './test/fixture/args',
                ignore: paths
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                var ignoreArgs = /--ignore=([^\s]+)/.exec(output);
                expect(ignoreArgs).to.be.not.null;
                expect(ignoreArgs[1].split(',')).to.have.members(paths);

                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--ignore" option if an empty array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                ignore: []
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--ignore');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--ignore" option if not an array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                ignore: 'test string'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--ignore');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use passed in "exclude" option', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                exclude: ['foo', 'bar', 'baz']
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                var excludeArgs = /--exclude=([^\s]+)/.exec(output);
                expect(excludeArgs).to.be.not.null;
                expect(excludeArgs[1].split(',')).to.have.members(['foo', 'bar', 'baz']);

                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--exclude" option if an empty array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                exclude: []
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--exclude');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--exclude" option if not an array is passed in', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                exclude: 'test string'
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--exclude');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should use "--colors" flag if "colors" option is true', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                colors: true
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.contain('--colors');
                done();
            });

            plugin.write(fakeFile);
        });

        it('should not use "--colors" flag if "colors" option is false', function(done) {
            var plugin = phpcs({
                bin: './test/fixture/args',
                colors: false
            });

            plugin.on('data', function(file) {
                var output = file.phpcsReport.output.trim();
                expect(output).to.not.contain('--collors');
                done();
            });

            plugin.write(fakeFile);
        });
    });
});
<|endoftext|>


<commit_before>var game = {};

game.initialise = function() {
    common.require('draw');
    common.require('level');
    common.require('objects');
    common.require('userInterface');

    window.requestAnimFrame(game.drawLoop());
};

game.drawLoop = function() {
    requestAnimationFrame(game.drawLoop);
    draw(userInterface.elements.canvas, level.get(), 0, 0);
};<commit_msg>Call of draw function has been corrected<commit_after>var game = {};

game.initialise = function() {
    common.require('draw');
    common.require('level');
    common.require('objects');
    common.require('userInterface');

    window.requestAnimFrame(game.drawLoop());
};

game.drawLoop = function() {
    requestAnimationFrame(game.drawLoop);
    draw(userInterface.elements.canvas, level.get(), objects.list(), 0, 0);
};<|endoftext|>


<commit_before>alert("TEST");
<commit_msg>Load API request object into function app() and successfully log response.results to console<commit_after>//IIFE containing main tasks of page
(function(){
  'use strict';

  var url = "https://api.etsy.com/v2/listings/active.js?api_key=l3usap5o1yhtiz130c55s1fq&keywords=ninjas&includes=Images,Shop&sort_on=score&limit=48";
  fetchJSONP(url, app);

  //Fetches JSONP data from Etsy API
  function fetchJSONP(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    var script = document.createElement('script');

    window[callbackName] = function(data) {
        delete window[callbackName];
        document.body.removeChild(script);
        callback(data);
    };

    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.body.appendChild(script);
  }

  //function that will delegate other tasks to helper functions to manipulate data recieved from API
  function app(response) {
    var results = response.results;
    console.log(results);
  }

})();
<|endoftext|>


<commit_before>$(document).ready(function() {
  console.log('blog.js ready');
});<commit_msg>delete post.js file wc is unused<commit_after><|endoftext|>


<commit_before>$(document).ready(function() {

  /*
   * LOVELY INITIATIVES
   */

  // Initialize a temp array
  var tempfarray = [];

  // ID of the Google Spreadsheet
  var spreadsheetID = "13-ozrkaBha3CQIwP9J_FuEF3hnQpXYrKzVxNqS0Hzoo";

  // Make sure it is public or set to Anyone with link can view
  var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json";

  // Create Modal
  function getModal(itemid) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      var n = itemid;
      var ititle = entry[n].gsx$title.$t;
      var icategory = entry[n].gsx$category.$t;
      var isubcategory = entry[n].gsx$subcategory.$t;
      var idescription = entry[n].gsx$description.$t;
      var iwebsite = entry[n].gsx$website.$t;
      var iimage = entry[n].gsx$image.$t;
      var istatus = entry[n].gsx$status.$t;
      var iregion = entry[n].gsx$region.$t;
      var ifellow = entry[n].gsx$fellow.$t;
      var ischool = entry[n].gsx$school.$t;
      var istate = entry[n].gsx$state.$t;
      var istakeholders = entry[n].gsx$stakeholders.$t;
      var iresources = entry[n].gsx$resources.$t;
      var iactivity = entry[n].gsx$activity.$t;
      var idesiredoutcome = entry[n].gsx$desiredoutcome.$t;
      var iimpactachieved = entry[n].gsx$impactachieved.$t;
      var icohorts = entry[n].gsx$cohorts.$t;

      // Refreshes the Modal
      $('#myModalLabel').empty();
      $('#modal-body-1').empty();
      $('#modal-body-2').empty();
      $('.modal-footer').empty();

      $('#myModalLabel').append(ititle + '

' + iwebsite + '
');
      $('#modal-body-1').append('

Cohorts:
' + icohorts + '

Main Category:
' + icategory + '

Related Categories:
' + isubcategory +'

Fellow(s):
' + ifellow + '

Status:
' + istatus + '

School and State:
' + ischool + ', ' + istate + '

Region:
' + iregion + '

Stakeholders:
' + istakeholders + '

Resources:
' + iresources);
      $('#modal-body-2').append('

Description:
' + idescription + '

Activity:
' + iactivity + '

Desired Outcome:
' + idesiredoutcome + '

Impact Achieved:
' + iimpactachieved + '

Challenges faced and Plans to overcome:');

      $('#myModal').modal("show");

    });
  }

  // Append Data
  function appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts) {
    $('.list').append('
' + ititle + '
 ' + 'by ' + ifellow + '
Main Category: ' + icategory + '

' + idescription + '

');
  }

  // Get the Data from the spreadsheet using JSON
  function getData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);

      };
    });
  }

  // Filters data
  function filterData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var isubcategory = entry[i].gsx$subcategory.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        // Filters the cateogries
        function iscorrectcategory(kategori, subkategori, nombor) {
          for (var l = 0; l < tempfarray.length; l++) {
            if (kategori.indexOf(tempfarray[l]) < 0  && subkategori.indexOf(tempfarray[l]) < 0) {
              return false;
              break;
            } else if (l == tempfarray.length - 1) {
              appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
              break;
            }
          }
        };

        iscorrectcategory(icategory, isubcategory, i);

      };
    });
  }

  // Individual Filter Buttons
  function idvfilterData(filteredword, type) {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];

    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        if (type == "region") {
          if (iregion.indexOf(filteredword) >= 0) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
          }
        } else if (type = "status") {
          if (filteredword == istatus) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
          }
        };
      };
    });
  }

  // Search Query
  function searchedData(searchword) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var ischool = entry[i].gsx$school.$t;
        var istate = entry[i].gsx$state.$t;
        var istakeholders = entry[i].gsx$stakeholders.$t;
        var iresources = entry[i].gsx$resources.$t;
        var iactivity = entry[i].gsx$activity.$t;
        var idesiredoutcome = entry[i].gsx$desiredoutcome.$t;
        var iimpactachieved = entry[i].gsx$impactachieved.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        // Set to lower case
        searchword = searchword.toLowerCase();
        var ltitle = ititle.toLowerCase();
        var lcategory = icategory.toLowerCase();
        var ldescription = idescription.toLowerCase();
        var lstatus = istatus.toLowerCase();
        var lregion = iregion.toLowerCase();
        var lfellow = ifellow.toLowerCase();
        var lschool = ischool.toLowerCase();
        var lstate = istate.toLowerCase();
        var lstakeholders = istakeholders.toLowerCase();
        var lresources = iresources.toLowerCase();
        var lactivity = iactivity.toLowerCase();
        var ldesiredoutcome = idesiredoutcome.toLowerCase();
        var limpactachieved = iimpactachieved.toLowerCase();

        if (ltitle.indexOf(searchword) >= 0 || ldescription.indexOf(searchword) >= 0 || lcategory.indexOf(searchword) >= 0 || lstatus.indexOf(searchword) >= 0 || lregion.indexOf(searchword) >= 0 || lfellow.indexOf(searchword) >= 0 || lschool.indexOf(searchword) >= 0 || lstate.indexOf(searchword) >= 0 || lstakeholders.indexOf(searchword) >= 0 || lresources.indexOf(searchword) >= 0 || lactivity.indexOf(searchword) >= 0 || ldesiredoutcome.indexOf(searchword) >= 0 || limpactachieved.indexOf(searchword) >= 0 || icohorts.indexOf(searchword) >= 0) {
          appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
        };
      };
    });
  }

  // Create categories button function
  /* function getCategories() {
    $.getJSON(url, function(data) {
      var cattemp = [];
      var entry = data.feed.entry;

      function appendCategory(category) {
        $("#testkategori").append('
<input type="checkbox" class="filtercheckbox" id="filter-' + category + '" />' + category + '
')

        var script = document.createElement("script");

        script.innerHTML = '$("#filter-' + category + ').click(function(){checkboxfilter("' + category + ',"filter-' + category + '");});'

        document.footer.appendChild(script);
      }

      for (var i = 0; i < entry.length; i++) {
        var icategory = entry[i].gsx$category.$t;

        if (cattemp.indexOf(icategory) < 0) {
          cattemp.push(icategory);
          appendCategory(icategory);
        }
      }
    });
  } */

  // Generate the Initial Data
  // getCategories();
  getData();

  // Links the title of the Iniative to its profile page
  $(".list").delegate(".name", "click", function() {
    var id = $(this).attr("id");
    getModal(id);
  });

  // These are the buttons function
  // Always Lucky - Random list generator
  $('#filter-random').click(function() {
    $.getJSON(url, function(data) {
      $('input[class=filtercheckbox]').attr('checked', false);
      tempfarray = [];

      var entry = data.feed.entry;
      var max = entry.length;
      var min = 0;

      $(".list").empty();

      // Generate random item
      var rn = Math.floor(Math.random() * (max + min)) + min;

      // Append the random item unto the database
      var inum = rn;
      var ititle = entry[rn].gsx$title.$t;
      var icategory = entry[rn].gsx$category.$t;
      var idescription = entry[rn].gsx$description.$t;
      var iwebsite = entry[rn].gsx$website.$t;
      var iimage = entry[rn].gsx$image.$t;
      var istatus = entry[rn].gsx$status.$t;
      var iregion = entry[rn].gsx$region.$t;
      var ifellow = entry[rn].gsx$fellow.$t;
      var icohorts = entry[rn].gsx$cohorts.$t;

      appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
    });
  });

  // Search Button
  $("#search_button").click(function() {
    var user_input = $(".searched").val();
    searchedData(user_input);
  });

  // Search Keypress
  $(".searched").keypress(function(event) {
    if (event.which == 13) {
      var user_input = $(".searched").val();
      searchedData(user_input);
    }
  });

  // Pushes or removes an element from the array that needs to be filtered
  function checkboxfilter(categoryp, id) {
    if (document.getElementById(id).checked) {
      tempfarray.push(categoryp);
      filterData();
    } else {
      var ssindex = tempfarray.indexOf(categoryp);
      if (ssindex > -1) {
        tempfarray.splice(ssindex, 1);
      }
      if (tempfarray.length <= 0) {
        getData();
      } else {
        filterData();
      }
    }
  }

  // Subject Specific
  $('#filter-subject-specific').click(function() {
    checkboxfilter("Subject Specific", "filter-subject-specific");
  });

  // Teaching Quality
  $('#filter-teaching-quality').click(function() {
    checkboxfilter("Teaching Quality", "filter-teaching-quality");
  });

  // Personal Development
  $('#filter-development').click(function() {
    checkboxfilter("Development", "filter-development");
  });

  // English Oral Profiency
  $('#filter-english-oral-fluency').click(function() {
    checkboxfilter("English Oral Fluency", "filter-english-oral-fluency");
  });

  // Literacy
  $('#filter-literacy').click(function() {
    checkboxfilter("Literacy", "filter-literacy");
  });

  // Numeracy
  $("#filter-numeracy").click(function() {
    checkboxfilter("Numeracy", "filter-numeracy");
  });

  // Tertiary Education
  $("#filter-tertiary-education").click(function() {
    checkboxfilter("Tertiary Education", "filter-tertiary-education");
  });

  // Learning Environment
  $("#filter-learning-environment").click(function() {
    checkboxfilter("Learning Environment", "filter-learning-environment");
  });

  // Participation
  $("#filter-participation").click(function() {
    checkboxfilter("Participation", "filter-participation");
  });

  // North
  $("#filter-north").click(function() {
    idvfilterData("North", "region");
  });

  // South
  $("#filter-east").click(function() {
    idvfilterData("East", "region");
  });

  // West
  $("#filter-west").click(function() {
    idvfilterData("West", "region");
  });

  // South
  $("#filter-south").click(function() {
    idvfilterData("South", "region");
  });

  // Active
  $("#filter-active").click(function() {
    idvfilterData("Active", "status");
  });

  // Inactive
  $("#filter-inactive").click(function() {
    idvfilterData("Inactive", "status");
  });

  // wat
  $("#filter-notwat").click(function() {
    getModal(1);
  });

  // Show all
  $('#filter-none').click(function() {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];
    getData();
  });
});
<commit_msg>Update index.js<commit_after>$(document).ready(function() {

  /*
   * LOVELY INITIATIVES
   */

  // Initialize a temp array
  var tempfarray = [];

  // ID of the Google Spreadsheet
  var spreadsheetID = "13-ozrkaBha3CQIwP9J_FuEF3hnQpXYrKzVxNqS0Hzoo";

  // Make sure it is public or set to Anyone with link can view
  var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/od6/public/values?alt=json";

  // Create Modal
  function getModal(itemid) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      var n = itemid;
      var ititle = entry[n].gsx$title.$t;
      var icategory = entry[n].gsx$category.$t;
      var isubcategory = entry[n].gsx$subcategory.$t;
      var idescription = entry[n].gsx$description.$t;
      var iwebsite = entry[n].gsx$website.$t;
      var iimage = entry[n].gsx$image.$t;
      var istatus = entry[n].gsx$status.$t;
      var iregion = entry[n].gsx$region.$t;
      var ifellow = entry[n].gsx$fellow.$t;
      var ischool = entry[n].gsx$school.$t;
      var istate = entry[n].gsx$state.$t;
      var istakeholders = entry[n].gsx$stakeholders.$t;
      var iresources = entry[n].gsx$resources.$t;
      var iactivity = entry[n].gsx$activity.$t;
      var idesiredoutcome = entry[n].gsx$desiredoutcome.$t;
      var iimpactachieved = entry[n].gsx$impactachieved.$t;
      var icohorts = entry[n].gsx$cohorts.$t;

      // Refreshes the Modal
      $('#myModalLabel').empty();
      $('#modal-body-1').empty();
      $('#modal-body-2').empty();
      $('.modal-footer').empty();

      $('#myModalLabel').append(ititle + '

' + iwebsite + '
');
      $('#modal-body-1').append('

Cohorts:
' + icohorts + '

Main Category:
' + icategory + '

Related Categories:
' + isubcategory + '

Fellow(s):
' + ifellow + '

Status:
' + istatus + '

School and State:
' + ischool + ', ' + istate + '

Region:
' + iregion + '

Stakeholders:
' + istakeholders + '

Resources:
' + iresources);
      $('#modal-body-2').append('

Description:
' + idescription + '

Activity:
' + iactivity + '

Desired Outcome:
' + idesiredoutcome + '

Impact Achieved:
' + iimpactachieved + '

Challenges faced and Plans to overcome:');

      $('#myModal').modal("show");

    });
  }

  // Append Data
  function appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts) {
    $('.list').append('
' + ititle + '
 ' + 'by ' + ifellow + '
Main Category: ' + icategory + '

' + idescription + '

');
  }

  // Get the Data from the spreadsheet using JSON
  function getData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);

      };
    });
  }

  // Filters data
  function filterData() {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var isubcategory = entry[i].gsx$subcategory.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        // Filters the cateogries
        function iscorrectcategory(kategori, subkategori, nombor) {
          for (var l = 0; l < tempfarray.length; l++) {
            if (kategori.indexOf(tempfarray[l]) < 0 && subkategori.indexOf(tempfarray[l]) < 0) {
              return false;
              break;
            } else if (l == tempfarray.length - 1) {
              appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
              break;
            }
          }
        };

        iscorrectcategory(icategory, isubcategory, i);

      };
    });
  }

  // Individual Filter Buttons
  function idvfilterData(filteredword, type) {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];

    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        if (type == "region") {
          if (iregion.indexOf(filteredword) >= 0) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
          }
        } else if (type = "status") {
          if (filteredword == istatus) {
            appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
          }
        };
      };
    });
  }

  // Search Query
  function searchedData(searchword) {
    $.getJSON(url, function(data) {

      var entry = data.feed.entry;

      $(".list").empty();

      for (var i = 0; i < entry.length; i++) {
        var inum = i;
        var ititle = entry[i].gsx$title.$t;
        var icategory = entry[i].gsx$category.$t;
        var idescription = entry[i].gsx$description.$t;
        var iwebsite = entry[i].gsx$website.$t;
        var iimage = entry[i].gsx$image.$t;
        var istatus = entry[i].gsx$status.$t;
        var iregion = entry[i].gsx$region.$t;
        var ifellow = entry[i].gsx$fellow.$t;
        var ischool = entry[i].gsx$school.$t;
        var istate = entry[i].gsx$state.$t;
        var istakeholders = entry[i].gsx$stakeholders.$t;
        var iresources = entry[i].gsx$resources.$t;
        var iactivity = entry[i].gsx$activity.$t;
        var idesiredoutcome = entry[i].gsx$desiredoutcome.$t;
        var iimpactachieved = entry[i].gsx$impactachieved.$t;
        var icohorts = entry[i].gsx$cohorts.$t;

        // Set to lower case
        searchword = searchword.toLowerCase();
        var ltitle = ititle.toLowerCase();
        var lcategory = icategory.toLowerCase();
        var ldescription = idescription.toLowerCase();
        var lstatus = istatus.toLowerCase();
        var lregion = iregion.toLowerCase();
        var lfellow = ifellow.toLowerCase();
        var lschool = ischool.toLowerCase();
        var lstate = istate.toLowerCase();
        var lstakeholders = istakeholders.toLowerCase();
        var lresources = iresources.toLowerCase();
        var lactivity = iactivity.toLowerCase();
        var ldesiredoutcome = idesiredoutcome.toLowerCase();
        var limpactachieved = iimpactachieved.toLowerCase();

        if (ltitle.indexOf(searchword) >= 0 || ldescription.indexOf(searchword) >= 0 || lcategory.indexOf(searchword) >= 0 || lstatus.indexOf(searchword) >= 0 || lregion.indexOf(searchword) >= 0 || lfellow.indexOf(searchword) >= 0 || lschool.indexOf(searchword) >= 0 || lstate.indexOf(searchword) >= 0 || lstakeholders.indexOf(searchword) >= 0 || lresources.indexOf(searchword) >= 0 || lactivity.indexOf(searchword) >= 0 || ldesiredoutcome.indexOf(searchword) >= 0 || limpactachieved.indexOf(searchword) >= 0 || icohorts.indexOf(searchword) >= 0) {
          appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
        };
      };
    });
  }

  // Create categories button function
  function getCategories() {
    $.getJSON(url, function(data) {
      var cattemp = [];
      var entry = data.feed.entry;

      function appendCategory(category) {
        $("#mainkategories").append('
<input type="checkbox" class="filtercheckbox" id="filter-' + category + '" />' + category + '
')
      }

      for (var i = 0; i < entry.length; i++) {
        var icategory = entry[i].gsx$category.$t;

        if (cattemp.indexOf(icategory) < 0) {
          cattemp.push(icategory);
          appendCategory(icategory);
        }
      }
    });
  }

  // Generate the Initial Data
  getCategories();
  getData();

  // Links the title of the Iniative to its profile page
  $(".list").delegate(".name", "click", function() {
    var id = $(this).attr("id");
    getModal(id);
  });

  // These are the buttons function
  // Always Lucky - Random list generator
  $('#filter-random').click(function() {
    $.getJSON(url, function(data) {
      $('input[class=filtercheckbox]').attr('checked', false);
      tempfarray = [];

      var entry = data.feed.entry;
      var max = entry.length;
      var min = 0;

      $(".list").empty();

      // Generate random item
      var rn = Math.floor(Math.random() * (max + min)) + min;

      // Append the random item unto the database
      var inum = rn;
      var ititle = entry[rn].gsx$title.$t;
      var icategory = entry[rn].gsx$category.$t;
      var idescription = entry[rn].gsx$description.$t;
      var iwebsite = entry[rn].gsx$website.$t;
      var iimage = entry[rn].gsx$image.$t;
      var istatus = entry[rn].gsx$status.$t;
      var iregion = entry[rn].gsx$region.$t;
      var ifellow = entry[rn].gsx$fellow.$t;
      var icohorts = entry[rn].gsx$cohorts.$t;

      appendData(inum, ititle, icategory, idescription, iwebsite, iimage, iregion, ifellow, icohorts);
    });
  });

  // Search Button
  $("#search_button").click(function() {
    var user_input = $(".searched").val();
    searchedData(user_input);
  });

  // Search Keypress
  $(".searched").keypress(function(event) {
    if (event.which == 13) {
      var user_input = $(".searched").val();
      searchedData(user_input);
    }
  });

  // Pushes or removes an element from the array that needs to be filtered
  function checkboxfilter(categoryp, id) {
    if (document.getElementById(id).checked) {
      tempfarray.push(categoryp);
      filterData();
    } else {
      var ssindex = tempfarray.indexOf(categoryp);
      if (ssindex > -1) {
        tempfarray.splice(ssindex, 1);
      }
      if (tempfarray.length <= 0) {
        getData();
      } else {
        filterData();
      }
    }
  }

  $('#mainkategories').delegate(".filtercheckbox", "click", function() {
    var id = $(this).attr("id");
    var categoryp = $(this).attr("id").replace('filter-', '');

    checkboxfilter(categoryp, id);
  });

  // North
  $("#filter-north").click(function() {
    idvfilterData("North", "region");
  });

  // South
  $("#filter-east").click(function() {
    idvfilterData("East", "region");
  });

  // West
  $("#filter-west").click(function() {
    idvfilterData("West", "region");
  });

  // South
  $("#filter-south").click(function() {
    idvfilterData("South", "region");
  });

  // Active
  $("#filter-active").click(function() {
    idvfilterData("Active", "status");
  });

  // Inactive
  $("#filter-inactive").click(function() {
    idvfilterData("Inactive", "status");
  });

  // wat
  $("#filter-notwat").click(function() {
    getModal(1);
  });

  // Show all
  $('#filter-none').click(function() {
    $('input[class=filtercheckbox]').attr('checked', false);
    tempfarray = [];
    getData();
  });
});
<|endoftext|>


<commit_before>//nomensa
require(['modules/generate_player'], function(player) {
  $(player);
});

//set up sticky headings
require(['modules/stickyheaders'], function(setupStickyHeaders) {
  setupStickyHeaders();
});

// scrolling down and up
require(['modules/anchor_scrolling'], function(scrollToAnchor) {
  $("#markdown-toc a").on('click', function() {
    scrollToAnchor($(this).attr('href'));
  });
  $("#contents").on("click", function() {
    scrollToAnchor('html');
  });
});

require(['modules/magna-charta.min'], function() {
  $(".horizontal-bar-chart").each(function(i, item) {
    var opts = {
      outOf: 70,
      autoOutdent: true
    }
    if($(item).hasClass("mc-stacked")) {
      opts.barPadding = 5;
    } else if(!$(item).hasClass("mc-negative")) {
      opts.barPadding = 2;
    }

    // some special cases
    $.magnaCharta($(item), opts);
  });
});

<commit_msg>add proportional breakdown chart functionality back in<commit_after>//nomensa
require(['modules/generate_player'], function(player) {
  $(player);
});

//set up sticky headings
require(['modules/stickyheaders'], function(setupStickyHeaders) {
  setupStickyHeaders();
});

// scrolling down and up
require(['modules/anchor_scrolling'], function(scrollToAnchor) {
  $("#markdown-toc a").on('click', function() {
    scrollToAnchor($(this).attr('href'));
  });
  $("#contents").on("click", function() {
    scrollToAnchor('html');
  });
});

require(['modules/magna-charta.min'], function() {
  $(".horizontal-bar-chart").each(function(i, item) {
    var opts = {
      outOf: 70,
      autoOutdent: true
    }
    if($(item).hasClass("mc-stacked")) {
      opts.barPadding = 5;
    } else if(!$(item).hasClass("mc-negative")) {
      opts.barPadding = 2;
    }

    // some special cases
    $.magnaCharta($(item), opts);
  });
  $('.proportional.breakdown-chart tbody tr td:first-child').css('height', function(index) {
    var height = +($(this).text().replace('%', '')) * 4;
    return height;
  });
});

<|endoftext|>


<commit_before>(function() {
  'use strict';
  var api = 'https://46.101.48.218:4430';
  $(document).ready(function() {
    var url = api + '/resources/';
    getManifest(url);
  });

  // Gets the Manifests in JSON
  function getManifest(url, resource) {
    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.responseType = 'json';
    req.onload = function() {
      if (req.status === 200) {
        var json = req.response;
        if(resource) {
          var maxDownloads = 0;
          guardabosques(json, maxDownloads, resource);
        } else {
          addResources(json);
        }
      } else {
        console.error(Error('XMLHttpRequest Error: ' + req.statusText));
      }
    };
    req.onerror = function() {
      console.error(Error('Network Error'));
    };
    req.send();
  }

  // Adds the resources to the content table
  function addResources(data) {
    var tbody = $("tbody");
    data.forEach(function(resource) {
      var row = getRow(resource);
      tbody.append(row);
    });
    clickResource();
  }

  // When click in a resource gets the respective url regarding the protocol
  function clickResource() {
    $('.resource').on('click', 'button', function(event){
      event.preventDefault();
      var url = api + '/resource/' + resource.attr('id');
      switch ($(this).attr('id')) {
        case "h11":
          url = url + '/h11';
          break;
        case "h2":
          url = url + '/h2';
          break;
        case "s31":
          url = url + '/s31';
          break;
        default:
          console.error(Error('bad request'));
          break;
        }
        var resource =  $(this).closest('.resource');
        resource.addClass('downloading');
        resource.find('button').prop('disabled', true);
        getManifest(url, resource);
      });
  }

  // Auxiliar function
  function getRow(resource) {
    var row = '
'+resource.name+'	';
    resource.protocols.forEach(function(protocol) {
      row = row + '<button type="button" id="';
      switch(protocol){
        case "h11":
          row = row + 'h11" class="btn btn-xs btn-default">HTTP/1.1';
        break;
        case "s31":
          row = row + 's31" class="btn btn-xs btn-success">SPDY/3.1';
        break;
        case "h2":
          row = row + 'h2" class="btn btn-xs btn-primary">HTTP/2';
        break;
      }
      row = row + '</button>	';
    });
    row = row + '
';
    return row;
  }

})();
<commit_msg>Fixes resource links<commit_after>(function() {
  'use strict';
  var api = 'https://46.101.48.218:4430';
  $(document).ready(function() {
    var url = api + '/resources/';
    getManifest(url);
  });

  // Gets the Manifests in JSON
  function getManifest(url, resource) {
    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.responseType = 'json';
    req.onload = function() {
      if (req.status === 200) {
        var json = req.response;
        if(resource) {
          var maxDownloads = 0;
          guardabosques(json, maxDownloads, resource);
        } else {
          addResources(json);
        }
      } else {
        console.error(Error('XMLHttpRequest Error: ' + req.statusText));
      }
    };
    req.onerror = function() {
      console.error(Error('Network Error'));
    };
    req.send();
  }

  // Adds the resources to the content table
  function addResources(data) {
    var tbody = $("tbody");
    data.forEach(function(resource) {
      var row = getRow(resource);
      tbody.append(row);
    });
    clickResource();
  }

  // When click in a resource gets the respective url regarding the protocol
  function clickResource() {
    $('.resource').on('click', 'button', function(event){
      event.preventDefault();
      var resource =  $(this).closest('.resource');
      resource.addClass('downloading');
      resource.find('button').prop('disabled', true);

      var url = api + '/resource/' + resource.attr('id');
      switch ($(this).attr('id')) {
        case "h11":
          url = url + '/h11';
          break;
        case "h2":
          url = url + '/h2';
          break;
        case "s31":
          url = url + '/s31';
          break;
        default:
          console.error(Error('bad request'));
          break;
        }
        getManifest(url, resource);
      });
  }

  // Auxiliar function
  function getRow(resource) {
    var row = '
'+resource.name+'	';
    resource.protocols.forEach(function(protocol) {
      row = row + '<button type="button" id="';
      switch(protocol){
        case "h11":
          row = row + 'h11" class="btn btn-xs btn-default">HTTP/1.1';
        break;
        case "s31":
          row = row + 's31" class="btn btn-xs btn-success">SPDY/3.1';
        break;
        case "h2":
          row = row + 'h2" class="btn btn-xs btn-primary">HTTP/2';
        break;
      }
      row = row + '</button>	';
    });
    row = row + '
';
    return row;
  }

})();
<|endoftext|>


<commit_before>(function($) {
    window.bootSource = function() {
        if(window.location.pathname.match(/source\/{0,1}$/gi) !== null) {
            $.ajax({
                url: "api/packages/" + $('#tree').data("package-name") + "/versions/" + $('#tree').data('package-version') + "/sourceTree",
                crossDomain:true,
                xhrFields: {
                    withCredentials: true
                }
            }).done(function(result){
                if(result.tree.length > 0){
                    // Select the first file in 'root'
                    for(var node of result.tree){
                        if(node.nodes === undefined){
                            node.state.selected = true;
                            loadSource(node.href);
                            break;
                        }
                    }
                    $('#tree').treeview(
                        {
                            data: result.tree,
                            levels: 1,
                            emptyIcon: "glyphicon glyphicon-file",
                            expandIcon: "glyphicon glyphicon-folder-close",
                            collapseIcon: "glyphicon glyphicon-folder-open",
                            onNodeSelected: function(event, data) {
                                loadSource(data.href);
                            }
                        });
                    $('#tree').fadeIn();
                }
                else{
                    $('#source-not-found').fadeIn();
                }

            });
        };
    };

    var loadSource = function(href){
        $('#source-container').hide();
        $.ajax({
            url: "api/packages/" + $('#tree').data("package-name") + "/versions/"+ $('#tree').data('package-version') + "/source/" + href,
            crossDomain:true,
            xhrFields: {
            withCredentials: true
            }
        }).done(function(result){
            if(result.source !== undefined){
                $('#code').html(result.source);
                $('#source-container').fadeIn();

                // Highlight code
                $('pre code').each(function(i, block) {
                    hljs.highlightBlock(block);
                    hljs.lineNumbersBlock(block);
                });
            }
        });
    }

})($jq);<commit_msg>for of to for<commit_after>(function($) {
    window.bootSource = function() {
        if(window.location.pathname.match(/source\/{0,1}$/gi) !== null) {
            $.ajax({
                url: "api/packages/" + $('#tree').data("package-name") + "/versions/" + $('#tree').data('package-version') + "/sourceTree",
                crossDomain:true,
                xhrFields: {
                    withCredentials: true
                }
            }).done(function(result){
                if(result.tree.length > 0){
                    // Select the first file in 'root'
                    for(var i = 0; i < result.tree.length; i++) {
                        var node = result.tree[i];
                        if(node.nodes === undefined){
                            node.state.selected = true;
                            loadSource(node.href);
                            break;
                        }
                    }
                    $('#tree').treeview(
                        {
                            data: result.tree,
                            levels: 1,
                            emptyIcon: "glyphicon glyphicon-file",
                            expandIcon: "glyphicon glyphicon-folder-close",
                            collapseIcon: "glyphicon glyphicon-folder-open",
                            onNodeSelected: function(event, data) {
                                loadSource(data.href);
                            }
                        });
                    $('#tree').fadeIn();
                }
                else{
                    $('#source-not-found').fadeIn();
                }

            });
        };
    };

    var loadSource = function(href){
        $('#source-container').hide();
        $.ajax({
            url: "api/packages/" + $('#tree').data("package-name") + "/versions/"+ $('#tree').data('package-version') + "/source/" + href,
            crossDomain:true,
            xhrFields: {
            withCredentials: true
            }
        }).done(function(result){
            if(result.source !== undefined){
                $('#code').html(result.source);
                $('#source-container').fadeIn();

                // Highlight code
                $('pre code').each(function(i, block) {
                    hljs.highlightBlock(block);
                    hljs.lineNumbersBlock(block);
                });
            }
        });
    }

})($jq);<|endoftext|>


<commit_before>function setLab() {
    selectedLab = document.querySelectorAll(".lab-selected").item(0).innerHTML;
    console.log("Set Lab To: " + selectedLab);
    reloadData();
}

function reloadData() {
    populateIngredientList(0);
    populateAllIngredients();
}

function ingredientList(recipe) {
    var list = "
 " + recipe['name'] + "
";
    list += "
";
    for (var j = 0; j < recipe['ingredients'].length; ++j) {
        list += "
" + recipe['ingredients'][j] + "
";
    }
    list += "
";
    return list;
}

function singleRecipeModal(recipe_name) {
    var currentLab = document.getElementsByClassName("lab-selected")[0].innerHTML;
    var recipes = allRecipes[currentLab];
    for (var i=0; i < recipes.length; ++i) {
        if (recipes[i]['name'] == recipe_name) {
            var recipe = recipes[i];
            document.getElementById("single-recipe-name").innerHTML = recipe_name;
            document.getElementById("single-recipe-ingredients").innerHTML = ingredientList(recipe);
            document.getElementById("single-recipe-image").src = recipe['image'];
            var singleRecDir = document.getElementById("single-recipe-directions");
            Object.keys(recipe['timedInstructions']).forEach(function (key) {
                var instructions = recipe['timedInstructions'][key];
                for (var k=0; k<instructions.length; ++k) {
                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(instructions[k]));
                    singleRecDir.appendChild(li);
                }
            });
            break;
        }
    }
}

function populateIngredients(recipe) {
  var myName = recipe.name;

  var list = "";
  list += "
 " + myName + "
";
  list += "
";

  for (var i = 0; i < recipe.ingredients.length; i++) {
    list += "
" + recipe.ingredients[i] + "
";
  };

  list += "
";

  document.getElementById("ingredient-single-view").innerHTML = list;
};

function populateIngredientList(name) {
  populateAllIngredients();

  switch (name) {
  case 0:
    var recipe = allRecipes[selectedLab][0];
    populateIngredients(recipe);
    break;
  case 1:
    var recipe = allRecipes[selectedLab][1];
    populateIngredients(recipe);
    break;
  case 2:
    var recipe = allRecipes[selectedLab][2];
    populateIngredients(recipe);
    break;
  case 3:
    var recipe = allRecipes[selectedLab][3];
    populateIngredients(recipe);
    break;
  default:
    // alert("None found");
    break;
  }
};

// function populateIngredientList(name) {
//     var currentLab = document.getElementsByClassName("lab-selected")[0].innerHTML;
//     var recipes = allRecipes[currentLab];

//     for (var i=0; i < recipes.length; ++i) {
//         if (recipes[i]['name'] == name) {
//             var recipe = recipes[i];
//             document.getElementById("ingredient-single-view").innerHTML = ingredientList(recipe);
//             break;
//         }
//     }
// }

function populateAllIngredients() {
    var html = "";
    html = "
All Ingredients
";
    html += "
";

    var recipes = allRecipes[selectedLab];

    for (var i = 0; i < recipes.length; i++) {
      var ingredients = recipes[i].ingredients;

      for (var k = 0; k < ingredients.length; k++) {
        html += "
" + ingredients[k] + "
";
      };
    };

    html += "
";

    document.getElementById("ingredient-combined-view").innerHTML = html;
}

function mealLoaded() {
    setLab();
    populateAllIngredients();
    var currentLab = document.getElementsByClassName("lab-selected")[0].innerHTML;
    document.getElementById("title").innerHTML = currentLab;
    var recipes = allRecipes[currentLab];
    populateIngredientList(recipes[0]['name']);
    var singles = document.querySelectorAll("a[href='#single-recipe']");

    for (var i=0; i<singles.length; ++i) {
        var single = singles[i];
        single.onclick = function () { singleRecipeModal(this.nextSibling.childNodes[0].innerHTML) };
    }
}

function setIdValue(id, value) {
  document.getElementById(id).Value = value;
}

window.addEventListener("DOMContentLoaded", function() {
    window.location.href = '#meal-modal';
    document.getElementById("loadMealButton").addEventListener('click', mealLoaded);
});<commit_msg>Fixed Single Recipe View duplication problem.<commit_after>function setLab() {
    selectedLab = document.querySelectorAll(".lab-selected").item(0).innerHTML;
    console.log("Set Lab To: " + selectedLab);
    reloadData();
}

function reloadData() {
    populateIngredientList(0);
    populateAllIngredients();
}

function ingredientList(recipe) {
    var list = "
 " + recipe['name'] + "
";
    list += "
";
    for (var j = 0; j < recipe['ingredients'].length; ++j) {
        list += "
" + recipe['ingredients'][j] + "
";
    }
    list += "
";
    return list;
}

function singleRecipeModal(recipe_name) {
    var currentLab = document.getElementsByClassName("lab-selected")[0].innerHTML;
    var recipes = allRecipes[currentLab];
    for (var i=0; i < recipes.length; ++i) {
        if (recipes[i]['name'] == recipe_name) {
            var recipe = recipes[i];
            document.getElementById("single-recipe-name").innerHTML = recipe_name;
            document.getElementById("single-recipe-ingredients").innerHTML = ingredientList(recipe);
            document.getElementById("single-recipe-image").src = recipe['image'];
            var singleRecDir = document.getElementById("single-recipe-directions");
            singleRecDir.innerHTML = ""; // Prevent duplicate instructions.
            Object.keys(recipe['timedInstructions']).forEach(function (key) {
                var instructions = recipe['timedInstructions'][key];

                for (var k=0; k<instructions.length; ++k) {
                    var li = document.createElement("li");
                    li.appendChild(document.createTextNode(instructions[k]));
                    singleRecDir.appendChild(li);
                }
            });
            break;
        }
    }
}

function populateIngredients(recipe) {
  var myName = recipe.name;

  var list = "";
  list += "
 " + myName + "
";
  list += "
";

  for (var i = 0; i < recipe.ingredients.length; i++) {
    list += "
" + recipe.ingredients[i] + "
";
  };

  list += "
";

  document.getElementById("ingredient-single-view").innerHTML = list;
};

function populateIngredientList(name) {
  populateAllIngredients();

  switch (name) {
  case 0:
    var recipe = allRecipes[selectedLab][0];
    populateIngredients(recipe);
    break;
  case 1:
    var recipe = allRecipes[selectedLab][1];
    populateIngredients(recipe);
    break;
  case 2:
    var recipe = allRecipes[selectedLab][2];
    populateIngredients(recipe);
    break;
  case 3:
    var recipe = allRecipes[selectedLab][3];
    populateIngredients(recipe);
    break;
  default:
    // alert("None found");
    break;
  }
};

// function populateIngredientList(name) {
//     var currentLab = document.getElementsByClassName("lab-selected")[0].innerHTML;
//     var recipes = allRecipes[currentLab];

//     for (var i=0; i < recipes.length; ++i) {
//         if (recipes[i]['name'] == name) {
//             var recipe = recipes[i];
//             document.getElementById("ingredient-single-view").innerHTML = ingredientList(recipe);
//             break;
//         }
//     }
// }

function populateAllIngredients() {
    var html = "";
    html = "
All Ingredients
";
    html += "
";

    var recipes = allRecipes[selectedLab];

    for (var i = 0; i < recipes.length; i++) {
      var ingredients = recipes[i].ingredients;

      for (var k = 0; k < ingredients.length; k++) {
        html += "
" + ingredients[k] + "
";
      };
    };

    html += "
";

    document.getElementById("ingredient-combined-view").innerHTML = html;
}

function mealLoaded() {
    setLab();
    populateAllIngredients();
    var currentLab = document.getElementsByClassName("lab-selected")[0].innerHTML;
    document.getElementById("title").innerHTML = currentLab;
    var recipes = allRecipes[currentLab];
    populateIngredientList(recipes[0]['name']);
    var singles = document.querySelectorAll("a[href='#single-recipe']");

    for (var i=0; i<singles.length; ++i) {
        var single = singles[i];
        single.onclick = function () { singleRecipeModal(this.nextSibling.childNodes[0].innerHTML) };
    }
}

function setIdValue(id, value) {
  document.getElementById(id).Value = value;
}

window.addEventListener("DOMContentLoaded", function() {
    window.location.href = '#meal-modal';
    document.getElementById("loadMealButton").addEventListener('click', mealLoaded);
});<|endoftext|>