<commit_before>define(function(require, exports, module) {
    main.consumes = ["Plugin", "automate", "vfs", "c9", "proc", "fs", "error_handler"];
    main.provides = ["installer"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var automate = imports.automate;
        var c9 = imports.c9;
        var fs = imports.fs;
        var proc = imports.proc;
        var errorHandler = imports.error_handler;

        var DEBUG = c9.location.indexOf("debug=3") != -1;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit = plugin.getEmitter();

        var NAMESPACE = "installer";
        var installSelfCheck = options.installSelfCheck && c9.platform != "win32";
        var installChecked = false;

        var packages = {};
        var sessions = [];
        var installed = false;
        var waitForSuccess = false;
        var installCb, arch;

        // Check that all the dependencies are installed
        var VERSION = 1;

        if (!options.cli)
            createSession("Cloud9 IDE", VERSION, require("./install/install"));

        function load() {
            if (options.cli)
                return simpleInstallRead();

            imports.vfs.on("beforeConnect", function(e) {
                if (installChecked)
                    return e.done(false);

                if (!installSelfCheck) {
                    installChecked = true;
                    e.done(false);
                    simpleInstallRead();
                    return;
                }

                installCb = e.done;

                if (!proc.installMode)
                    readFromDisk(e.vfs);
                else
                    proc.installMode = e.vfs;

                return false;
            });
        }

        /***** Methods *****/

        function simpleInstallRead(){
            var path = options.installPath.replace(c9.home, "~") + "/installed";
            fs.readFile(path, function(err, data) {
                if (err) {
                    if (err.code == "ENOENT")
                        installed = {};
                    else
                        c9.once("connect", simpleInstallRead);
                    return;
                }

                parse(data);
                emit.sticky("ready", installed);
            });
        }

        function parse(data){
            if (data.match(/^1[\r\n]*$/)) // Backwards compatibility
                data = "Cloud9 IDE@1\nc9.ide.collab@1\nc9.ide.find@1";

            installed = {};
            data.split("\n").forEach(function(line){
                if (!line) return;
                var p = line.split("@");
                installed[p[0]] = parseInt(p[1], 10) || 0;
            });
        }

        function readFromDisk(vfs){
            function done(err){
                if (!installed) installed = {};

                if (err && err.code == "ENOENT" || installed["Cloud9 IDE"] !== VERSION) {
                    // Tmux and pty.js are probably not installed. Lets switch
                    // to a special mode of proc
                    proc.installMode = vfs;

                    plugin.once("success", function(){
                        proc.installMode = false;
                        installChecked = true;
                        installCb(true);
                        installCb = null;
                    });

                    // Wait until installer is done
                    plugin.on("stop", function listen(e){
                        if (e.session.package.name == "Cloud9 IDE" && (!e.error || !waitForSuccess)) {
                            plugin.waitForSuccess = false;
                            plugin.off("stop", listen);
                        }
                    }, plugin);
                }
                else {
                    installChecked = true;
                    installCb();
                    installCb = null;
                }

                emit.sticky("ready", installed);
            }

            vfs.readfile(options.installPath.replace(c9.home, "~") + "/installed", {
                encoding: "utf8"
            }, function(err, meta) {
                if (err) {
                    if (err.code == "ENOENT") done(err);
                    return; // Wait for reconnect to try again
                }

                var data = "";
                var stream = meta.stream;
                stream.on("data", function(chunk){ data += chunk; });
                stream.on("end", function(){
                    parse(data);
                    done();
                });
            });
        }

        function addPackageManager(name, implementation){
            automate.addCommand(NAMESPACE, name, implementation);
        }

        function removePackageManager(name) {
            automate.removeCommand(NAMESPACE, name);
        }

        // Add aliases to support a broader range of platforms
        function addPackageManagerAlias(){
            var args = [NAMESPACE];
            for (var i = 0; i < arguments.length; i++) {
                args.push(arguments[i]);
            }

            automate.addCommandAlias.apply(this, args);
        }

        function isInstalled(pkgName, pkgVersion, callback){
            if (!installSelfCheck)
                return true;

            if (typeof pkgVersion == "function")
                callback = pkgVersion, pkgVersion = undefined;

            if (!installed && callback) {
                return plugin.once("ready", function(){
                    if (isInstalled(pkgName, pkgVersion, callback))
                        callback();
                });
            }

            var boolInstalled = installed[pkgName]
                && (pkgVersion ? installed[pkgName] == pkgVersion : true);

            if (!boolInstalled && callback) {
                plugin.on("stop", function listen(){
                    if (isInstalled(pkgName, pkgVersion)) {
                        callback();
                        plugin.off("stop", listen);
                    }
                });
            }

            return boolInstalled;
        }

        function reinstall(packageName, silent){
            if (packages[packageName]) {
                if (!silent)
                    emit("reinstall", { name: packageName });

                createSession(packageName, packages[packageName].version,
                    packages[packageName].populate, null, true);

                return true;
            }

            return false;
        }

        function createSession(packageName, packageVersion, populateSession, callback, force) {
            if (!installed) {
                return plugin.on("ready",
                    createSession.bind(this, packageName, packageVersion, populateSession, callback, force));
            }

            if (!options.cli && !c9.isReady) {
                return c9.on("ready",
                    createSession.bind(this, packageName, packageVersion, populateSession, callback, force));
            }

            if (typeof packageVersion == "function") {
                force = callback;
                callback = populateSession;
                populateSession = packageVersion;
                packageVersion = populateSession.version;
            }

            packageVersion  = populateSession.version || parseInt(packageVersion, 10) || 0;
            packages[packageName] = {
                version: packageVersion,
                populate: populateSession
            };

            if (!force && installed[packageName] == packageVersion)
                return callback && callback();

            var session = automate.createSession(NAMESPACE);

            var add = session.task; delete session.task;
            function install(options, task, validate) {
                if (!task || typeof task == "function") {
                    if (typeof task == "function")
                        validate = task;
                    task = options;
                    options = {};
                }

                add(task, options, validate);
            }

            function start(callback, force) {
                if (force || emit("beforeStart", { session: session }) !== false) {
                    // Pre script
                    if (pre) session.tasks.unshift({ "bash": pre });

                    // Post script
                    if (post) session.tasks.push({ "bash": post });

                    // Start installation
                    session.run(callback);
                }
            }

            session.on("run", function(){
                emit("start", { session: session });
            });
            session.on("stop", function(err){
                sessions.splice(sessions.indexOf(session), 1);
                emit("stop", { session: session, error: err });

                // Update installed file
                if (!err && force !== 2) {
                    installed[packageName] = packageVersion;
                    var contents = Object.keys(installed).map(function(item){
                        return item + "@" + installed[item];
                    }).join("\n");
                    fs.writeFile("~/.c9/installed", contents, function(){
                        callback && callback(err);
                    });
                }
                else {
                    callback && callback(err);
                }
            });
            session.on("each", function(e){
                emit("each", e);
            });

            var intro, pre, post;
            session.freezePublicAPI({
                /**
                 *
                 */
                package: {
                    name: packageName,
                    version: packageVersion
                },

                /**
                 *
                 */
                get introduction(){ return intro; },
                set introduction(value){ intro = value; },
                /**
                 *
                 */
                get preInstallScript(){ return pre; },
                set preInstallScript(value){ pre = value; },
                /**
                 *
                 */
                get postInstallScript(){ return post; },
                set postInstallScript(value){ post = value; },

                /**
                 *
                 */
                install: install,

                /**
                 *
                 */
                start: start
            });

            session.on("unload", function(){
                sessions.splice(sessions.indexOf(session), 1);
            }, plugin);

            sessions.push(session);

            if (arch === undefined) {
                arch = null;
                proc.execFile("uname", { args: ["-m"] }, function(e, p) {
                    if (/x86_64/.test(p)) p = "x64";
                    else if (/i.*86/) p = "x86";
                    else if (/armv6l|armv7l/) p = "arm-pi";
                    arch = p || undefined;
                    emit.sticky("arch", arch);
                });
            }

            plugin.once("arch", function() {
                populateSession(session, {
                    platform: c9.platform,
                    arch: arch
                });
            });

            return session;
        }

        function ptyExec(options, onData, callback) {
            console.log(options)
            // Working around PTY.js not having an exit code
            // Until https://github.com/chjj/pty.js/pull/110#issuecomment-93573223 is merged
            // wrap script in a function and use subshell to prevent exit 0 skipping echo ß
            // make sure sudo is called with correct passwd and
            var script = (DEBUG ? "set -x\n" : "")
                + 'export TERM=xterm\n' // helps with debian dialog error on apt-get install
                + 'fcn() {\n'+ options.code + '\n}\n'
                + 'sudo(){ /usr/bin/sudo -S -p "###[sudo] password for %p: " "$@" ; }\n'
                + 'exit() { if [ "$1" == "0" ]; then echo ß; else echo "exiting with $1"; fi; command exit $1; }\n'
                + 'fcn "$@" && echo ß\n';

            proc.pty(options.bash || "bash", {
                args: ["-c", script].concat(options.args || []),
                cwd: options.cwd || null
            }, function(err, pty){
                if (err) return callback(err);

                var done = false;
                var buffer = "";

                // Pipe the data to the onData function
                pty.on("data", function(chunk){
                    buffer += chunk;
                    if (chunk.indexOf("ß") > -1) {
                        done = true;
                        chunk = chunk.replace("ß", "");
                    }
                    onData(chunk, pty);
                });

                // When process exits call callback
                pty.on("exit", function(code){
                    if (!done && !code) code = "E_MISSING_END_MARKER";

                    if (code) {
                        errorHandler.log("install error", {
                            output: buffer,
                            script: script,
                            name: options.name,
                            args: options.args,
                            code: code
                        });
                    }

                    if (!code) callback();
                    else callback(new Error("Failed " + options.name + ". Exit code " + code));
                });
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("unload", function() {
            installChecked = false;
            installed = false;
            installCb = arch = undefined;
            waitForSuccess = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            /**
             *
             */
            get packages(){ return packages; },

            /**
             *
             */
            get sessions(){ return sessions; },

            /**
             *
             */
            get installed(){ return installed; },

            /**
             *
             */
            get checked(){ return installChecked; },

            /**
             * @ignore
             */
            get waitForSuccess(){ return waitForSuccess; },
            set waitForSuccess(v){ waitForSuccess = v; if (!v) emit("success"); },

            _events: [
                /**
                 * @event beforeStart
                 */
                "beforeStart",
                /**
                 * @event start
                 */
                "start",
                /**
                 * @event stop
                 */
                "stop",
                /**
                 * @event each
                 */
                "each"
            ],

            /**
             *
             */
            isInstalled: isInstalled,

            /**
             *
             */
            reinstall: reinstall,

            /**
             *
             */
            createSession: createSession,

            /**
             *
             */
            addPackageManager: addPackageManager,

            /**
             *
             */
            removePackageManager: removePackageManager,

            /**
             *
             */
            addPackageManagerAlias: addPackageManagerAlias,

            /**
             *
             */
            ptyExec: ptyExec,
        });

        register(null, {
            installer: plugin
        });
    }
});<commit_msg>update package.json<commit_after>define(function(require, exports, module) {
    main.consumes = ["Plugin", "automate", "vfs", "c9", "proc", "fs", "error_handler"];
    main.provides = ["installer"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var automate = imports.automate;
        var c9 = imports.c9;
        var fs = imports.fs;
        var proc = imports.proc;
        var errorHandler = imports.error_handler;

        var DEBUG = c9.location.indexOf("debug=3") != -1;

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit = plugin.getEmitter();

        var NAMESPACE = "installer";
        var installSelfCheck = options.installSelfCheck && c9.platform != "win32";
        var installChecked = false;

        var packages = {};
        var sessions = [];
        var installed = false;
        var waitForSuccess = false;
        var installCb, arch;

        // Check that all the dependencies are installed
        var VERSION = 1;

        if (!options.cli)
            createSession("Cloud9 IDE", VERSION, require("./install/install"));

        function load() {
            if (options.cli)
                return simpleInstallRead();

            imports.vfs.on("beforeConnect", function(e) {
                if (installChecked)
                    return e.done(false);

                if (!installSelfCheck) {
                    installChecked = true;
                    e.done(false);
                    simpleInstallRead();
                    return;
                }

                installCb = e.done;

                if (!proc.installMode)
                    readFromDisk(e.vfs);
                else
                    proc.installMode = e.vfs;

                return false;
            });
        }

        /***** Methods *****/

        function simpleInstallRead(){
            var path = options.installPath.replace(c9.home, "~") + "/installed";
            fs.readFile(path, function(err, data) {
                if (err) {
                    if (err.code == "ENOENT")
                        installed = {};
                    else
                        c9.once("connect", simpleInstallRead);
                    return;
                }

                parse(data);
                emit.sticky("ready", installed);
            });
        }

        function parse(data){
            if (data.match(/^1[\r\n]*$/)) // Backwards compatibility
                data = "Cloud9 IDE@1\nc9.ide.collab@1\nc9.ide.find@1";

            installed = {};
            data.split("\n").forEach(function(line){
                if (!line) return;
                var p = line.split("@");
                installed[p[0]] = parseInt(p[1], 10) || 0;
            });
        }

        function readFromDisk(vfs){
            function done(err){
                if (!installed) installed = {};

                if (err && err.code == "ENOENT" || installed["Cloud9 IDE"] !== VERSION) {
                    // Tmux and pty.js are probably not installed. Lets switch
                    // to a special mode of proc
                    proc.installMode = vfs;

                    plugin.once("success", function(){
                        proc.installMode = false;
                        installChecked = true;
                        installCb(true);
                        installCb = null;
                    });

                    // Wait until installer is done
                    plugin.on("stop", function listen(e){
                        if (e.session.package.name == "Cloud9 IDE" && (!e.error || !waitForSuccess)) {
                            plugin.waitForSuccess = false;
                            plugin.off("stop", listen);
                        }
                    }, plugin);
                }
                else {
                    installChecked = true;
                    installCb();
                    installCb = null;
                }

                emit.sticky("ready", installed);
            }

            vfs.readfile(options.installPath.replace(c9.home, "~") + "/installed", {
                encoding: "utf8"
            }, function(err, meta) {
                if (err) {
                    if (err.code == "ENOENT") done(err);
                    return; // Wait for reconnect to try again
                }

                var data = "";
                var stream = meta.stream;
                stream.on("data", function(chunk){ data += chunk; });
                stream.on("end", function(){
                    parse(data);
                    done();
                });
            });
        }

        function addPackageManager(name, implementation){
            automate.addCommand(NAMESPACE, name, implementation);
        }

        function removePackageManager(name) {
            automate.removeCommand(NAMESPACE, name);
        }

        // Add aliases to support a broader range of platforms
        function addPackageManagerAlias(){
            var args = [NAMESPACE];
            for (var i = 0; i < arguments.length; i++) {
                args.push(arguments[i]);
            }

            automate.addCommandAlias.apply(this, args);
        }

        function isInstalled(pkgName, pkgVersion, callback){
            if (!installSelfCheck)
                return true;

            if (typeof pkgVersion == "function")
                callback = pkgVersion, pkgVersion = undefined;

            if (!installed && callback) {
                return plugin.once("ready", function(){
                    if (isInstalled(pkgName, pkgVersion, callback))
                        callback();
                });
            }

            var boolInstalled = installed[pkgName]
                && (pkgVersion ? installed[pkgName] == pkgVersion : true);

            if (!boolInstalled && callback) {
                plugin.on("stop", function listen(){
                    if (isInstalled(pkgName, pkgVersion)) {
                        callback();
                        plugin.off("stop", listen);
                    }
                });
            }

            return boolInstalled;
        }

        function reinstall(packageName, silent){
            if (packages[packageName]) {
                if (!silent)
                    emit("reinstall", { name: packageName });

                createSession(packageName, packages[packageName].version,
                    packages[packageName].populate, null, true);

                return true;
            }

            return false;
        }

        function createSession(packageName, packageVersion, populateSession, callback, force) {
            if (!installed) {
                return plugin.on("ready",
                    createSession.bind(this, packageName, packageVersion, populateSession, callback, force));
            }

            if (!options.cli && !c9.isReady) {
                return c9.on("ready",
                    createSession.bind(this, packageName, packageVersion, populateSession, callback, force));
            }

            if (typeof packageVersion == "function") {
                force = callback;
                callback = populateSession;
                populateSession = packageVersion;
                packageVersion = populateSession.version;
            }

            packageVersion  = populateSession.version || parseInt(packageVersion, 10) || 0;
            packages[packageName] = {
                version: packageVersion,
                populate: populateSession
            };

            if (!force && installed[packageName] == packageVersion)
                return callback && callback();

            var session = automate.createSession(NAMESPACE);

            var add = session.task; delete session.task;
            function install(options, task, validate) {
                if (!task || typeof task == "function") {
                    if (typeof task == "function")
                        validate = task;
                    task = options;
                    options = {};
                }

                add(task, options, validate);
            }

            function start(callback, force) {
                if (force || emit("beforeStart", { session: session }) !== false) {
                    // Pre script
                    if (pre) session.tasks.unshift({ "bash": pre });

                    // Post script
                    if (post) session.tasks.push({ "bash": post });

                    // Start installation
                    session.run(callback);
                }
            }

            session.on("run", function(){
                emit("start", { session: session });
            });
            session.on("stop", function(err){
                sessions.splice(sessions.indexOf(session), 1);
                emit("stop", { session: session, error: err });

                // Update installed file
                if (!err && force !== 2) {
                    installed[packageName] = packageVersion;
                    var contents = Object.keys(installed).map(function(item){
                        return item + "@" + installed[item];
                    }).join("\n");
                    fs.writeFile("~/.c9/installed", contents, function(){
                        callback && callback(err);
                    });
                }
                else {
                    callback && callback(err);
                }
            });
            session.on("each", function(e){
                emit("each", e);
            });

            var intro, pre, post;
            session.freezePublicAPI({
                /**
                 *
                 */
                package: {
                    name: packageName,
                    version: packageVersion
                },

                /**
                 *
                 */
                get introduction(){ return intro; },
                set introduction(value){ intro = value; },
                /**
                 *
                 */
                get preInstallScript(){ return pre; },
                set preInstallScript(value){ pre = value; },
                /**
                 *
                 */
                get postInstallScript(){ return post; },
                set postInstallScript(value){ post = value; },

                /**
                 *
                 */
                install: install,

                /**
                 *
                 */
                start: start
            });

            session.on("unload", function(){
                sessions.splice(sessions.indexOf(session), 1);
            }, plugin);

            sessions.push(session);

            if (arch === undefined) {
                arch = null;
                proc.execFile("uname", { args: ["-m"] }, function(e, p) {
                    if (/x86_64/.test(p)) p = "x64";
                    else if (/i.*86/) p = "x86";
                    else if (/armv6l|armv7l/) p = "arm-pi";
                    arch = p || undefined;
                    emit.sticky("arch", arch);
                });
            }

            plugin.once("arch", function() {
                populateSession(session, {
                    platform: c9.platform,
                    arch: arch
                });
            });

            return session;
        }

        function ptyExec(options, onData, callback) {
            // Working around PTY.js not having an exit code
            // Until https://github.com/chjj/pty.js/pull/110#issuecomment-93573223 is merged
            // wrap script in a function and use subshell to prevent exit 0 skipping echo ß
            // make sure sudo is called with correct passwd and
            var script = (DEBUG ? "set -x\n" : "")
                + 'export TERM=xterm\n' // helps with debian dialog error on apt-get install
                + 'fcn() {\n'+ options.code + '\n}\n'
                + 'sudo(){ /usr/bin/sudo -S -p "###[sudo] password for %p: " "$@" ; }\n'
                + 'exit() { if [ "$1" == "0" ]; then echo ß; else echo "exiting with $1"; fi; command exit $1; }\n'
                + 'fcn "$@" && echo ß\n';

            proc.pty(options.bash || "bash", {
                args: ["-c", script].concat(options.args || []),
                cwd: options.cwd || null
            }, function(err, pty){
                if (err) return callback(err);

                var done = false;
                var buffer = "";

                // Pipe the data to the onData function
                pty.on("data", function(chunk){
                    buffer += chunk;
                    if (chunk.indexOf("ß") > -1) {
                        done = true;
                        chunk = chunk.replace("ß", "");
                    }
                    onData(chunk, pty);
                });

                // When process exits call callback
                pty.on("exit", function(code){
                    if (!done && !code) code = "E_MISSING_END_MARKER";

                    if (code) {
                        errorHandler.log("install error", {
                            output: buffer,
                            script: script,
                            name: options.name,
                            args: options.args,
                            code: code
                        });
                    }

                    if (!code) callback();
                    else callback(new Error("Failed " + options.name + ". Exit code " + code));
                });
            });
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("unload", function() {
            installChecked = false;
            installed = false;
            installCb = arch = undefined;
            waitForSuccess = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
            /**
             *
             */
            get packages(){ return packages; },

            /**
             *
             */
            get sessions(){ return sessions; },

            /**
             *
             */
            get installed(){ return installed; },

            /**
             *
             */
            get checked(){ return installChecked; },

            /**
             * @ignore
             */
            get waitForSuccess(){ return waitForSuccess; },
            set waitForSuccess(v){ waitForSuccess = v; if (!v) emit("success"); },

            _events: [
                /**
                 * @event beforeStart
                 */
                "beforeStart",
                /**
                 * @event start
                 */
                "start",
                /**
                 * @event stop
                 */
                "stop",
                /**
                 * @event each
                 */
                "each"
            ],

            /**
             *
             */
            isInstalled: isInstalled,

            /**
             *
             */
            reinstall: reinstall,

            /**
             *
             */
            createSession: createSession,

            /**
             *
             */
            addPackageManager: addPackageManager,

            /**
             *
             */
            removePackageManager: removePackageManager,

            /**
             *
             */
            addPackageManagerAlias: addPackageManagerAlias,

            /**
             *
             */
            ptyExec: ptyExec,
        });

        register(null, {
            installer: plugin
        });
    }
});<|endoftext|>


<commit_before>/*

Copyright 2015 Lessig Equal Citizens Exploratory Committee

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

// Part of this function modified from here:
// http://stackoverflow.com/a/2880929/1569632
//
// NOTE: This could be made more efficient by caching the result (and then
// killing the cache on URL changes, but we only call it once, so meh.

// ******************************************************************************
//   BE CAREFUL WITH THIS FILE. IT IS INCLUDED IN teams and website repositories
// ******************************************************************************

var getUrlParams = function() {
  var match,
  pl     = /\+/g,  // Regex for replacing addition symbol with a space
  search = /([^&=]+)=?([^&]*)/g,
  decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
  query  = window.location.search.substring(1);

  urlParams = {};
  while (match = search.exec(query))
    urlParams[decode(match[1])] = decode(match[2]);

  return urlParams;
};

var readCookie = function(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
};

var validateEmail = function(email) {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
};

var paymentConfig = null;
var stripeHandler = null;

var getAmountCents = function() {
  return Math.floor($('#amount_input').val() * 100);
};

var validateForm = function() {
    var email = $('#email_input').val() || null;
    var occ = $('#occupation_input').val() || null;
    var emp = $('#employer_input').val() || null;
    var amount = $('#amount_input').val() || null;

    if (!email) {
      showError( "Please enter email");
      return false;
    } else if (!validateEmail(email)) {
      showError("Please enter a valid email");
      return false;
    } else if (!occ) {
      showError( "Please enter occupation");
      return false;
    } else if (!emp) {
      showError( "Please enter employer");
      return false;
    } else if (!amount) {
      showError( "Please enter an amount");
      return false;
    } else if (amount < 1) {
      showError( "Please enter an amount of $1 or more");
      return false;
    }
    return true;
};

var validateBitcoinForm = function() {
  var amount = $('#amount_input').val() || null;
  var firstName = $('#first_name_input').val() || null;
  var lastName = $('#last_name_input').val() || null;
  var address = $('#address_input').val() || null;
  var city = $('#city_input').val() || null;
  var state = $('#state_input').val() || null;
  var zip = $('#zip_input').val() || null;

  if (amount > 100) {
    showError( "Thank you for your generosity, but we are only able to accept Bitcoin donations of $100 or less");
    return false;
  } else if ($("#requiredConfirmation").is(':checked') == false ) {
    showError( "We are only able to accept donations from US citizens or green card holders, and you may only donate your own bitcoin.");
    return false;
  } else if (!firstName) {
    showError( "Please enter your first name");
    return false;
  } else if (!lastName) {
    showError( "Please enter your last name");
    return false;
  } else if (!address) {
    showError( "Please enter your address");
    return false;
  } else if (!city) {
    showError( "Please enter your address");
    return false;
  } else if (!state) {
    showError( "Please enter your state");
    return false;
  } else if (!zip) {
    showError( "Please enter your zip code");
    return false;
  } else {
    return true;
  }
}

var bitcoinPledge = function() {
    if (validateForm() && validateBitcoinForm()) {
        var amount = $('#amount_input').val() || null;

        setLoading(true);
        createPledge("Bitcoin", { BITCOIN: {} });
    }
    return false;
};

var paypalPledge = function() {
    if (validateForm()) {
        setLoading(true);
        createPledge("Paypal", { PAYPAL: { step : 'start' } });
    }
    return false;
};
var pledge = function() {
  if (validateForm()) {
    var cents = getAmountCents();
    stripeHandler.open({
      email: $('#email_input').val(),
      amount: cents
    });
  }
};

var showError = function(errorText) {
  $('#formError').text(errorText);
  $('#formError').show();
}

var setLoading = function(loading) {
  if (loading) {
    $('#pledgeButton .pledgeText').hide();
    $('#pledgeButton').off('click');
    $('#pledgeButton .spinner').show();
    $('#paypalButton').hide();
  } else {
    $('#pledgeButton .pledgeText').show();
    $('#pledgeButton').on('click', pledge);
    $('#pledgeButton .spinner').hide();
    $('#paypalButton').show();
  }
}

var onTokenRecv = function(token, args) {
  setLoading(true);
  createPledge(args.billing_name, { STRIPE: { token: token.id } });
};

var createPledge = function(name, payment) {
  var urlParams = getUrlParams();
  var pledgeType = null;
  var request_url = null;

  if ('STRIPE' in payment) {
      request_url = PLEDGE_URL + '/r/pledge';
  }

  if ('PAYPAL' in payment) {
      request_url = PLEDGE_URL + '/r/paypal_start';
  }

  if ('BITCOIN' in payment) {
      request_url = PLEDGE_URL + '/r/bitcoin_start';
  }
  // ALL PAYPAL PAYMENTS AND BITCOIN PAYMENTS ARE DONATIONS
  if($("#directDonate_input").is(':checked') || ('PAYPAL' in payment) || ('BITCOIN' in payment) ) {
    pledgeType = 'DONATION';
  } else {
    pledgeType = 'CONDITIONAL';
  }

  var firstName = $('#first_name_input').val() || null;
  var lastName = $('#last_name_input').val() || null;
  var address = $('#address_input').val() || null;
  var city = $('#city_input').val() || null;
  var state = $('#state_input').val() || null;
  var zip = $('#zip_input').val() || null;
  var recurring = $('#recurring_input').is(':checked');
  var recurrence_period = $('#recurrence_period_input').val() || null;
  var enddate = $('enddate_input').val() || null;
  var keep_donation = $('#keep_donation').is(':checked');
  if (($("#requiredConfirmation").is(':checked') == false ) && ('BITCOIN' in payment) ) {
    console.log('Trying to pay with BITCOIN without a confirmation')
    return;
  }

  var data = {
    email: $('#email_input').val(),
    phone: $('#phone_input').val(),
    name: name,
    occupation: $('#occupation_input').val(),
    employer: $('#employer_input').val(),
    target: $('#targeting_input').val(),
    subscribe: $('#emailSignupInput').is(':checked') ? true : false,
    // anonymous: $scope.ctrl.form.anonymous,
    amountCents: getAmountCents(),
    pledgeType: pledgeType,
    team: urlParams['team'] || readCookie("last_team_key") || '',
    payment: payment
  };
  if (recurring) {
    data['recurring'] = recurring;
  }
  if(recurrence_period) {
    data['recurrence_period'] = recurrence_period;
  }
  if(enddate) {
    data['enddate'] = enddate;
  }
  if ($("#requiredConfirmation").is(':checked')) {
    data['bitcoinConfirm'] = true;
  }

  if (firstName) {
    data['firstName'] = firstName;
  }

  if (lastName) {
    data['lastName'] = lastName;
  }

  if (address) {
    data['address'] = address;
  }

  if (zip) {
    data['zip'] = zip;
  }

  if (city) {
    data['city'] = city;
  }

  if (state) {
    data['state'] = state;
  }

  data['keep_donation'] = keep_donation;

  $("input[name='thingname']").each(function(index) {
    data[$(this).data()['nationbuildername']] =  $(this).val();
  });

  $.ajax({
      type: 'POST',
      url: request_url,
      data: JSON.stringify(data),
      contentType: "application/json",
      dataType: 'json',
      success: function(data) {
        if ('paypal_url' in data) {
          location.href = data.paypal_url
        } else if ('bitpay_url' in data) {
          location.href = data.bitpay_url
        } else {
          location.href = RECEIPT_URL + data.receipt_url + '&amount=' + data.pledge_amount + '&recurring=' + recurring;
        }
      },
      error: function(data) {
        setLoading(false);
        responseJSON = data.responseJSON || null

        if (responseJSON && ('paymentError' in responseJSON)) {
          showError("We're having trouble charging your card: " + responseJSON.paymentError);
        } else {
          $('#formError').text('Oops, something went wrong. Try again in a few minutes');
          $('#formError').show();
        }
      },
  });
};

$(document).ready(function() {
  var urlParams = getUrlParams();
  var passedEmail = urlParams['email'] || '';
  var header = urlParams['header'] || '';

  //choose the frequency type
  $('input[name=monthly]').click('click',function(){
    console.log('set it');
    $('#recurrence_period_input').val( $('input[name=monthly]:checked').val() );
  });

  $('#email_input').val(passedEmail);

  $('#pledgeButton').on('click', pledge);

  $('#paypalButton').on('click', paypalPledge);

  $('#bitcoinButton').on('click', bitcoinPledge);

  $.get(PLEDGE_URL + '/r/payment_config', {}, function(){}, "json").done(function(pConf) {
      paymentConfig = pConf;
      stripeConfig = {
        key: paymentConfig.stripePublicKey,
        name: 'Lessig Equal Citizens Exploratory Committee',
        panelLabel: 'Pledge',
        billingAddress: true,
        image: PLEDGE_URL + '/static/lessig-logo-128.png',
        token: function(token, args) {
          onTokenRecv(token, args);
        }
      };
    stripeHandler = StripeCheckout.configure(stripeConfig);
  });
});
<commit_msg>reverts to ternary operator (i guess we need this)<commit_after>/*

Copyright 2015 Lessig Equal Citizens Exploratory Committee

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

// Part of this function modified from here:
// http://stackoverflow.com/a/2880929/1569632
//
// NOTE: This could be made more efficient by caching the result (and then
// killing the cache on URL changes, but we only call it once, so meh.

// ******************************************************************************
//   BE CAREFUL WITH THIS FILE. IT IS INCLUDED IN teams and website repositories
// ******************************************************************************

var getUrlParams = function() {
  var match,
  pl     = /\+/g,  // Regex for replacing addition symbol with a space
  search = /([^&=]+)=?([^&]*)/g,
  decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
  query  = window.location.search.substring(1);

  urlParams = {};
  while (match = search.exec(query))
    urlParams[decode(match[1])] = decode(match[2]);

  return urlParams;
};

var readCookie = function(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
};

var validateEmail = function(email) {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
};

var paymentConfig = null;
var stripeHandler = null;

var getAmountCents = function() {
  return Math.floor($('#amount_input').val() * 100);
};

var validateForm = function() {
    var email = $('#email_input').val() || null;
    var occ = $('#occupation_input').val() || null;
    var emp = $('#employer_input').val() || null;
    var amount = $('#amount_input').val() || null;

    if (!email) {
      showError( "Please enter email");
      return false;
    } else if (!validateEmail(email)) {
      showError("Please enter a valid email");
      return false;
    } else if (!occ) {
      showError( "Please enter occupation");
      return false;
    } else if (!emp) {
      showError( "Please enter employer");
      return false;
    } else if (!amount) {
      showError( "Please enter an amount");
      return false;
    } else if (amount < 1) {
      showError( "Please enter an amount of $1 or more");
      return false;
    }
    return true;
};

var validateBitcoinForm = function() {
  var amount = $('#amount_input').val() || null;
  var firstName = $('#first_name_input').val() || null;
  var lastName = $('#last_name_input').val() || null;
  var address = $('#address_input').val() || null;
  var city = $('#city_input').val() || null;
  var state = $('#state_input').val() || null;
  var zip = $('#zip_input').val() || null;

  if (amount > 100) {
    showError( "Thank you for your generosity, but we are only able to accept Bitcoin donations of $100 or less");
    return false;
  } else if ($("#requiredConfirmation").is(':checked') == false ) {
    showError( "We are only able to accept donations from US citizens or green card holders, and you may only donate your own bitcoin.");
    return false;
  } else if (!firstName) {
    showError( "Please enter your first name");
    return false;
  } else if (!lastName) {
    showError( "Please enter your last name");
    return false;
  } else if (!address) {
    showError( "Please enter your address");
    return false;
  } else if (!city) {
    showError( "Please enter your address");
    return false;
  } else if (!state) {
    showError( "Please enter your state");
    return false;
  } else if (!zip) {
    showError( "Please enter your zip code");
    return false;
  } else {
    return true;
  }
}

var bitcoinPledge = function() {
    if (validateForm() && validateBitcoinForm()) {
        var amount = $('#amount_input').val() || null;

        setLoading(true);
        createPledge("Bitcoin", { BITCOIN: {} });
    }
    return false;
};

var paypalPledge = function() {
    if (validateForm()) {
        setLoading(true);
        createPledge("Paypal", { PAYPAL: { step : 'start' } });
    }
    return false;
};
var pledge = function() {
  if (validateForm()) {
    var cents = getAmountCents();
    stripeHandler.open({
      email: $('#email_input').val(),
      amount: cents
    });
  }
};

var showError = function(errorText) {
  $('#formError').text(errorText);
  $('#formError').show();
}

var setLoading = function(loading) {
  if (loading) {
    $('#pledgeButton .pledgeText').hide();
    $('#pledgeButton').off('click');
    $('#pledgeButton .spinner').show();
    $('#paypalButton').hide();
  } else {
    $('#pledgeButton .pledgeText').show();
    $('#pledgeButton').on('click', pledge);
    $('#pledgeButton .spinner').hide();
    $('#paypalButton').show();
  }
}

var onTokenRecv = function(token, args) {
  setLoading(true);
  createPledge(args.billing_name, { STRIPE: { token: token.id } });
};

var createPledge = function(name, payment) {
  var urlParams = getUrlParams();
  var pledgeType = null;
  var request_url = null;

  if ('STRIPE' in payment) {
      request_url = PLEDGE_URL + '/r/pledge';
  }

  if ('PAYPAL' in payment) {
      request_url = PLEDGE_URL + '/r/paypal_start';
  }

  if ('BITCOIN' in payment) {
      request_url = PLEDGE_URL + '/r/bitcoin_start';
  }
  // ALL PAYPAL PAYMENTS AND BITCOIN PAYMENTS ARE DONATIONS
  if($("#directDonate_input").is(':checked') || ('PAYPAL' in payment) || ('BITCOIN' in payment) ) {
    pledgeType = 'DONATION';
  } else {
    pledgeType = 'CONDITIONAL';
  }

  var firstName = $('#first_name_input').val() || null;
  var lastName = $('#last_name_input').val() || null;
  var address = $('#address_input').val() || null;
  var city = $('#city_input').val() || null;
  var state = $('#state_input').val() || null;
  var zip = $('#zip_input').val() || null;
  var recurring = $('#recurring_input').is(':checked') ? true : false;
  var recurrence_period = $('#recurrence_period_input').val() || null;
  var enddate = $('enddate_input').val() || null;
  var keep_donation = $('#keep_donation').is(':checked') ? true : false;
  if (($("#requiredConfirmation").is(':checked') == false ) && ('BITCOIN' in payment) ) {
    console.log('Trying to pay with BITCOIN without a confirmation')
    return;
  }

  var data = {
    email: $('#email_input').val(),
    phone: $('#phone_input').val(),
    name: name,
    occupation: $('#occupation_input').val(),
    employer: $('#employer_input').val(),
    target: $('#targeting_input').val(),
    subscribe: $('#emailSignupInput').is(':checked') ? true : false,
    // anonymous: $scope.ctrl.form.anonymous,
    amountCents: getAmountCents(),
    pledgeType: pledgeType,
    team: urlParams['team'] || readCookie("last_team_key") || '',
    payment: payment
  };
  if (recurring) {
    data['recurring'] = recurring;
  }
  if(recurrence_period) {
    data['recurrence_period'] = recurrence_period;
  }
  if(enddate) {
    data['enddate'] = enddate;
  }
  if ($("#requiredConfirmation").is(':checked')) {
    data['bitcoinConfirm'] = true;
  }

  if (firstName) {
    data['firstName'] = firstName;
  }

  if (lastName) {
    data['lastName'] = lastName;
  }

  if (address) {
    data['address'] = address;
  }

  if (zip) {
    data['zip'] = zip;
  }

  if (city) {
    data['city'] = city;
  }

  if (state) {
    data['state'] = state;
  }

  data['keep_donation'] = keep_donation;

  $("input[name='thingname']").each(function(index) {
    data[$(this).data()['nationbuildername']] =  $(this).val();
  });

  $.ajax({
      type: 'POST',
      url: request_url,
      data: JSON.stringify(data),
      contentType: "application/json",
      dataType: 'json',
      success: function(data) {
        if ('paypal_url' in data) {
          location.href = data.paypal_url
        } else if ('bitpay_url' in data) {
          location.href = data.bitpay_url
        } else {
          location.href = RECEIPT_URL + data.receipt_url + '&amount=' + data.pledge_amount + '&recurring=' + recurring;
        }
      },
      error: function(data) {
        setLoading(false);
        responseJSON = data.responseJSON || null

        if (responseJSON && ('paymentError' in responseJSON)) {
          showError("We're having trouble charging your card: " + responseJSON.paymentError);
        } else {
          $('#formError').text('Oops, something went wrong. Try again in a few minutes');
          $('#formError').show();
        }
      },
  });
};

$(document).ready(function() {
  var urlParams = getUrlParams();
  var passedEmail = urlParams['email'] || '';
  var header = urlParams['header'] || '';

  //choose the frequency type
  $('input[name=monthly]').click('click',function(){
    console.log('set it');
    $('#recurrence_period_input').val( $('input[name=monthly]:checked').val() );
  });

  $('#email_input').val(passedEmail);

  $('#pledgeButton').on('click', pledge);

  $('#paypalButton').on('click', paypalPledge);

  $('#bitcoinButton').on('click', bitcoinPledge);

  $.get(PLEDGE_URL + '/r/payment_config', {}, function(){}, "json").done(function(pConf) {
      paymentConfig = pConf;
      stripeConfig = {
        key: paymentConfig.stripePublicKey,
        name: 'Lessig Equal Citizens Exploratory Committee',
        panelLabel: 'Pledge',
        billingAddress: true,
        image: PLEDGE_URL + '/static/lessig-logo-128.png',
        token: function(token, args) {
          onTokenRecv(token, args);
        }
      };
    stripeHandler = StripeCheckout.configure(stripeConfig);
  });
});
<|endoftext|>


<commit_before>'use strict';
// generated on 2017-03-03 using generator-gulp-bootstrap 0.0.4

var gulp = require('gulp');
var browserSync = require('browser-sync');
var pump = require('pump');
var reload = browserSync.reload;
var gutil = require('gulp-util');
var sassJson = require('gulp-sass-json');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', ['sassvars'], function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.sass({ errLogToConsole: true }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('app/styles'))
        .pipe(reload({ stream: true }))
        .pipe($.size());
});

gulp.task('sassvars', function () {
    return gulp.src('app/styles/base/_variables.scss')
        .pipe(sassJson())
        .pipe(gulp.dest('app/styles'));
});

gulp.task('scripts', function () {

    gulp.src('app/scripts/main/**/*.html')
        .pipe($.angularTemplatecache('templates.js', {
            module: 'vbr-style-guide'
        }))
        .pipe(gulp.dest('app/scripts/main'));

    return gulp.src(['app/scripts/main/**/*.module.js', 'app/scripts/main/**/*.js'])
        .pipe($.jshint())
        .pipe($.ngAnnotate({
            remove: true,
            add: true,
            single_quotes: true
        }))
        .pipe($.uglify())
        .pipe($.concat('main.js'))
        .pipe(gulp.dest('app/scripts'))
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('styleguide'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('styleguide/images'))
        .pipe(reload({ stream: true, once: true }))
        .pipe($.size());
});

gulp.task('fonts', function () {
    var streamqueue = require('streamqueue');
    return streamqueue({ objectMode: true },
        $.bowerFiles(),
        gulp.src('app/fonts/**/*')
    )
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('styleguide/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['app/styles/main.css', 'app/styles/variables.json', 'styleguide', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('serve', ['aigis'], function () {
    browserSync.init(null, {
        server: {
            baseDir: 'styleguide',
            directory: true
        },
        debugInfo: false,
        open: false
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started connect web server on ' + bs.options.url);
    });
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;
    gulp.src('app/styles/*.scss')
        .pipe(wiredep({
            directory: 'bower_components'
        }))
        .pipe(gulp.dest('app/styles'));
    gulp.src('template_ejs/scripts.ejs')
        .pipe(wiredep({
            directory: 'bower_components',
            fileTypes: {
                html: {
                    replace: {
                        js: '<script src="<%- root%>{{filePath}}"></script>'
                    }
                }
            }
        }))
        .pipe(gulp.dest('template_ejs'));
});

gulp.task('watch', ['serve'], function () {

    // watch for changes
    gulp.watch(['styleguide/*.html'], reload);
    gulp.watch(['aigis_config.yml', 'template_ejs/**/*', 'aigis_assets/**/*'], ['aigis', 'delayed-reload']);
    gulp.watch('app/styles/**/*.scss', ['styles', 'aigis']);
    gulp.watch(['app/scripts/main/**/*.js', 'app/scripts/**/*.html'], ['scripts', 'aigis']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('html/**/*', ['aigis']);
    gulp.watch('bower.json', ['wiredep', 'aigis']);
});

gulp.task("aigis", ['styles', 'scripts'], function () {
    gulp.src("./aigis_config.yml")
        .pipe($.aigis());
});

gulp.task('delayed-reload', function () {
    setTimeout(reload, 5000);
});

gulp.task('buildScripts',function(cb){
    pump([
            gulp.src(['app/scripts/main/*.module.js','app/scripts/main/*.directive.js','app/scripts/main/*.controller.js','app/scripts/main/templates.js','app/scripts/main/*.constants.js','!app/scripts/**/*.spec.js','app/scripts/main/components/**/*.js']),
            $.ngAnnotate(),
            $.uglify(),
            $.concat('index.min.js'),
            gulp.dest('dist/scripts/')
        ],
        cb
    );
});

gulp.task('buildStyles',function(cb){
    pump([
        gulp.src('app/styles/**/*.scss'),
        $.size(),
        gulp.dest('dist/scss/')
    ],
    cb);
});

gulp.task('build', ['clean','buildScripts','buildStyles'], function () {
    return true;
});

gulp.task('default', ['clean'], function () {
    gulp.start('watch');
});
<commit_msg>fix (build)<commit_after>'use strict';
// generated on 2017-03-03 using generator-gulp-bootstrap 0.0.4

var gulp = require('gulp');
var browserSync = require('browser-sync');
var pump = require('pump');
var reload = browserSync.reload;
var gutil = require('gulp-util');
var sassJson = require('gulp-sass-json');

// load plugins
var $ = require('gulp-load-plugins')();

gulp.task('styles', ['sassvars'], function () {
    return gulp.src('app/styles/main.scss')
        .pipe($.sass({ errLogToConsole: true }))
        .pipe($.autoprefixer('last 1 version'))
        .pipe(gulp.dest('app/styles'))
        .pipe(reload({ stream: true }))
        .pipe($.size());
});

gulp.task('sassvars', function () {
    return gulp.src('app/styles/base/_variables.scss')
        .pipe(sassJson())
        .pipe(gulp.dest('app/styles'));
});

gulp.task('scripts', function () {

    gulp.src('app/scripts/main/**/*.html')
        .pipe($.angularTemplatecache('templates.js', {
            module: 'vbr-style-guide'
        }))
        .pipe(gulp.dest('app/scripts/main'));

    return gulp.src(['app/scripts/main/**/*.module.js', 'app/scripts/main/**/*.js'])
        .pipe($.jshint())
        .pipe($.ngAnnotate({
            remove: true,
            add: true,
            single_quotes: true
        }))
        .pipe($.uglify())
        .pipe($.concat('main.js'))
        .pipe(gulp.dest('app/scripts'))
        .pipe($.jshint.reporter(require('jshint-stylish')))
        .pipe($.size());
});

gulp.task('html', ['styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js');
    var cssFilter = $.filter('**/*.css');

    return gulp.src('app/*.html')
        .pipe($.useref.assets())
        .pipe(jsFilter)
        .pipe($.uglify())
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe($.csso())
        .pipe(cssFilter.restore())
        .pipe($.useref.restore())
        .pipe($.useref())
        .pipe(gulp.dest('styleguide'))
        .pipe($.size());
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*')
        .pipe($.cache($.imagemin({
            optimizationLevel: 3,
            progressive: true,
            interlaced: true
        })))
        .pipe(gulp.dest('styleguide/images'))
        .pipe(reload({ stream: true, once: true }))
        .pipe($.size());
});

gulp.task('fonts', function () {
    var streamqueue = require('streamqueue');
    return streamqueue({ objectMode: true },
        $.bowerFiles(),
        gulp.src('app/fonts/**/*')
    )
        .pipe($.filter('**/*.{eot,svg,ttf,woff}'))
        .pipe($.flatten())
        .pipe(gulp.dest('styleguide/fonts'))
        .pipe($.size());
});

gulp.task('clean', function () {
    return gulp.src(['app/styles/main.css', 'app/styles/variables.json', 'styleguide', 'dist'], { read: false }).pipe($.clean());
});

gulp.task('serve', ['aigis'], function () {
    browserSync.init(null, {
        server: {
            baseDir: 'styleguide',
            directory: true
        },
        debugInfo: false,
        open: false
    }, function (err, bs) {
        require('opn')(bs.options.url);
        console.log('Started connect web server on ' + bs.options.url);
    });
});

// inject bower components
gulp.task('wiredep', function () {
    var wiredep = require('wiredep').stream;
    gulp.src('app/styles/*.scss')
        .pipe(wiredep({
            directory: 'bower_components'
        }))
        .pipe(gulp.dest('app/styles'));
    gulp.src('template_ejs/scripts.ejs')
        .pipe(wiredep({
            directory: 'bower_components',
            fileTypes: {
                html: {
                    replace: {
                        js: '<script src="<%- root%>{{filePath}}"></script>'
                    }
                }
            }
        }))
        .pipe(gulp.dest('template_ejs'));
});

gulp.task('watch', ['serve'], function () {

    // watch for changes
    gulp.watch(['styleguide/*.html'], reload);
    gulp.watch(['aigis_config.yml', 'template_ejs/**/*', 'aigis_assets/**/*'], ['aigis', 'delayed-reload']);
    gulp.watch('app/styles/**/*.scss', ['styles', 'aigis']);
    gulp.watch(['app/scripts/main/**/*.js', 'app/scripts/**/*.html'], ['scripts', 'aigis']);
    gulp.watch('app/images/**/*', ['images']);
    gulp.watch('html/**/*', ['aigis']);
    gulp.watch('bower.json', ['wiredep', 'aigis']);
});

gulp.task("aigis", ['styles', 'scripts'], function () {
    gulp.src("./aigis_config.yml")
        .pipe($.aigis());
});

gulp.task('delayed-reload', function () {
    setTimeout(reload, 5000);
});

gulp.task('buildScripts',function(cb){
    pump([
            gulp.src(['app/scripts/main/*.module.js','app/scripts/main/*.directive.js','app/scripts/main/*.controller.js','app/scripts/main/templates.js','app/scripts/main/*.constants.js','!app/scripts/**/*.spec.js', 'app/scripts/main/components/**/*.js']),
            $.ngAnnotate(),
            $.uglify(),
            $.concat('index.min.js'),
            gulp.dest('dist/scripts/')
        ],
        cb
    );
});

gulp.task('buildStyles',function(cb){
    pump([
        gulp.src('app/styles/**/*.scss'),
        $.size(),
        gulp.dest('dist/scss/')
    ],
    cb);
});

gulp.task('build', ['clean','buildScripts','buildStyles'], function () {
    return true;
});

gulp.task('default', ['clean'], function () {
    gulp.start('watch');
});
<|endoftext|>


<commit_before>/**
 * language fix
 */

const _ = require('lodash')

module.exports = async () => {
  const lang = require('@electerm/electerm-locales/dist/en_us.js').lang
  return prefix => {
    return (id) => {
      return _.get(lang, `${prefix}.${id}`) || id
    }
  }
}
<commit_msg>[skip build] Fix tests<commit_after>/**
 * language fix
 */

const _ = require('lodash')

function capitalizeFirstLetter (string) {
  return string.charAt(0).toUpperCase() + string.slice(1)
}

module.exports = async () => {
  const lang = require('@electerm/electerm-locales/dist/en_us.js').lang
  return prefix => {
    return (id) => {
      return capitalizeFirstLetter(_.get(lang, `${prefix}.${id}`) || id)
    }
  }
}
<|endoftext|>


<commit_before>'use strict'

import { Component }   from 'react'
import DocumentTitle   from 'react-document-title'
import marked          from 'marked'

import docs            from '../../docs.json'

marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false
})

class FAQpage extends Component {

  constructor (props) {
    super(props)

    this.state = {
      questions: null
    }

    this.setQuestions = this.setQuestions.bind(this)
  }

  componentWillMount() {
    this.setQuestions()
  }

  setQuestions() {
    let questions = []
    console.log(docs);
    let markdown = docs['faq'].markdown
    let markdownParts = markdown.split(/### (.*)/g)
    markdownParts.splice(0, 1)

    for (let i = 0; i < markdownParts.length; i += 2) {
      questions.push({
        question: markdownParts[i],
        answer: marked(markdownParts[i+1]),
      })
    }

    this.setState({
      questions
    })
  }

  render () {
    const { questions } = this.state

    return(
      <DocumentTitle title="Blockstack - FAQ">

Frequently Asked Questions

                { questions.map((faq, index) => {
                  return (

{ faq.question }

                  )
                }) }

      </DocumentTitle>
    );
  }

}

export default FAQpage
<commit_msg>remove logs<commit_after>'use strict'

import { Component }   from 'react'
import DocumentTitle   from 'react-document-title'
import marked          from 'marked'

import docs            from '../../docs.json'

marked.setOptions({
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false
})

class FAQpage extends Component {

  constructor (props) {
    super(props)

    this.state = {
      questions: null
    }

    this.setQuestions = this.setQuestions.bind(this)
  }

  componentWillMount() {
    this.setQuestions()
  }

  setQuestions() {
    let questions = []
    let markdown = docs['faq'].markdown
    let markdownParts = markdown.split(/### (.*)/g)
    markdownParts.splice(0, 1)

    for (let i = 0; i < markdownParts.length; i += 2) {
      questions.push({
        question: markdownParts[i],
        answer: marked(markdownParts[i+1]),
      })
    }

    this.setState({
      questions
    })
  }

  render () {
    const { questions } = this.state

    return(
      <DocumentTitle title="Blockstack - FAQ">

Frequently Asked Questions

                { questions.map((faq, index) => {
                  return (

{ faq.question }

                  )
                }) }

      </DocumentTitle>
    );
  }

}

export default FAQpage
<|endoftext|>


<commit_before>;
"use strict";

var duk = (function() {
    var streams = { "40"  : "http://radio.4duk.ru/4duk40.mp3"
                  , "64"  : "http://radio.4duk.ru/4duk64.mp3"
                  , "128" : "http://radio.4duk.ru/4duk128.mp3"
                  };

    var audio = new Audio(); var playing = false;

    function isPlaying() { return playing; }
    function setPlaying(p) { playing = p; return playing; }

    function getStreamQuality()        { return localStorage[ "stream_quality" ] || 128; }
    function setStreamQuality(stream_quality) { localStorage[ "stream_quality" ] = stream_quality; }

    function startPlaying() {
        audio.src = streams[ getStreamQuality() ];
        audio.load();
        audio.play();
        setPlaying(true);

        console.log(arguments.callee.name, audio.src);
    }

    function stopPlaying() {
        audio.pause();
        audio.currentTime = 0;
        audio.src = "";
        setPlaying(false);

        console.log(arguments.callee.name);
    }

    function shiftQuality() {
        var stream_quality = { "40"  : "64"
                             , "64"  : "128"
                             , "128" : "40"
                             }[ getStreamQuality() ];
        var was_playing = isPlaying();
        stopPlaying();
        setStreamQuality(stream_quality);
        if (was_playing) { startPlaying(); }

        console.log(arguments.callee.name);
    }

    chrome.commands.onCommand.addListener(function(command) {
        console.log("chrome commands' listener: ", command);

        switch (command) {
            case "toogle-playing": {
                if (isPlaying()) {
                    stopPlaying();
                } else {
                    startPlaying();
                }
            }
        }
    });

    return { startPlaying     : startPlaying
           , stopPlaying      : stopPlaying
           , shiftQuality     : shiftQuality
           , isPlaying        : isPlaying
           , getStreamQuality : getStreamQuality
    };
}());

function getDuk() { return duk; };

<commit_msg>Fix default quality value<commit_after>;
"use strict";

var duk = (function() {
    var streams = { "40"  : "http://radio.4duk.ru/4duk40.mp3"
                  , "64"  : "http://radio.4duk.ru/4duk64.mp3"
                  , "128" : "http://radio.4duk.ru/4duk128.mp3"
                  };

    var audio = new Audio(); var playing = false;

    function isPlaying() { return playing; }
    function setPlaying(p) { playing = p; return playing; }

    function getStreamQuality()        { return localStorage[ "stream_quality" ] || "128"; }
    function setStreamQuality(stream_quality) { localStorage[ "stream_quality" ] = stream_quality; }

    function startPlaying() {
        audio.src = streams[ getStreamQuality() ];
        audio.load();
        audio.play();
        setPlaying(true);

        console.log(arguments.callee.name, audio.src);
    }

    function stopPlaying() {
        audio.pause();
        audio.currentTime = 0;
        audio.src = "";
        setPlaying(false);

        console.log(arguments.callee.name);
    }

    function shiftQuality() {
        var stream_quality = { "40"  : "64"
                             , "64"  : "128"
                             , "128" : "40"
                             }[ getStreamQuality() ];
        var was_playing = isPlaying();
        stopPlaying();
        setStreamQuality(stream_quality);
        if (was_playing) { startPlaying(); }

        console.log(arguments.callee.name);
    }

    chrome.commands.onCommand.addListener(function(command) {
        console.log("chrome commands' listener: ", command);

        switch (command) {
            case "toogle-playing": {
                if (isPlaying()) {
                    stopPlaying();
                } else {
                    startPlaying();
                }
            }
        }
    });

    return { startPlaying     : startPlaying
           , stopPlaying      : stopPlaying
           , shiftQuality     : shiftQuality
           , isPlaying        : isPlaying
           , getStreamQuality : getStreamQuality
    };
}());

function getDuk() { return duk; };

<|endoftext|>


<commit_before>var React = require('react');

var MainComponent = require('../components/MainComponent');

require('../main.css');

var PropTypes = React.PropTypes;

var MainContainer = React.createClass({
  getDefaultProps: function() {
    return {
      latitude: 35.6684,
      longitude: -80.4786,
      zoom: 7,
      isChartsVisible: false,
      headerHeight:100,
      breadCrumbsHeight:50
    };
  },
  setHeight(repeat,val){
    //set the height of element based on a ratio 1.618
    if(repeat<1){
      return val
    } else{
      return this.setHeight(repeat-1, val/1.618)
    }
  },
  setSize: function(chartVis){
    //when state is not defined yet set to true
    var vis = this.state ? chartVis : false;
    var padding = this.state ? this.state.rowPadding : true;

    //components with fixed heights.
    var headerHeight = this.props.headerHeight;
    var breadCrumbsHeight = this.props.breadCrumbsHeight;

    //map and chart areas should scale to browser
    //for leaflet the map height needs to be explicit
    //adjustable heights.
    //first get whats leftover from fixed components
    // the calculate the map hieght.
    //give the rest to the chart
    var leftover = window.innerHeight -
                        (headerHeight + breadCrumbsHeight +
                          (padding*4)
                        );

    if (vis){
      var mapHeight = this.setHeight(1,leftover);
      var chartHeight = window.innerHeight - (leftover - mapHeight);
    } else {
      var mapHeight  = leftover
      var chartHeight = 0;
    }

    //do not let map height less than 250 pixels
    if (mapHeight < 300){
        mapHeight = 300
    }

    //do not let chart area less than 100 pixels
    //  may need to rethink this if the charts need more space....
    if (chartHeight < 100){
        chartHeight = 100
    }

    //set size varriabe
    return {
      isChartsVisible: vis,
      headerHeight: headerHeight,
      mapHeight: mapHeight,
      chartHeight: chartHeight,
      breadCrumbsHeight: breadCrumbsHeight,
      rowPadding: 1
    }
  },
  getInitialState: function () {
    var sizes = this.setSize();

    return{
      latitude: 35.6683,
      longitude: -80.4786,
      zoom: 7,
      defpad:5,
      isChartsVisible: false,
      rowPadding: 1,
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    }
  },
  handleChartToggle: function(e){
    //toggle state of chart area
    //var active = !this.state.isChartsVisible;

    //set new map size without chart area
    var sizes = this.setSize(false);

    this.setState({
      isChartsVisible: sizes.isChartsVisible,
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    })

  },
  HandleMapZoomEnd: function(mapComp,e){
    var L = mapComp.refs.map.leafletElement

    var zoom = L.getZoom();
    var center = L.getCenter();

    this.setState({
      zoom: zoom,
      latitude: center.lat,
      longitude: center.lng
    })

  },
  handleMapMoveEnd: function(mapComp,e){
    var L = mapComp.refs.map.leafletElement
    var center = L.getCenter();
    var zoom = L.getZoom();

    this.setState({
      zoom: zoom,
      latitude: center.lat,
      longitude: center.lng
    })
  },
  handleCenter: function(e){
    this.setState({
      latitude: 35.6683,
      longitude: -81.4786
    })
  },
  handleSearchChange: function(comp,e){

    var input = e.target;
    var options = {componentRestrictions: {country: 'us'}};
    var ac = new google.maps.places.Autocomplete(input, options);

    var self = this;

    google.maps.event.addListener(ac, 'place_changed', function () {
      var place = ac.getPlace();
      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();
      var zoom = self.state.zoom > 12 ? self.state.zoom  : 12

      self.setState({
        latitude: lat,
        longitude: lng,
        zoom: zoom
      })

  });

  },
  handleMapClick: function(e){

    //set new map size without chart area
    var sizes = this.setSize(true);

    this.setState({
      isChartsVisible: sizes.isChartsVisible,
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    })

  },
  handleResize: function(e) {

    //handling the scaling of map and chart areas
    var sizes = this.setSize(this.state.isChartsVisible);

    this.setState({
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    })
  },
  componentDidMount: function() {

    //handle resize.  - map and chart areas should scale to browser
    //width and height
    window.addEventListener('resize', this.handleResize);

    //for semantic-ui dropdowns..  not implemented yet
    $('.ui.dropdown').dropdown();
  },
  render: function() {
    return (
      <MainComponent
        defpad={this.state.defpad}
        latitude= {this.state.latitude}
        longitude= {this.state.longitude}
        zoom = {this.state.zoom}
        handleChartToggle={this.handleChartToggle}
        handleSearchChange={this.handleSearchChange}
        isChartsVisible={this.state.isChartsVisible}
        handleMapClick={this.handleMapClick}
        handleCenter={this.handleCenter}
        handleMapMoveEnd={this.handleMapMoveEnd}
        HandleMapZoomEnd={this.HandleMapZoomEnd}
        headerHeight={this.state.headerHeight}
        mapHeight={this.state.mapHeight}
        chartHeight={this.state.chartHeight}
        breadCrumbsHeight={this.state.breadCrumbsHeight}
        rowPadding={this.state.rowPadding} />
    )

  }

});

module.exports = MainContainer;
<commit_msg>tweaks to search<commit_after>var React = require('react');

var MainComponent = require('../components/MainComponent');

require('../main.css');

var PropTypes = React.PropTypes;

var MainContainer = React.createClass({
  getDefaultProps: function() {
    return {
      latitude: 35.6684,
      longitude: -80.4786,
      zoom: 7,
      isChartsVisible: false,
      headerHeight:100,
      breadCrumbsHeight:50
    };
  },
  setHeight(repeat,val){
    //set the height of element based on a ratio 1.618
    if(repeat<1){
      return val
    } else{
      return this.setHeight(repeat-1, val/1.618)
    }
  },
  setSize: function(chartVis){
    //when state is not defined yet set to true
    var vis = this.state ? chartVis : false;
    var padding = this.state ? this.state.rowPadding : true;

    //components with fixed heights.
    var headerHeight = this.props.headerHeight;
    var breadCrumbsHeight = this.props.breadCrumbsHeight;

    //map and chart areas should scale to browser
    //for leaflet the map height needs to be explicit
    //adjustable heights.
    //first get whats leftover from fixed components
    // the calculate the map hieght.
    //give the rest to the chart
    var leftover = window.innerHeight -
                        (headerHeight + breadCrumbsHeight +
                          (padding*4)
                        );

    if (vis){
      var mapHeight = this.setHeight(1,leftover);
      var chartHeight = window.innerHeight - (leftover - mapHeight);
    } else {
      var mapHeight  = leftover
      var chartHeight = 0;
    }

    //do not let map height less than 250 pixels
    if (mapHeight < 300){
        mapHeight = 300
    }

    //do not let chart area less than 100 pixels
    //  may need to rethink this if the charts need more space....
    if (chartHeight < 100){
        chartHeight = 100
    }

    //set size varriabe
    return {
      isChartsVisible: vis,
      headerHeight: headerHeight,
      mapHeight: mapHeight,
      chartHeight: chartHeight,
      breadCrumbsHeight: breadCrumbsHeight,
      rowPadding: 1
    }
  },
  getInitialState: function () {
    var sizes = this.setSize();

    return{
      latitude: 35.6683,
      longitude: -80.4786,
      zoom: 7,
      defpad:5,
      isChartsVisible: false,
      rowPadding: 1,
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    }
  },
  handleChartToggle: function(e){
    //toggle state of chart area
    //var active = !this.state.isChartsVisible;

    //set new map size without chart area
    var sizes = this.setSize(false);

    this.setState({
      isChartsVisible: sizes.isChartsVisible,
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    })

  },
  HandleMapZoomEnd: function(mapComp,e){
    var L = mapComp.refs.map.leafletElement

    var zoom = L.getZoom();
    var center = L.getCenter();

    this.setState({
      zoom: zoom,
      latitude: center.lat,
      longitude: center.lng
    })

  },
  handleMapMoveEnd: function(mapComp,e){
    var L = mapComp.refs.map.leafletElement
    var center = L.getCenter();
    var zoom = L.getZoom();

    this.setState({
      zoom: zoom,
      latitude: center.lat,
      longitude: center.lng
    })
  },
  handleCenter: function(e){
    this.setState({
      latitude: 35.6683,
      longitude: -81.4786
    })
  },
  handleSearchChange: function(comp,e){

    var input = e.target;
    //var options = {componentRestrictions: {country: 'us'}};
    // var ac = new google.maps.places.Autocomplete(input, options);

    var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(33.6878, -84.5288),
      new google.maps.LatLng(36.9674, -74.8169));

    var options = {bounds: defaultBounds}
    var self = this;

    var ac = new google.maps.places.SearchBox(input,options);

    google.maps.event.addListener(ac, 'places_changed', function () {
      var place = ac.getPlaces()[0];

      if (!place.geometry) return;

      if (!place.address_components){
          input.value = place.formatted_address
      }

      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();
      var zoom = self.state.zoom > 12 ? self.state.zoom  : 12

      self.setState({
        latitude: lat,
        longitude: lng,
        zoom: zoom
      })

      // google.maps.event.addDomListener(ac, 'keydown', function(e) {
      //   if (e.keyCode == 13) {
      //       e.preventDefault();
      //       var place = ac.getPlaces()[0];
      //
      //       //var place = ac.getPlace();
      //       var lat = place.geometry.location.lat();
      //       var lng = place.geometry.location.lng();
      //       var zoom = self.state.zoom > 12 ? self.state.zoom  : 12
      //
      //       self.setState({
      //         latitude: lat,
      //         longitude: lng,
      //         zoom: zoom
      //       })
      //
      //   }
      // });

  });

  },
  handleMapClick: function(e){

    //set new map size without chart area
    var sizes = this.setSize(true);

    this.setState({
      isChartsVisible: sizes.isChartsVisible,
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    })

  },
  handleResize: function(e) {

    //handling the scaling of map and chart areas
    var sizes = this.setSize(this.state.isChartsVisible);

    this.setState({
      headerHeight: sizes.headerHeight,
      mapHeight: sizes.mapHeight,
      chartHeight: sizes.chartHeight,
      breadCrumbsHeight: sizes.breadCrumbsHeight
    })
  },
  componentDidMount: function() {

    //handle resize.  - map and chart areas should scale to browser
    //width and height
    window.addEventListener('resize', this.handleResize);

    //for semantic-ui dropdowns..  not implemented yet
    $('.ui.dropdown').dropdown();
  },
  render: function() {
    return (
      <MainComponent
        defpad={this.state.defpad}
        latitude= {this.state.latitude}
        longitude= {this.state.longitude}
        zoom = {this.state.zoom}
        handleChartToggle={this.handleChartToggle}
        handleSearchChange={this.handleSearchChange}
        isChartsVisible={this.state.isChartsVisible}
        handleMapClick={this.handleMapClick}
        handleCenter={this.handleCenter}
        handleMapMoveEnd={this.handleMapMoveEnd}
        HandleMapZoomEnd={this.HandleMapZoomEnd}
        headerHeight={this.state.headerHeight}
        mapHeight={this.state.mapHeight}
        chartHeight={this.state.chartHeight}
        breadCrumbsHeight={this.state.breadCrumbsHeight}
        rowPadding={this.state.rowPadding} />
    )

  }

});

module.exports = MainContainer;
<|endoftext|>


<commit_before>(function() {

var ui = angular.module('axelor.ui');

PortalCtrl.$inject = ['$scope', '$element'];
function PortalCtrl($scope, $element) {

	var view = $scope._views['portal'];
	var viewPromise = $scope.loadView('portal', view.name);

	setTimeout(function(){
		$scope.$apply(function(){
			if (view.deferred)
				view.deferred.resolve($scope);
		});
	});

	viewPromise.success(function(fields, schema){
		$scope.parse(schema);
	});

	$scope.parse = function(schema) {
	};

	$scope.show = function(promise) {
		$scope.updateRoute();
	};

	$scope.getRouteOptions = function() {
		return {
			mode: 'portal',
			args: []
		};
	};

	$scope.setRouteOptions = function(options) {
		$scope.updateRoute();
	};

}

ui.directive('uiViewPortal', function(){
	return {
		scope: true,
		controller: PortalCtrl,
		link: function(scope, element, attrs) {

			scope.parse = function(schema) {
				scope.portletCols = schema.cols || 2;
				scope.portlets = schema.items;
			};

			setTimeout(function(){
				element.sortable({
					handle: ".portlet-header",
					items: "> .portlet"
				});
			});
		},
		replace: true,
		transclude: true,
		template:
		'
'+
			'

'+
		'
'
	};
});

PortletCtrl.$inject = ['$scope', '$element', 'MenuService', 'DataSource', 'ViewService'];
function PortletCtrl($scope, $element, MenuService, DataSource, ViewService) {

	$scope.initPortlet = function(action) {

		MenuService.action(action).success(function(result){
			if (_.isEmpty(result.data)) {
				return;
			}
			var view = result.data[0].view;

			$scope._viewParams = view;
			$scope._viewAction = action;

			ViewCtrl.call(self, $scope, DataSource, ViewService);

			$scope.title = view.title;
			$scope.parsePortlet(view);
		});
	};
}

ui.directive('uiViewPortlet', ['$compile', function($compile){
	return {
		scope: true,
		controller: PortletCtrl,
		link: function(scope, element, attrs) {
			setTimeout(function(){
				scope.initPortlet(attrs.action);
			});

			var initialized = false;
			scope.parsePortlet = function(view) {
				if (initialized) {
					return;
				}
				initialized = true;

				scope.noFilter = attrs.canSearch != "true";

				var template = $compile($('

'))(scope);
				element.find('.portlet-content:first').append(template);

				scope.show();

				if (scope.portletCols) {

					var cols = scope.portletCols;
					var colSpan = +attrs.colSpan || 1;
					var rowSpan = +attrs.rowSpan || 1;

					var width = 100;
					var height = (+attrs.height || 250) * rowSpan;

					width = (width / cols) * colSpan;

					element.width(width + '%').height(height);
				}
			};

			scope.onPortletToggle = function(event) {
				var e = $(event.target);
				e.toggleClass('icon-chevron-up icon-chevron-down');
				element.toggleClass('portlet-minimized');
				if (e.hasClass('icon-chevron-up')) {
					$.event.trigger('adjustSize');
				}
			};

			scope.doNext = function() {
				if (this.canNext()) this.onNext();
			};

			scope.doPrev = function() {
				if (this.canPrev()) this.onPrev();
			};
		},
		replace: true,
		template:
		'
'+
			'
'+
				'
'+
					'
'+
						'
'+
							''+
							'
'+
								'
'+
									'{{pagerText()}}'+
									''+
										''+
										''+
									''+
								'
'+
								'

'+
								'
'+
									''+
										''+
										''+
									''+
								'
'+
							'
'+
						'
'+
					'
'+
				'
'+
				'

'+
			'
'+
		'
'
	};
}]);

})();<commit_msg>Fixed portlet reload issue.<commit_after>(function() {

var ui = angular.module('axelor.ui');

PortalCtrl.$inject = ['$scope', '$element'];
function PortalCtrl($scope, $element) {

	var view = $scope._views['portal'];
	var viewPromise = $scope.loadView('portal', view.name);

	setTimeout(function(){
		$scope.$apply(function(){
			if (view.deferred)
				view.deferred.resolve($scope);
		});
	});

	viewPromise.success(function(fields, schema){
		$scope.parse(schema);
	});

	$scope.parse = function(schema) {
	};

	$scope.show = function(promise) {
		$scope.updateRoute();
	};

	$scope.onShow = function() {

	};

	$scope.getRouteOptions = function() {
		return {
			mode: 'portal',
			args: []
		};
	};

	$scope.setRouteOptions = function(options) {
		$scope.updateRoute();
	};

}

ui.directive('uiViewPortal', function(){
	return {
		scope: true,
		controller: PortalCtrl,
		link: function(scope, element, attrs) {

			scope.parse = function(schema) {
				scope.portletCols = schema.cols || 2;
				scope.portlets = schema.items;
			};

			setTimeout(function(){
				element.sortable({
					handle: ".portlet-header",
					items: "> .portlet"
				});
			});
		},
		replace: true,
		transclude: true,
		template:
		'
'+
			'

'+
		'
'
	};
});

PortletCtrl.$inject = ['$scope', '$element', 'MenuService', 'DataSource', 'ViewService'];
function PortletCtrl($scope, $element, MenuService, DataSource, ViewService) {

	var self = this;

	function init() {

		ViewCtrl.call(self, $scope, DataSource, ViewService);

		$scope.show = function() {

		};

		$scope.onShow = function() {

		};
	}

	$scope.initPortlet = function(action) {

		MenuService.action(action).success(function(result){
			if (_.isEmpty(result.data)) {
				return;
			}
			var view = result.data[0].view;

			$scope._viewParams = view;
			$scope._viewAction = action;

			init();

			$scope.title = view.title;
			$scope.parsePortlet(view);
		});
	};
}

ui.directive('uiViewPortlet', ['$compile', function($compile){
	return {
		scope: true,
		controller: PortletCtrl,
		link: function(scope, element, attrs) {
			setTimeout(function(){
				scope.initPortlet(attrs.action);
			});

			var initialized = false;
			scope.parsePortlet = function(view) {
				if (initialized) {
					return;
				}
				initialized = true;

				scope.noFilter = attrs.canSearch != "true";

				var template = $compile($('

'))(scope);
				element.find('.portlet-content:first').append(template);

				scope.show();

				if (scope.portletCols) {

					var cols = scope.portletCols;
					var colSpan = +attrs.colSpan || 1;
					var rowSpan = +attrs.rowSpan || 1;

					var width = 100;
					var height = (+attrs.height || 250) * rowSpan;

					width = (width / cols) * colSpan;

					element.width(width + '%').height(height);
				}
			};

			scope.onPortletToggle = function(event) {
				var e = $(event.target);
				e.toggleClass('icon-chevron-up icon-chevron-down');
				element.toggleClass('portlet-minimized');
				if (e.hasClass('icon-chevron-up')) {
					$.event.trigger('adjustSize');
				}
			};

			scope.doNext = function() {
				if (this.canNext()) this.onNext();
			};

			scope.doPrev = function() {
				if (this.canPrev()) this.onPrev();
			};
		},
		replace: true,
		template:
		'
'+
			'
'+
				'
'+
					'
'+
						'
'+
							''+
							'
'+
								'
'+
									'{{pagerText()}}'+
									''+
										''+
										''+
									''+
								'
'+
								'

'+
								'
'+
									''+
										''+
										''+
									''+
								'
'+
							'
'+
						'
'+
					'
'+
				'
'+
				'

'+
			'
'+
		'
'
	};
}]);

})();<|endoftext|>