<commit_before>#!/usr/bin/env node
require('../lib/node-version-check'); // @note that this should not respect CLI --silent

var _ = require('lodash'),
    program = require('commander'),
    version = require('../package.json').version,
    newman = require('../'),

    /**
     * A CLI parser helper to process stringified numbers into integers, perform safety checks, and return the result.
     *
     * @param {String} arg - The stringified number argument pulled from the CLI arguments list.
     * @returns {Number} - The supplied argument, casted to an integer.
     */
    Integer = function (arg) {
        var num = Number(arg);

        if (!_.isSafeInteger(num) || num <= 0) {
            throw new Error('The value must be a positive integer.');
        }

        return num.valueOf();
    },

    /**
     * Separates reporter specific arguments from the rest.
     *
     * @todo Figure out a better way! (Or submit a PR to argparse).
     * @param {Array} allArgs - An array of strings, each coresponding to a CLI argument.
     * @returns {Object} - An object with reporter and regular argument key-values.
     */
    separateReporterArgs = function (allArgs) {
        var reporterArgs = [],
            args = [],
            i;

        // Separate the reporter arguments from the rest
        for (i = 0; i < allArgs.length; i++) {
            if (_.startsWith(allArgs[i], '--reporter-')) {
                reporterArgs.push(allArgs[i]);

                // Also push the next parameter if it's not an option.
                allArgs[i + 1] && !_.startsWith(allArgs[i + 1], '-') && reporterArgs.push(allArgs[++i]);
            }
            else {
                args.push(allArgs[i]);
            }
        }
        return {
            reporter: reporterArgs,
            argv: args
        };
    },

    /**
     *  used for collecting global key=value variables supplied through command line
     *
     * --global-var "foo=bar" --global-var "alpha=beta"
     *
     * @param {String} val - The argument provided to `--global-var`.
     * @param {String} memo - The array that is populated by key value pairs.
     * @returns {{key, value}} - The object representation of the current CLI variable.
    */
    collect = function (val, memo) {
        var arg = val,
            eqIndex = arg.indexOf('='),
            hasEq = eqIndex !== -1;
        // This is done instead of splitting by `=` to avoid chopping off `=` that could be present in the value
        arg = hasEq ? { key: arg.slice(0, eqIndex), value: arg.slice(eqIndex + 1) } :
            { key: arg, value: undefined };
        memo.push(arg);
        return memo;
    },

    /**
     * Creates a parser capable of handling options typically given to "newman run" command.
     *
     * @param  {Object} rawArgs - The rawArgs supplied to rawOptions, to be passed to program.parse()
     *
     *  Adds run command options to the common commander program instance.
     * @private
     */

    run = function (rawArgs) {

        program
            .version(version);

        program
            .command('run <collection>')
            .description('URL or path to a Postman Collection.')
            .option('-e, --environment <path>', 'Specify a URL or Path to a Postman Environment.')
            .option('-g, --globals <path>', 'Specify a URL or Path to a file containing Postman Globals.')
            .option('--folder <path>', 'Run a single folder from a collection.')
            .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run.', 'cli')
            .option('-n, --iteration-count <n>', 'Define the number of iterations to run.', Integer)
            .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either json or csv).')
            .option('--export-environment <path>', 'Exports the environment to a file after completing the run.')
            .option('--export-globals <path>', 'Specify an output file to dump Globals before exiting.')
            .option('--export-collection <path>', 'Specify an output file to save the executed collection')
            .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', Integer, 0)
            .option('--bail',
                'Specify whether or not to gracefully stop a collection run on encountering the first error.')
            .option('-x , --suppress-exit-code',
                'Specify whether or not to override the default exit code for the current run.')
            .option('--silent', 'Prevents newman from showing output to CLI.')
            .option('--disable-unicode',
                'Forces unicode compliant symbols to be replaced by their plain text equivalents')
            .option('--global-var <value>',
                'Allows the specification of global variables via the command line, in a key=value format', collect, [])
            // commander had some issue with flags starting with --no, thus camelCased
            // resolved https://github.com/tj/commander.js/pull/709
            .option('--color', 'Force colored output (for use in CI environments).')
            .option('--no-color', 'Disable colored output.')
            .option('--timeout-request <n>', 'Specify a timeout for requests (in milliseconds).', Integer)
            .option('--timeout-script <n>', 'Specify a timeout for script (in milliseconds).', Integer)
            .option('--ignore-redirects', 'If present, Newman will not follow HTTP Redirects.')
            .option('-k, --insecure', 'Disables SSL validations.')
            .option('--ssl-client-cert <path>',
                'Specify the path to the Client SSL certificate. Supports .cert and .pfx files.')
            .option('--ssl-client-key <path>',
                'Specify the path to the Client SSL key (not needed for .pfx files)')
            .option('--ssl-client-passphrase <path>',
                'Specify the Client SSL passphrase (optional, needed for passphrase protected keys).')
            .parse(rawArgs);
    },

    /**
     * Parses the variadic arguments for reporters.
     *
     * @param {Array} args - The array of passed CLI arguments.
     * @param {Array} reporters - A list of reporters used within the current run.
     * @returns {Object} - An object of parsed reporter options.
     */
    reporter = function (args, reporters) {
        var parsed = {
                generic: {}
            },
            name,
            path,
            arg,
            i;

        // ensure that whatever reporter is provided a blank options object object is forwarded
        _.forEach(reporters, (reporter) => { parsed[reporter] = {}; });

        for (i = 0; i < args.length; i++) {
            // Remove trailing whitespace
            arg = _.trim(args[i]);

            // Remove "--reporter-"
            arg = arg.replace('--reporter-', '');

            name = _.split(arg, '-', 1)[0]; // Reporter Name.

            // if we have a valid reporter, the path should be the <name>.camelCaseOfTheRest
            // otherwise, we add it to the generic options.
            path = _.includes(reporters, name) ?
                [name, _.camelCase(arg.replace(name + '-', ''))].join('.') :
                ['generic', _.camelCase(arg)].join('.');

            // If the next arg is an option, set the current arg to true,
            // otherwise set it to the next arg.
            _.set(parsed, path, (!args[i + 1] || _.startsWith(args[i + 1], '-')) ? true : args[++i]);
        }
        return parsed;
    },

    /**
     * Formats the options to the required format for the dispatch function.
     *
     * @param {Object} options - The options populated through CLI.
     * @returns {Object} - An object of formatted options.
     */
    formatOptions = function (options) {
        var command = (_.includes(options.rawArgs[0], 'version') ||
        _.includes(options.rawArgs[0], '-v') || _.includes(options.rawArgs[0], '-V')) ?
                'version' : options._name,
            optionsObj;

        optionsObj = { [command]: {} };

        optionsObj.version = options._version || false;
        optionsObj[command].noColor = !options.color || false;
        optionsObj[command].color = options.color || false;
        optionsObj[command].timeoutRequest = options.timeoutRequest || null;
        optionsObj[command].timeoutScript = options.timeoutScript || null;
        optionsObj[command].ignoreRedirects = options.ignoreRedirects || false;
        optionsObj[command].insecure = options.insecure || false;
        optionsObj[command].sslClientCert = options.sslClientCert || null;
        optionsObj[command].sslClientKey = options.sslClientKey || null;
        optionsObj[command].sslClientPassphrase = options.sslClientPassphrase || null;
        optionsObj[command].collection = options.args || options.rawArgs ? options.args[1] || options.rawArgs[1] : null;
        optionsObj[command].environment = options.environment || null;
        optionsObj[command].globals = options.globals || null;
        optionsObj[command].folder = options.folder || null;
        optionsObj[command].reporters = options.reporters || [];
        optionsObj[command].iterationCount = options.iterationCount || null;
        optionsObj[command].iterationData = options.iterationData || null;
        optionsObj[command].exportEnvironment = options.exportEnvironment || null;
        optionsObj[command].exportGlobals = options.exportGlobals || null;
        optionsObj[command].exportCollection = options.exportCollection || null;
        optionsObj[command].delayRequest = options.delayRequest;
        optionsObj[command].bail = options.bail || false;
        optionsObj[command].suppressExitCode = options.suppressExitCode || false;
        optionsObj[command].silent = options.silent || false;
        optionsObj[command].disableUnicode = options.disableUnicode || false;
        optionsObj[command].globalVar = options.globalVar || null;
        optionsObj[command].reporterOptions = options.reporterOptions || {};
        optionsObj[command].reporter = options.reporter || {};
        optionsObj.command = command;
        return optionsObj;
    },

    /**
     * Loads the raw options for Newman, without loading special options such as collection, environment etc. This
     * function does not access the network or the file-system.
     *
     * @param {Array} procArgv - An array of strings, each corresponding to a command line argument.
     * @param {String} programName - The program name displayed at the start of every newman run.
     * @param {Function} callback - The callback function whose invocation marks the end of the raw options parsing.
     * @returns {*}
     */
    rawOptions = function (procArgv, programName, callback) {
        var reporterArgs,
            rawArgs,
            result,
            checkForColor;
        rawArgs = separateReporterArgs(procArgv);

        try {
            run(rawArgs.argv);
            program.commands.forEach((command) => {
                if (command._name === 'run') {
                    result = command;
                }
            });

            if (_.isEmpty(procArgv) || _.includes(procArgv, '-h') || _.includes(procArgv, '--help')) {
                return result.outputHelp();
            }
        }
        catch (error) {
            return callback(_.set(error, 'help', program.outputHelp()));
        }

        // Handle the reporter Names
        _.isString(result.reporters) && (result.reporters = result.reporters.split(','));

        // Populate the reporter args as well.
        reporterArgs = reporter(rawArgs.reporter, result.reporters);
        result.reporterOptions = reporterArgs.generic;
        result.reporter = _.transform(_.omit(reporterArgs, 'generic'), function (acc, value, key) {
            acc[key] = _.assignIn(value, reporterArgs.generic);
        }, {});
        // eslint-disable-next-line max-len
        // This hack has been added from //https://github.com/mochajs/mocha/blob/961c5392480a6e9ca730e43a4e86fde0d4420fc9/bin/_mocha#L20//2-L211
        // @todo remove when https://github.com/tj/commander.js/issues/691 is fixed.
        checkForColor = _.includes(process.argv, '--color');
        if (checkForColor) {
            result.color = true;
        }
        if (!result.color) { result.color = false; }
        result = formatOptions(result);
        return callback(null, result);
    },

    /**
     * Calls the appropriate Newman command.
     *
     * @param {Object} options - The set of options passed via the CLI, including the command, and other details.
     * @param {Function} callback - The function called to mark the completion of command parsing.
     * @returns {*}
     */
    dispatch = function (options, callback) {
        var command = options.command;

        if (_.isFunction(newman[command])) {
            return newman[command](options[command], callback);
        }

        callback(new Error('Oops, unsupported command: ' + options.command));
    };

// This hack has been added from https://github.com/nodejs/node/issues/6456#issue-151760275
// @todo: remove when https://github.com/nodejs/node/issues/6456 has been fixed
(Number(process.version[1]) >= 6) && [process.stdout, process.stderr].forEach((s) => {
    s && s.isTTY && s._handle && s._handle.setBlocking && s._handle.setBlocking(true);
});

module.exports = rawOptions;

/**
* Loads resources from the network, and then calls the callback.
*
* @param {Array} procArgv - The array of tokenised CLI argument strings.
* @param {String} programName - The displayed program name during runs.
* @param {Function} callback - The callback function whose invocation marks the end of the CLI parsing routine.
* @returns {*}
*/
// ensure we run this script exports if this is a direct stdin
// exported rawOptions above for cases when required as a module for eg tests.
!module.parent && module.exports(process.argv.slice(2), 'newman', function (err, args) {
    if (err) {
        err.help && console.info(err.help + '\n'); // will print out usage information.
        console.error(err.message || err);
        return process.exit(1); // @todo: args do not arrive on CLI error hence cannot read `-x`
    }

    dispatch(args, function (err, summary) {
        var runError = err || summary.run.error || summary.run.failures.length;

        if (err) {
            err.help && console.info(err.help); // will print out usage information.
            console.error(err.message || err);
        }

        if (runError && !_.get(args, 'run.suppressExitCode')) {
            process.exit(1);
        }
    });
});
<commit_msg>Modified formatOptions to reduce verbosity<commit_after>#!/usr/bin/env node
require('../lib/node-version-check'); // @note that this should not respect CLI --silent

var _ = require('lodash'),
    program = require('commander'),
    version = require('../package.json').version,
    newman = require('../'),

    /**
     * A CLI parser helper to process stringified numbers into integers, perform safety checks, and return the result.
     *
     * @param {String} arg - The stringified number argument pulled from the CLI arguments list.
     * @returns {Number} - The supplied argument, casted to an integer.
     */
    Integer = function (arg) {
        var num = Number(arg);

        if (!_.isSafeInteger(num) || num <= 0) {
            throw new Error('The value must be a positive integer.');
        }

        return num.valueOf();
    },

    /**
     * Separates reporter specific arguments from the rest.
     *
     * @todo Figure out a better way! (Or submit a PR to argparse).
     * @param {Array} allArgs - An array of strings, each coresponding to a CLI argument.
     * @returns {Object} - An object with reporter and regular argument key-values.
     */
    separateReporterArgs = function (allArgs) {
        var reporterArgs = [],
            args = [],
            i;

        // Separate the reporter arguments from the rest
        for (i = 0; i < allArgs.length; i++) {
            if (_.startsWith(allArgs[i], '--reporter-')) {
                reporterArgs.push(allArgs[i]);

                // Also push the next parameter if it's not an option.
                allArgs[i + 1] && !_.startsWith(allArgs[i + 1], '-') && reporterArgs.push(allArgs[++i]);
            }
            else {
                args.push(allArgs[i]);
            }
        }
        return {
            reporter: reporterArgs,
            argv: args
        };
    },

    /**
     *  used for collecting global key=value variables supplied through command line
     *
     * --global-var "foo=bar" --global-var "alpha=beta"
     *
     * @param {String} val - The argument provided to `--global-var`.
     * @param {String} memo - The array that is populated by key value pairs.
     * @returns {{key, value}} - The object representation of the current CLI variable.
    */
    collect = function (val, memo) {
        var arg = val,
            eqIndex = arg.indexOf('='),
            hasEq = eqIndex !== -1;
        // This is done instead of splitting by `=` to avoid chopping off `=` that could be present in the value
        arg = hasEq ? { key: arg.slice(0, eqIndex), value: arg.slice(eqIndex + 1) } :
            { key: arg, value: undefined };
        memo.push(arg);
        return memo;
    },

    /**
     * Creates a parser capable of handling options typically given to "newman run" command.
     *
     * @param  {Object} rawArgs - The rawArgs supplied to rawOptions, to be passed to program.parse()
     *
     *  Adds run command options to the common commander program instance.
     * @private
     */

    run = function (rawArgs) {

        program
            .version(version);

        program
            .command('run <collection>')
            .description('URL or path to a Postman Collection.')
            .option('-e, --environment <path>', 'Specify a URL or Path to a Postman Environment.')
            .option('-g, --globals <path>', 'Specify a URL or Path to a file containing Postman Globals.')
            .option('--folder <path>', 'Run a single folder from a collection.')
            .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run.', 'cli')
            .option('-n, --iteration-count <n>', 'Define the number of iterations to run.', Integer)
            .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either json or csv).')
            .option('--export-environment <path>', 'Exports the environment to a file after completing the run.')
            .option('--export-globals <path>', 'Specify an output file to dump Globals before exiting.')
            .option('--export-collection <path>', 'Specify an output file to save the executed collection')
            .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', Integer, 0)
            .option('--bail',
                'Specify whether or not to gracefully stop a collection run on encountering the first error.')
            .option('-x , --suppress-exit-code',
                'Specify whether or not to override the default exit code for the current run.')
            .option('--silent', 'Prevents newman from showing output to CLI.')
            .option('--disable-unicode',
                'Forces unicode compliant symbols to be replaced by their plain text equivalents')
            .option('--global-var <value>',
                'Allows the specification of global variables via the command line, in a key=value format', collect, [])
            // commander had some issue with flags starting with --no, thus camelCased
            // resolved https://github.com/tj/commander.js/pull/709
            .option('--color', 'Force colored output (for use in CI environments).')
            .option('--no-color', 'Disable colored output.')
            .option('--timeout-request <n>', 'Specify a timeout for requests (in milliseconds).', Integer)
            .option('--timeout-script <n>', 'Specify a timeout for script (in milliseconds).', Integer)
            .option('--ignore-redirects', 'If present, Newman will not follow HTTP Redirects.')
            .option('-k, --insecure', 'Disables SSL validations.')
            .option('--ssl-client-cert <path>',
                'Specify the path to the Client SSL certificate. Supports .cert and .pfx files.')
            .option('--ssl-client-key <path>',
                'Specify the path to the Client SSL key (not needed for .pfx files)')
            .option('--ssl-client-passphrase <path>',
                'Specify the Client SSL passphrase (optional, needed for passphrase protected keys).')
            .parse(rawArgs);
    },

    /**
     * Parses the variadic arguments for reporters.
     *
     * @param {Array} args - The array of passed CLI arguments.
     * @param {Array} reporters - A list of reporters used within the current run.
     * @returns {Object} - An object of parsed reporter options.
     */
    reporter = function (args, reporters) {
        var parsed = {
                generic: {}
            },
            name,
            path,
            arg,
            i;

        // ensure that whatever reporter is provided a blank options object object is forwarded
        _.forEach(reporters, (reporter) => { parsed[reporter] = {}; });

        for (i = 0; i < args.length; i++) {
            // Remove trailing whitespace
            arg = _.trim(args[i]);

            // Remove "--reporter-"
            arg = arg.replace('--reporter-', '');

            name = _.split(arg, '-', 1)[0]; // Reporter Name.

            // if we have a valid reporter, the path should be the <name>.camelCaseOfTheRest
            // otherwise, we add it to the generic options.
            path = _.includes(reporters, name) ?
                [name, _.camelCase(arg.replace(name + '-', ''))].join('.') :
                ['generic', _.camelCase(arg)].join('.');

            // If the next arg is an option, set the current arg to true,
            // otherwise set it to the next arg.
            _.set(parsed, path, (!args[i + 1] || _.startsWith(args[i + 1], '-')) ? true : args[++i]);
        }
        return parsed;
    },

    /**
     * Formats the options to the required format for the dispatch function.
     *
     * @param {Object} options - The options populated through CLI.
     * @returns {Object} - An object of formatted options.
     */
    formatOptions = function (options) {
        var command = (_.includes(options.rawArgs[0], 'version') ||
        _.includes(options.rawArgs[0], '-v') || _.includes(options.rawArgs[0], '-V')) ?
                'version' : options._name,
            optionsObj, optionName, prop,
            optionNames = [];

        options.options.forEach(function (option) {
            optionName = option.long;
            optionName = optionName.replace('--', '');
            optionName = optionName.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
            optionNames.push(optionName);
        });

        optionsObj = { [command]: {} };
        optionsObj.command = command;
        optionsObj.version = options.parent._version || false;
        optionsObj[command].collection = options.args || options.rawArgs ? options.args[1] || options.rawArgs[1] : null;
        optionsObj[command].reporter = options.reporter || {};
        optionsObj[command].reporterOptions = options.reporterOptions || {};

        for (prop in options) {
            if (_.includes(optionNames, String(prop))) {
                optionsObj[command][prop] = options[prop];
            }
        }

        return optionsObj;
    },

    /**
     * Loads the raw options for Newman, without loading special options such as collection, environment etc. This
     * function does not access the network or the file-system.
     *
     * @param {Array} procArgv - An array of strings, each corresponding to a command line argument.
     * @param {String} programName - The program name displayed at the start of every newman run.
     * @param {Function} callback - The callback function whose invocation marks the end of the raw options parsing.
     * @returns {*}
     */
    rawOptions = function (procArgv, programName, callback) {
        var reporterArgs,
            rawArgs,
            result,
            checkForColor;
        rawArgs = separateReporterArgs(procArgv);

        try {
            run(rawArgs.argv);
            program.commands.forEach(function (command) {
                if (command._name === 'run') {
                    result = command;
                }
            });

            if (_.isEmpty(procArgv) || _.includes(procArgv, '-h') || _.includes(procArgv, '--help')) {
                return result.outputHelp();
            }
        }
        catch (error) {
            return callback(_.set(error, 'help', program.outputHelp()));
        }

        // Handle the reporter Names
        _.isString(result.reporters) && (result.reporters = result.reporters.split(','));

        // Populate the reporter args as well.
        reporterArgs = reporter(rawArgs.reporter, result.reporters);
        result.reporterOptions = reporterArgs.generic;
        result.reporter = _.transform(_.omit(reporterArgs, 'generic'), function (acc, value, key) {
            acc[key] = _.assignIn(value, reporterArgs.generic);
        }, {});
        // eslint-disable-next-line max-len
        // This hack has been added from //https://github.com/mochajs/mocha/blob/961c5392480a6e9ca730e43a4e86fde0d4420fc9/bin/_mocha#L20//2-L211
        // @todo remove when https://github.com/tj/commander.js/issues/691 is fixed.
        checkForColor = _.includes(process.argv, '--color');
        if (checkForColor) {
            result.color = true;
        }
        if (!result.color) { result.color = false; }
        result = formatOptions(result);
        return callback(null, result);
    },

    /**
     * Calls the appropriate Newman command.
     *
     * @param {Object} options - The set of options passed via the CLI, including the command, and other details.
     * @param {Function} callback - The function called to mark the completion of command parsing.
     * @returns {*}
     */
    dispatch = function (options, callback) {
        var command = options.command;

        if (_.isFunction(newman[command])) {
            return newman[command](options[command], callback);
        }

        callback(new Error('Oops, unsupported command: ' + options.command));
    };

// This hack has been added from https://github.com/nodejs/node/issues/6456#issue-151760275
// @todo: remove when https://github.com/nodejs/node/issues/6456 has been fixed
(Number(process.version[1]) >= 6) && [process.stdout, process.stderr].forEach((s) => {
    s && s.isTTY && s._handle && s._handle.setBlocking && s._handle.setBlocking(true);
});

module.exports = rawOptions;

/**
* Loads resources from the network, and then calls the callback.
*
* @param {Array} procArgv - The array of tokenised CLI argument strings.
* @param {String} programName - The displayed program name during runs.
* @param {Function} callback - The callback function whose invocation marks the end of the CLI parsing routine.
* @returns {*}
*/
// ensure we run this script exports if this is a direct stdin
// exported rawOptions above for cases when required as a module for eg tests.
!module.parent && module.exports(process.argv.slice(2), 'newman', function (err, args) {
    if (err) {
        err.help && console.info(err.help + '\n'); // will print out usage information.
        console.error(err.message || err);
        return process.exit(1); // @todo: args do not arrive on CLI error hence cannot read `-x`
    }

    dispatch(args, function (err, summary) {
        var runError = err || summary.run.error || summary.run.failures.length;

        if (err) {
            err.help && console.info(err.help); // will print out usage information.
            console.error(err.message || err);
        }

        if (runError && !_.get(args, 'run.suppressExitCode')) {
            process.exit(1);
        }
    });
});
<|endoftext|>


<commit_before>$(function() {
    /***************
        getTop8
    ***************/
    // On page load: Ajax GET request to '/api/getTop8'
    $.ajax({
        type: 'GET',
        url: '/api/getTop8',
        data: 'json',
        datatype: 'application/json',
        success: function(data) {
            // On success below jquery fills rows of Top8 table with data retrieved from /api/getTop8
            var hash = JSON.parse(data);
            // for (var i = 0; i <= 7; i++) {
            //     for (var key in hash[i]['songList']) {
            //         console.log(key);
            //     }
            // }
            for (var i = 0; i <= 7; i++) {
                if (typeof hash[i] === 'undefined') {
                    $('td.playlist-name:eq(' + i + ')').text('N/A');
                    $('td.playlist-popularity:eq(' + i + ')').text('N/A');
                } else {
                    for (var j in hash[i]['songList']) {
                        var currentPlaylistText = $('td.playlist-name:eq(' + i + ')').text();
                        currentPlaylistText += hash[i]['songList'][j]['title'] + ' by ' + hash[i]['songList'][j]['author'] + ', ';
                        $('td.playlist-name:eq(' + i + ')').text(formatPlaylist(currentPlaylistText));
                        $('td.playlist-popularity:eq(' + i + ')').text(hash[i]['popularity']);
                    }
                    // Remove trailing comma
                    $('td.playlist-name:eq(' + i + ')').text($('td.playlist-name:eq(' + i + ')').text().slice(0, -2));
                }
            }
        },
        error: function(data) {
            // alert('Failed to retrieve Top8 content');
            console.log('Failed to retrieve Top8 content');
        }
    });
    /********************
        suggestPlaylist
    *********************/
    function suggestPlaylist() {
        var parseTitle = $('#enter-song').val().replace(/\\/g, '\\/').split('#');
        var title = parseTitle[0];
        if (title === '') {
            console.log("LET ME KNOW");
            $('.author-suggest').text('');
            removeTableRows();
            var author = $('#enter-song').val().split('#').pop();
            if (!(author === '')) {
                $('.song-suggest').text('No playlist found');
            } else {
                $('.song-suggest').text('');
            }
        } else {
            var data = {};
            var author = $('#enter-song').val().split('#').pop();
            // Gets the song name text
            data['song'] = {
                'title': title,
                'author': author
            };
            // data['song'] = "As She's Walking Away (w\\/ Alan Jackson)"; // Gets the song name text
            console.log(data['song']);
            $.ajax({
                type: 'POST',
                url: '/api/suggestPlaylist',
                data: JSON.stringify(data),
                dataType: "text",
                contentType: 'application/json',
                success: function(data) {
                    // On success, below jquery suggests playlist with highest popularity containing entered song
                    console.log('Success!');
                    var hash = JSON.parse(data);
                    // console.log(hash['songList'][0]);
                    removeTableRows();
                    for (var i in hash['songList']) {
                        $('.song-suggest:last').text(formatPlaylist(hash['songList'][i]['title']));
                        $('.author-suggest:last').text(formatPlaylist(hash['songList'][i]['author']));
                        addTableRows();
                        addTableRowsClasses();
                    }
                    // console.log($('.song-suggest:first').text());
                    // $('.playlist-row:first').remove();
                },
                error: function(data) {
                    // alert('Failed to retrieve Top8 content');
                    console.log('Failed to retrieve suggestPlaylist content');
                    removeTableRows();
                    $('.song-suggest').text('No Playlist Found');
                }
            });
        }
    }
    /********************
        getAutocomplete
    *********************/
    function autocomplete() {
        var parseTitle = $('#enter-song').val().replace(/\\/g, '\\/').split('#');
        var title = parseTitle[0];
        if (title === '') {
            console.log("LET ME KNOW");
            $('.song-autocomplete').text('');
            $('.author-autocomplete').text('');
        } else {
            var data = {};
            data['song'] = title; // Gets the song name text
            // console.log(data['song']);
            $.ajax({
                type: 'POST',
                url: '/api/getAutocomplete',
                data: JSON.stringify(data),
                dataType: "text",
                contentType: 'application/json',
                success: function(data) {
                    // On success, below jquery suggests playlist with highest popularity containing entered song
                    console.log('Success!');
                    var hash = JSON.parse(data);
                    console.log(hash); // Helps to know if the proper songs are being returned
                    for (var i = 0; i <= 3; i++) {
                        if (typeof hash[i] === 'undefined') {
                            // An autocomplete option is empty if the hash did not return the
                            // specified index
                            $('.song-autocomplete:eq(' + i + ')').text('');
                            $('.author-autocomplete:eq(' + i + ')').text('');
                        } else {
                            // Otherwise fill the autocomplete option with the corresponding song name
                            $('.song-autocomplete:eq(' + i + ')').text(hash[i]['title'].replace(/\\/g, ''));
                            $('.author-autocomplete:eq(' + i + ')').text(hash[i]['author'].replace(/\\/g, ''));
                        }
                    }
                },
                error: function(data) {
                    console.log('Failed to retrieve getAutocomplete content');
                    for (var i = 0; i <= 3; i++) {
                        $('.song-autocomplete:eq(' + i + ')').text('');
                        $('.author-autocomplete:eq(' + i + ')').text('');
                    }
                }
            });
        }
    }
    /*************************************
     * Helper functions
     **************************************/
    // Formats the playlist to remove ##'s and \'s
    function formatPlaylist(playlist) {
        playlist = playlist.replace(/\\/g, '');
        return playlist;
    }

    function addTableRows() {
        var songRow = songListTable.insertRow(); // Add to bottom
        var songTitleCell = songRow.insertCell(0);
        var songAuthorCell = songRow.insertCell(1);
    }

    function addTableRowsClasses() {
        // Assigns class names to dynamically generated rows
        $('#songListTable tbody tr td').attr('class', ''); // remove all previous classes
        $('#songListTable tbody tr').attr('class', 'playlist-row');
        $('#songListTable tbody tr td:even').attr('class', 'song-suggest');
        $('#songListTable tbody tr td:odd').attr('class', 'author-suggest');
        $('#songListTable thead tr').attr('class', 'playlist-header'); //
    }

    function removeTableRows() {
        $('.playlist-row:first').attr('class', 'temp');
        $('.playlist-row').remove();
        $('.playlist-row:first').attr('class', 'playlist-row');
    }
    /*************************************
     * Event Listeners
     **************************************/
    // keypress jquery event handler
    $('#enter-song').bind("keyup", function(e) {
        if (e.keyCode == 40) {
            // If the down arrow is selected, jump to the autocomplete suggestions
            $('#enter-song').blur();
            $("select:first").focus();
            $('.song-autocomplete:eq(' + 0 + ')').prop('selected', true);
            for (var i = 1; i <= 3; i++) {
                $('.song-autocomplete:eq(' + i + ')').prop('selected', false);
            }
            $('#suggested-playlist').prop('selected', false);
        } else {
            // For each key pressed a playlist and 4 songs are suggested
            suggestPlaylist();
            autocomplete();
        }
    });
    // $('.song-autocomplete:eq(' + 0 + ')').bind("keyup", function(e) {
    //     if (e.keyCode == 40) {
    //         // If the down arrow is selected, jump to the autocomplete suggestions
    //         $('#enter-song').focus();
    //         $("select:first").blur();
    //         $('.song-autocomplete:eq(' + 0 + ')').blur('selected', true);
    //     }
    // });
    // Clicking on an autocomplete suggestion changes the enter song text
    // to the autocomplete suggestion and updates the suggested playlist
    $('.autocomplete-row').click(function() {
        var enterSong = $('#enter-song');
        var song = $(this).children('.song-autocomplete').text();
        var author = $(this).children('.author-autocomplete').text();
        enterSong.val(song + '#' + author);
        var e = $.Event('keyup');
        e.which = 13; // 13 = enter key
        enterSong.trigger(e); // Triggers keyup event listener for enter song text input
        enterSong.focus();
    });

});
<commit_msg>w/ changed to w\/<commit_after>$(function() {
    /***************
        getTop8
    ***************/
    // On page load: Ajax GET request to '/api/getTop8'
    $.ajax({
        type: 'GET',
        url: '/api/getTop8',
        data: 'json',
        datatype: 'application/json',
        success: function(data) {
            // On success below jquery fills rows of Top8 table with data retrieved from /api/getTop8
            var hash = JSON.parse(data);
            // for (var i = 0; i <= 7; i++) {
            //     for (var key in hash[i]['songList']) {
            //         console.log(key);
            //     }
            // }
            for (var i = 0; i <= 7; i++) {
                if (typeof hash[i] === 'undefined') {
                    $('td.playlist-name:eq(' + i + ')').text('N/A');
                    $('td.playlist-popularity:eq(' + i + ')').text('N/A');
                } else {
                    for (var j in hash[i]['songList']) {
                        var currentPlaylistText = $('td.playlist-name:eq(' + i + ')').text();
                        currentPlaylistText += hash[i]['songList'][j]['title'] + ' by ' + hash[i]['songList'][j]['author'] + ', ';
                        $('td.playlist-name:eq(' + i + ')').text(formatPlaylist(currentPlaylistText));
                        $('td.playlist-popularity:eq(' + i + ')').text(hash[i]['popularity']);
                    }
                    // Remove trailing comma
                    $('td.playlist-name:eq(' + i + ')').text($('td.playlist-name:eq(' + i + ')').text().slice(0, -2));
                }
            }
        },
        error: function(data) {
            // alert('Failed to retrieve Top8 content');
            console.log('Failed to retrieve Top8 content');
        }
    });
    /********************
        suggestPlaylist
    *********************/
    function suggestPlaylist() {
        var parseTitle = $('#enter-song').val().replace(/\//g, '\\\/').split('#');
        var title = parseTitle[0];
        if (title === '') {
            console.log("LET ME KNOW");

            removeTableRows();
            var author = $('#enter-song').val().split('#').pop();
            if (!(author === '')) {
                $('.song-suggest').text('No playlist found');
                $('.author-suggest').text('N/A');
            } else {
                $('.song-suggest').text('');
                $('.author-suggest').text('');
            }
        } else {
            var data = {};
            var author = $('#enter-song').val().split('#').pop();
            // Gets the song name text
            data['song'] = {
                'title': title,
                'author': author
            };
            // data['song'] = "As She's Walking Away (w\\/ Alan Jackson)"; // Gets the song name text
            console.log(data['song']);
            $.ajax({
                type: 'POST',
                url: '/api/suggestPlaylist',
                data: JSON.stringify(data),
                dataType: "text",
                contentType: 'application/json',
                success: function(data) {
                    // On success, below jquery suggests playlist with highest popularity containing entered song
                    console.log('Success!');
                    var hash = JSON.parse(data);
                    // console.log(hash['songList'][0]);
                    removeTableRows();
                    for (var i in hash['songList']) {
                        $('.song-suggest:last').text(formatPlaylist(hash['songList'][i]['title']));
                        $('.author-suggest:last').text(formatPlaylist(hash['songList'][i]['author']));
                        addTableRows();
                        addTableRowsClasses();
                    }
                    // Remove extra row create in above loop
                    $('.playlist-row:last').remove();
                },
                error: function(data) {
                    // alert('Failed to retrieve Top8 content');
                    console.log('Failed to retrieve suggestPlaylist content');
                    removeTableRows();
                    $('.song-suggest').text('No Playlist Found');
                    $('.author-suggest').text('N/A');
                }
            });
        }
    }
    /********************
        getAutocomplete
    *********************/
    function autocomplete() {
        // console.log('Before: ' + $('#enter-song').val());
        var parseTitle = $('#enter-song').val().replace(/\//g, '\\\/').split('#');
        var title = parseTitle[0];
        console.log('After: ' + title);
        if (title === '') {
            console.log("LET ME KNOW");
            $('.song-autocomplete').text('');
            $('.author-autocomplete').text('');
        } else {
            var data = {};
            data['song'] = title; // Gets the song name text
            // console.log(data['song']);
            $.ajax({
                type: 'POST',
                url: '/api/getAutocomplete',
                data: JSON.stringify(data),
                dataType: "text",
                contentType: 'application/json',
                success: function(data) {
                    // On success, below jquery suggests playlist with highest popularity containing entered song
                    console.log('Success!');
                    var hash = JSON.parse(data);
                    console.log(hash); // Helps to know if the proper songs are being returned
                    for (var i = 0; i <= 3; i++) {
                        if (typeof hash[i] === 'undefined') {
                            // An autocomplete option is empty if the hash did not return the
                            // specified index
                            $('.song-autocomplete:eq(' + i + ')').text('');
                            $('.author-autocomplete:eq(' + i + ')').text('');
                        } else {
                            // Otherwise fill the autocomplete option with the corresponding song name
                            $('.song-autocomplete:eq(' + i + ')').text(hash[i]['title'].replace(/\\/g, ''));
                            $('.author-autocomplete:eq(' + i + ')').text(hash[i]['author'].replace(/\\/g, ''));
                        }
                    }
                },
                error: function(data) {
                    console.log('Failed to retrieve getAutocomplete content');
                    for (var i = 0; i <= 3; i++) {
                        $('.song-autocomplete:eq(' + i + ')').text('');
                        $('.author-autocomplete:eq(' + i + ')').text('');
                    }
                }
            });
        }
    }
    /*************************************
     * Helper functions
     **************************************/
    // Formats the playlist to remove ##'s and \'s
    function formatPlaylist(playlist) {
        playlist = playlist.replace(/\\/g, '');
        return playlist;
    }

    function addTableRows() {
        var songRow = songListTable.insertRow(); // Add to bottom
        var songTitleCell = songRow.insertCell(0);
        var songAuthorCell = songRow.insertCell(1);
    }

    function addTableRowsClasses() {
        // Assigns class names to dynamically generated rows
        $('#songListTable tbody tr td').attr('class', ''); // remove all previous classes
        $('#songListTable tbody tr').attr('class', 'playlist-row');
        $('#songListTable tbody tr td:even').attr('class', 'song-suggest');
        $('#songListTable tbody tr td:odd').attr('class', 'author-suggest');
        $('#songListTable thead tr').attr('class', 'playlist-header'); //
    }

    function removeTableRows() {
        // Hack to remove all rows except the first
        $('.playlist-row:first').attr('class', 'temp');
        $('.playlist-row').remove();
        $('.playlist-row:first').attr('class', 'playlist-row');
    }
    /*************************************
     * Event Listeners
     **************************************/
    // keypress jquery event handler
    $('#enter-song').bind("keyup", function(e) {
        if (e.keyCode == 40) {
            // If the down arrow is selected, jump to the autocomplete suggestions
            $('#enter-song').blur();
            $("select:first").focus();
            $('.song-autocomplete:eq(' + 0 + ')').prop('selected', true);
            for (var i = 1; i <= 3; i++) {
                $('.song-autocomplete:eq(' + i + ')').prop('selected', false);
            }
            $('#suggested-playlist').prop('selected', false);
        } else {
            // For each key pressed a playlist and 4 songs are suggested
            suggestPlaylist();
            autocomplete();
        }
    });
    // $('.song-autocomplete:eq(' + 0 + ')').bind("keyup", function(e) {
    //     if (e.keyCode == 40) {
    //         // If the down arrow is selected, jump to the autocomplete suggestions
    //         $('#enter-song').focus();
    //         $("select:first").blur();
    //         $('.song-autocomplete:eq(' + 0 + ')').blur('selected', true);
    //     }
    // });
    // Clicking on an autocomplete suggestion changes the enter song text
    // to the autocomplete suggestion and updates the suggested playlist
    $('.autocomplete-row').click(function() {
        var enterSong = $('#enter-song');
        var song = $(this).children('.song-autocomplete').text();
        var author = $(this).children('.author-autocomplete').text();
        enterSong.val(song + '#' + author);
        var e = $.Event('keyup');
        e.which = 13; // 13 = enter key
        enterSong.trigger(e); // Triggers keyup event listener for enter song text input
        enterSong.focus();
    });

});
<|endoftext|>


<commit_before>// iWall v1.6.0 //
// -----------------------------
// v1.0.0 ~ greg original
// v1.0.1 ~ merwan revisions
// v1.1.0 ~ begin using DOM tree manipulations and jquery
// v1.5.0 ~ new views, separated into proper files.
// v1.6.0 ~ filters working, infinite loop bug fixed (xajax not respecting scope)

// used to simulate array functions
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

// called when user starts the application
$(document).ready(function start() {
	Globals.searchMode = $("#searchMode").val();
	Globals.sortedBy = Globals.searchMode == "solr" ? "" : "updated";
	Globals.isiPad = window.Touch != undefined;
	window.onorientationchange = function() {
		ScrollView.pause();
		if (!Globals.displayMode && $("#content").css("display") == "none") {
			ScrollView.goFullScreen()
		} else {
			searchSubset(true);
		}

	}

	var doc = document,
		hash = window.location.hash;

	hash = hash.replace("_details", "");

	Globals.initDone = 1;

    $("#content").css({ paddingRight: "20px", paddingTop: "0px" });
    $("#wrapper_menu").css({ height: "0px" });

        // obsolete? (maybe should be detailsPane anyway?)
	//$("#details").hide();

	// add an event to monitor when the search box gains focus
	var box = doc.getElementById("searchBox");
	box.onfocus = function() {
		box.style.color = "#000000";
		box.value = box.value == "Enter a name..." ? "" : box.value;
	}

	$("#sortOrderIcon").click(function() { Utils.ascDesc(this) }).css({cursor: "pointer"});

	$("#buttonPlay").css("opacity", 0.3);
	$("#buttonPlay").css("filter", "progid:DXImageTransform.Microsoft.Alpha(opacity=30)");

	$("#loadingX").css( {height: Math.round($(window).height() - 190) + "px", paddingTop: Math.round(($(window).height() - 350)/2) + "px"});

	Globals.imageHeight = Math.floor(($(window).height() - Globals.headerHeight - Globals.footerHeight - (2*(Globals.rowPadding+Globals.imageBorder))) / Globals.maxRows);

	if ( hash.length > 1 ) { //for bookmarking
		if ( hash === "#searchAll" ) {
			hash = "";
		} else {
			box.style.color = "#000000";
			$("#searchBox").val(unescape(hash).replace('#', ''));
		}
		searchSubset(true);
	}
});

function searchSubset(first) {
	Globals.searchTerms = $.trim($("#searchBox").attr("value"));
	Globals.searchTerms = Globals.searchTerms == "Enter a name..." || Globals.searchTerms == "All" ? "" : Globals.searchTerms;

	var missing   = $("#checkMissing")   .is(":checked"),
		alive     = $("#checkAliveWell") .is(":checked"),
		injured   = $("#checkInjured")   .is(":checked"),
		deceased  = $("#checkDeceased")  .is(":checked"),
		unknown   = $("#checkUnknown")   .is(":checked"),
		found     = $("#checkFound")     .is(":checked"),

		complex   = $("#checkSexComplex").is(":checked"),
		male 	  = $("#checkSexMale")   .is(":checked"),
		female 	  = $("#checkSexFemale") .is(":checked"),
		genderUnk = $("#checkSexOther")  .is(":checked"),

		child 	  = $("#checkAgeChild")  .is(":checked"),
		adult	  = $("#checkAgeYouth")  .is(":checked"),
		ageUnk    = $("#checkAgeUnknown").is(":checked"),

		suburban  = $("#checkSuburban")  .is(":checked"),
		nnmc      = $("#checkNNMC")      .is(":checked"),
		otherHosp = $("#checkOtherHosp") .is(":checked"),

		sStatus       = missing + ";" + alive + ";" + injured + ";" + deceased + ";" + unknown + ";" + found,
		sGender       = complex + ";" + male + ";" + female + ";" + genderUnk,
		sAge          = child + ";" + adult + ";" +	ageUnk,
		sHospital     = suburban + ";" + nnmc + ";" + otherHosp,

		sPageControls = Globals.perPage * (Globals.currPage - 1)  + ";"
					  + Globals.perPage + ";"
					  + Globals.sortedBy + ";"
					  +	Globals.displayMode;

	Globals.incident = Globals.incident || $("#shortName").val();
	Globals.searchMode = $("#searchMode").val();
	$("#updateAlerts, #updateAlerts2").hide();

	inw_getData(Globals.searchMode, Globals.incident, Globals.searchTerms, sStatus, sGender, sAge, sHospital, sPageControls);
	if ( Globals.searchMode == "sql" ) {
		sPageControls = Globals.perPage * (Globals.currPage)  + ";"
				  + Globals.perPage + ";"
				  + Globals.sortedBy + ";"
				  +	Globals.displayMode;
		if ( Globals.displayMode ) {
			inw_hasNextPage(Globals.searchMode, Globals.incident, Globals.searchTerms, sStatus, sGender, sAge, sHospital, sPageControls);
			inw_getAllCount(Globals.incident);
		}
		$("#sqlFoundLabel").show();
		$("#solrFoundLabel").hide();
	} else {
		$("#solrFoundLabel").show();
		$("#sqlFoundLabel").hide();
	}

	$("#foundLabel").show();
	$("#refreshLabel").hide();
	if ( Globals.displayMode && Globals.searchMode != "sql" )
		$("#maxShown").hide();
	else
		$("#maxShown").show();

	$("#menuwrap").append($("#searchOptions").css({marginTop: "5px", marginLeft: "10px"}).show());
	if ( !$("#shortName").val().match(/(cmax|shield)/) ) $("#hospital").hide();
	$("#content").css({marginRight: "0px", paddingRight: "20px"});
        $("#buttonHelp").show();

	if ( Globals.initDone == 1 )
		$("#scrolling_content").html('

').show(50);

        // Queue up next search at first invocation.
        if (first) {
        	clearInterval(Globals.updaterId);
       		Globals.updaterId = setInterval(
                        "inw_checkForChanges('"+Globals.searchMode+"','"+Globals.incident+"','"+Globals.searchTerms+"','"+sStatus+"','"+sGender+"','"+sAge+"','"+sHospital+"')",
        		Globals.updaterTimer);
        }
}

Object.size = function(obj) {
	var size = 0, key;
	for (key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
};

function handleUuidListResponse() {
        // obsolete?
	//var temp = [], freshUuids = [];

	$("#totalRecordsSOLR").html(Utils.addCommas($("#totalRecordsSOLR").html()));

	showFacets();
	window.location.hash = Globals.searchTerms === "" ? "searchAll" : Globals.searchTerms;

	if ( Globals.displayMode ) {
		Globals.displayMode = true;
		DetailsView.drawPage();
	}
	else
		ScrollView.init();
}

function showFacets() {
        // obsolete?
	//var tempGender = 0, tempAge = 0;

	if ( Globals.searchMode == "solr" ) {
		var facets = jQuery.parseJSON($("#SOLRFacets").val());
		for( facet in facets ) {
			$("#" + facet + " > span").remove();
			$("#" + facet).append($("")
						  .css("font-size", "8pt")
						  .css("position", "absolute")
						  .css("right", "30px")
						  .css("margin-top", "5px")
						  .css("font-weight", "bold")
						  .html(Utils.addCommas(facets[facet])));
                        // obsolete?
			//if ( (facet == "male" || facet == "female") && parseInt(facets[facet]) > 0 )
				//tempGender++;
			//else if ( (facet == "child" || facet == "adult") && parseInt(facets[facet]) > 0 )
				//tempAge++;
		}
	} else {
		$("#filtersWrapper").find("label > span").remove();
	}
}

//
// Person Class
//
function Person() {

	// Basically takes the json-derived associative-array and inits fields.
	// Also inits other useful fields.
	this.init =  function(args) {
		if ( args ) {
			var date = Date.parse(args["statusSahanaUpdated"]);
			this.uuid         = args["p_uuid"];
			this.encodedUUID  = args["encodedUUID"];
			this.statusSahana = args["opt_status"];
			this.name         = $.trim(args["full_name"]) === "Unknown Unknown" || $.trim(args["full_name"]) == undefined ? "Unknown name" :  $.trim(args["full_name"]) || "Unknown name";

                        // Added check for zero (PL-253).
			this.age	  = (args["years_old"] == 0)? 0 : args["years_old"] || -1;
			this.minAge       = (args["minAge"] == 0)? 0 : args["minAge"] || -1;
			this.maxAge       = args["maxAge"] || -1;

			this.statusSahanaUpdated = date.toString("yyyy-MM-dd HH:mm");
			this.statusTriage = args["statusTriage"];
			this.id           = args["id"];
			this.peds         = args["peds"];
			this.location     = args["last_seen"];
			this.comments     = args["comments"];
			this.image        = null;
			this.imageUrl     = args["imageUrl"] || "res/img/s4unknown.png";
			this.imageHeight  = parseInt(args["imageHeight"]);
			this.imageWidth   = parseInt(args["imageWidth"]);
			this.hospitalIcon = args["hospitalIcon"] || "";
			this.imageShow    = true;
			this.x            = -999999;
			this.y            = -999999;
			this.wipe         = false;

			this.mass_casualty_id = args["mass_casualty_id"] || "";

                        // Added allowance for unbounded range (PL-252).
			if ( this.age > -1 )
				this.displayAge = this.age;
			else if ( this.minAge > -1 && this.maxAge == -1 )
				this.displayAge = this.minAge + "-?";
			else if ( this.minAge == -1 && this.maxAge > -1 )
				this.displayAge = "?-" + this.maxAge;
                        else if ( this.minAge > -1 && this.maxAge > -1 )
                                this.displayAge = this.minAge + "-" + this.maxAge;
			else
				this.displayAge = "Unknown";

			if ( args["gender"] === "mal" )
				this.gender = "Male";
			else if ( args["gender"] === "fml" )
				this.gender = "Female";
			else if ( args["gender"] === "cpx" )
				this.gender = "Complex";
			else
				this.gender = "Unknown";

			this.statusString()
		}
	};

		// to implement
	this.equals = function(otherPerson) {
		alert("equals!");
	}

	this.statusString = function() {
		var ss = this.statusSahana;

		if (this.statusSahana == "mis") {
			this.tagColor         = "00C";
			this.tagRGBA		  = "rgba(220,220,250, 0.60)";
			this.tagClass         = "statusMissing";
			this.statusSahanaFull = "missing";

		} else if (this.statusSahana == "ali") {
			this.tagColor         = "0A0";
			this.tagRGBA		  = "rgba(220,250,220, 0.60)";
			this.tagClass         = "statusAlive";
			this.statusSahanaFull = "alive and well";

		} else if (this.statusSahana == "inj") {
			this.tagColor         = "C00";
			this.tagRGBA		  = "rgba(250,220,220, 0.60)";
			this.tagClass         = "statusInjured";
			this.statusSahanaFull = "injured";

		} else if (this.statusSahana == "dec") {
			this.tagColor         = "000";
			this.tagRGBA		  = "rgba(220,220,220, 0.60)";
			this.tagClass         = "statusDeceased";
			this.statusSahanaFull = "deceased";
		} else if (this.statusSahana == "fnd") {
			this.tagColor         = "802A2A";
			this.tagClass         = "statusFound";
			this.statusSahanaFull = "found";
		} else {
			this.tagColor         = "777";
			this.tagRGBA		  = "rgba(220,220,220, 0.60)";
			this.tagClass         = "statusUnknown";
			this.statusSahanaFull = "unknown";
		}
	};
}
<commit_msg>fix default search result order for SQL<commit_after>// iWall v1.6.0 //
// -----------------------------
// v1.0.0 ~ greg original
// v1.0.1 ~ merwan revisions
// v1.1.0 ~ begin using DOM tree manipulations and jquery
// v1.5.0 ~ new views, separated into proper files.
// v1.6.0 ~ filters working, infinite loop bug fixed (xajax not respecting scope)

// used to simulate array functions
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

// called when user starts the application
$(document).ready(function start() {
	Globals.searchMode = $("#searchMode").val();
	Globals.isiPad = window.Touch != undefined;
	window.onorientationchange = function() {
		ScrollView.pause();
		if (!Globals.displayMode && $("#content").css("display") == "none") {
			ScrollView.goFullScreen()
		} else {
			searchSubset(true);
		}

	}

	var doc = document,
		hash = window.location.hash;

	hash = hash.replace("_details", "");

	Globals.initDone = 1;

    $("#content").css({ paddingRight: "20px", paddingTop: "0px" });
    $("#wrapper_menu").css({ height: "0px" });

        // obsolete? (maybe should be detailsPane anyway?)
	//$("#details").hide();

	// add an event to monitor when the search box gains focus
	var box = doc.getElementById("searchBox");
	box.onfocus = function() {
		box.style.color = "#000000";
		box.value = box.value == "Enter a name..." ? "" : box.value;
	}

	$("#sortOrderIcon").click(function() { Utils.ascDesc(this) }).css({cursor: "pointer"});

	$("#buttonPlay").css("opacity", 0.3);
	$("#buttonPlay").css("filter", "progid:DXImageTransform.Microsoft.Alpha(opacity=30)");

	$("#loadingX").css( {height: Math.round($(window).height() - 190) + "px", paddingTop: Math.round(($(window).height() - 350)/2) + "px"});

	Globals.imageHeight = Math.floor(($(window).height() - Globals.headerHeight - Globals.footerHeight - (2*(Globals.rowPadding+Globals.imageBorder))) / Globals.maxRows);

	if ( hash.length > 1 ) { //for bookmarking
		if ( hash === "#searchAll" ) {
			hash = "";
		} else {
			box.style.color = "#000000";
			$("#searchBox").val(unescape(hash).replace('#', ''));
		}
		searchSubset(true);
	}
});

function searchSubset(first) {
	Globals.searchTerms = $.trim($("#searchBox").attr("value"));
	Globals.searchTerms = Globals.searchTerms == "Enter a name..." || Globals.searchTerms == "All" ? "" : Globals.searchTerms;

	var missing   = $("#checkMissing")   .is(":checked"),
		alive     = $("#checkAliveWell") .is(":checked"),
		injured   = $("#checkInjured")   .is(":checked"),
		deceased  = $("#checkDeceased")  .is(":checked"),
		unknown   = $("#checkUnknown")   .is(":checked"),
		found     = $("#checkFound")     .is(":checked"),

		complex   = $("#checkSexComplex").is(":checked"),
		male 	  = $("#checkSexMale")   .is(":checked"),
		female 	  = $("#checkSexFemale") .is(":checked"),
		genderUnk = $("#checkSexOther")  .is(":checked"),

		child 	  = $("#checkAgeChild")  .is(":checked"),
		adult	  = $("#checkAgeYouth")  .is(":checked"),
		ageUnk    = $("#checkAgeUnknown").is(":checked"),

		suburban  = $("#checkSuburban")  .is(":checked"),
		nnmc      = $("#checkNNMC")      .is(":checked"),
		otherHosp = $("#checkOtherHosp") .is(":checked"),

		sStatus       = missing + ";" + alive + ";" + injured + ";" + deceased + ";" + unknown + ";" + found,
		sGender       = complex + ";" + male + ";" + female + ";" + genderUnk,
		sAge          = child + ";" + adult + ";" +	ageUnk,
		sHospital     = suburban + ";" + nnmc + ";" + otherHosp,

		sPageControls = Globals.perPage * (Globals.currPage - 1)  + ";"
					  + Globals.perPage + ";"
					  + Globals.sortedBy + ";"
					  +	Globals.displayMode;

	Globals.incident = Globals.incident || $("#shortName").val();
	Globals.searchMode = $("#searchMode").val();
	$("#updateAlerts, #updateAlerts2").hide();

	inw_getData(Globals.searchMode, Globals.incident, Globals.searchTerms, sStatus, sGender, sAge, sHospital, sPageControls);
	if ( Globals.searchMode == "sql" ) {
		sPageControls = Globals.perPage * (Globals.currPage)  + ";"
				  + Globals.perPage + ";"
				  + Globals.sortedBy + ";"
				  +	Globals.displayMode;
		if ( Globals.displayMode ) {
			inw_hasNextPage(Globals.searchMode, Globals.incident, Globals.searchTerms, sStatus, sGender, sAge, sHospital, sPageControls);
			inw_getAllCount(Globals.incident);
		}
		$("#sqlFoundLabel").show();
		$("#solrFoundLabel").hide();
	} else {
		$("#solrFoundLabel").show();
		$("#sqlFoundLabel").hide();
	}

	$("#foundLabel").show();
	$("#refreshLabel").hide();
	if ( Globals.displayMode && Globals.searchMode != "sql" )
		$("#maxShown").hide();
	else
		$("#maxShown").show();

	$("#menuwrap").append($("#searchOptions").css({marginTop: "5px", marginLeft: "10px"}).show());
	if ( !$("#shortName").val().match(/(cmax|shield)/) ) $("#hospital").hide();
	$("#content").css({marginRight: "0px", paddingRight: "20px"});
        $("#buttonHelp").show();

	if ( Globals.initDone == 1 )
		$("#scrolling_content").html('

').show(50);

        // Queue up next search at first invocation.
        if (first) {
        	clearInterval(Globals.updaterId);
       		Globals.updaterId = setInterval(
                        "inw_checkForChanges('"+Globals.searchMode+"','"+Globals.incident+"','"+Globals.searchTerms+"','"+sStatus+"','"+sGender+"','"+sAge+"','"+sHospital+"')",
        		Globals.updaterTimer);
        }
}

Object.size = function(obj) {
	var size = 0, key;
	for (key in obj) {
		if (obj.hasOwnProperty(key)) size++;
	}
	return size;
};

function handleUuidListResponse() {
        // obsolete?
	//var temp = [], freshUuids = [];

	$("#totalRecordsSOLR").html(Utils.addCommas($("#totalRecordsSOLR").html()));

	showFacets();
	window.location.hash = Globals.searchTerms === "" ? "searchAll" : Globals.searchTerms;

	if ( Globals.displayMode ) {
		Globals.displayMode = true;
		DetailsView.drawPage();
	}
	else
		ScrollView.init();
}

function showFacets() {
        // obsolete?
	//var tempGender = 0, tempAge = 0;

	if ( Globals.searchMode == "solr" ) {
		var facets = jQuery.parseJSON($("#SOLRFacets").val());
		for( facet in facets ) {
			$("#" + facet + " > span").remove();
			$("#" + facet).append($("")
						  .css("font-size", "8pt")
						  .css("position", "absolute")
						  .css("right", "30px")
						  .css("margin-top", "5px")
						  .css("font-weight", "bold")
						  .html(Utils.addCommas(facets[facet])));
                        // obsolete?
			//if ( (facet == "male" || facet == "female") && parseInt(facets[facet]) > 0 )
				//tempGender++;
			//else if ( (facet == "child" || facet == "adult") && parseInt(facets[facet]) > 0 )
				//tempAge++;
		}
	} else {
		$("#filtersWrapper").find("label > span").remove();
	}
}

//
// Person Class
//
function Person() {

	// Basically takes the json-derived associative-array and inits fields.
	// Also inits other useful fields.
	this.init =  function(args) {
		if ( args ) {
			var date = Date.parse(args["statusSahanaUpdated"]);
			this.uuid         = args["p_uuid"];
			this.encodedUUID  = args["encodedUUID"];
			this.statusSahana = args["opt_status"];
			this.name         = $.trim(args["full_name"]) === "Unknown Unknown" || $.trim(args["full_name"]) == undefined ? "Unknown name" :  $.trim(args["full_name"]) || "Unknown name";

                        // Added check for zero (PL-253).
			this.age	  = (args["years_old"] == 0)? 0 : args["years_old"] || -1;
			this.minAge       = (args["minAge"] == 0)? 0 : args["minAge"] || -1;
			this.maxAge       = args["maxAge"] || -1;

			this.statusSahanaUpdated = date.toString("yyyy-MM-dd HH:mm");
			this.statusTriage = args["statusTriage"];
			this.id           = args["id"];
			this.peds         = args["peds"];
			this.location     = args["last_seen"];
			this.comments     = args["comments"];
			this.image        = null;
			this.imageUrl     = args["imageUrl"] || "res/img/s4unknown.png";
			this.imageHeight  = parseInt(args["imageHeight"]);
			this.imageWidth   = parseInt(args["imageWidth"]);
			this.hospitalIcon = args["hospitalIcon"] || "";
			this.imageShow    = true;
			this.x            = -999999;
			this.y            = -999999;
			this.wipe         = false;

			this.mass_casualty_id = args["mass_casualty_id"] || "";

                        // Added allowance for unbounded range (PL-252).
			if ( this.age > -1 )
				this.displayAge = this.age;
			else if ( this.minAge > -1 && this.maxAge == -1 )
				this.displayAge = this.minAge + "-?";
			else if ( this.minAge == -1 && this.maxAge > -1 )
				this.displayAge = "?-" + this.maxAge;
                        else if ( this.minAge > -1 && this.maxAge > -1 )
                                this.displayAge = this.minAge + "-" + this.maxAge;
			else
				this.displayAge = "Unknown";

			if ( args["gender"] === "mal" )
				this.gender = "Male";
			else if ( args["gender"] === "fml" )
				this.gender = "Female";
			else if ( args["gender"] === "cpx" )
				this.gender = "Complex";
			else
				this.gender = "Unknown";

			this.statusString()
		}
	};

		// to implement
	this.equals = function(otherPerson) {
		alert("equals!");
	}

	this.statusString = function() {
		var ss = this.statusSahana;

		if (this.statusSahana == "mis") {
			this.tagColor         = "00C";
			this.tagRGBA		  = "rgba(220,220,250, 0.60)";
			this.tagClass         = "statusMissing";
			this.statusSahanaFull = "missing";

		} else if (this.statusSahana == "ali") {
			this.tagColor         = "0A0";
			this.tagRGBA		  = "rgba(220,250,220, 0.60)";
			this.tagClass         = "statusAlive";
			this.statusSahanaFull = "alive and well";

		} else if (this.statusSahana == "inj") {
			this.tagColor         = "C00";
			this.tagRGBA		  = "rgba(250,220,220, 0.60)";
			this.tagClass         = "statusInjured";
			this.statusSahanaFull = "injured";

		} else if (this.statusSahana == "dec") {
			this.tagColor         = "000";
			this.tagRGBA		  = "rgba(220,220,220, 0.60)";
			this.tagClass         = "statusDeceased";
			this.statusSahanaFull = "deceased";
		} else if (this.statusSahana == "fnd") {
			this.tagColor         = "802A2A";
			this.tagClass         = "statusFound";
			this.statusSahanaFull = "found";
		} else {
			this.tagColor         = "777";
			this.tagRGBA		  = "rgba(220,220,220, 0.60)";
			this.tagClass         = "statusUnknown";
			this.statusSahanaFull = "unknown";
		}
	};
}
<|endoftext|>