<commit_before>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax;

(function ($module) {
    "use strict";

    $module.extend({

        window: {
            // function are object in js
            modal: {

                new: function () {

                    var
                        self = this,
                        $ = jQuery,
                        ajax = Ajax,
                        args = arguments[0],
                        body = $("body"),
                        time = 0,
                        Constructor = $module.window.modal.new,
                        headers = args.header || args.headers || null,
                        params = args.param || args.params || null,

                        modal,
                        mask,
                        main,
                        header,
                        actions,
                        btnClose,
                        container,
                        btnHide,
                        Constructor,

                        setButtonsAction = function () {

                            $(document).off("keydown").on("keydown", function (e) {
                                if (e.keyCode === 27) {
                                    self.hide();
                                }
                            });

                            btnHide.click(function () {
                                self.hide();
                            });

                            btnClose.click(function () {
                                self.close();
                            });

                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            esPhinx(container[0]).observe(function () {
                                // implementar método find em esPhinx
                                imgs = main.find("img");
                                if (imgs.length) {
                                    imgs.each(function (i, img) {
                                        esPhinx(img).on("load", function () {
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function (callback) {
                                            callback(length === imgs.length);
                                        },
                                        ready: function () {
                                            main.centralizeOn($(document));
                                            self.show();
                                        }
                                    })

                                } else {
                                    main.centralizeOn($(document));
                                    self.show();
                                }
                            });
                        },

                        create = function () {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            header = $("");
                            actions = $("

").addClass("actions");
                            btnClose = $('')
                                .addClass("btn-close");
                            btnHide = $('')
                                .addClass("btn-hide");
                            container = $("

").addClass("container");

                            body.append(modal);

                            modal
                                .append(mask)
                                .append(main);

                            main
                                .append(header)
                                .css({
                                    "max-height": $(window).height(),
                                    "max-width": $(document).width()
                                });

                            header.append(actions);

                            actions.append(btnClose);
                            actions.append(btnHide);

                            main.append(container);

                            setButtonsAction();

                            observeContent();

                            ajax.new(args.contentSource, {
                                params: params,
                                headers: headers,
                                processing: function (xhr) {
                                    // debugger
                                    if (args.loading) {
                                        args.loading(modal, xhr);
                                    }
                                },
                                success: function (answer) {
                                    container.append(answer);
                                }
                            });

                        };

                    if (!(this instanceof Constructor)) {
                        self = Singleton.instanceExists
                            .apply(Constructor, arguments.flatten());
                        if (self) {
                            self.show();
                        } else {
                            return Constructor.singleton(arguments);
                        }
                    // esse else deverá sair para que o show possa ser usado por quem o instanciou
                    } else {
                        create();
                    }

                    // global scope (public)
                    this.close = function () {
                        // o objeto deveria ser detruído da memória??
                        main.hide();

                        mask.replaceToggleClass("transparent", "opacity-transition");

                        time = parseFloat(
                            mask.css("transition-duration")
                        ) * 1000;
                        setTimeout(function () {
                            modal.remove();
                        }, time);

                        self.deleteSingleton();
                    };

                    this.hide = function () {
                        main.hide();

                        mask.replaceToggleClass("transparent", "opacity-transition");

                        modal.css("zIndex", -1);

                    };

                    this.show = function () {
                        // debugger;
                        // modal = modal || self.domObject;
                        modal.css("zIndex", 0);
                        mask
                            .replaceToggleClass("transparent",
                                "opacity-transition");

                        main.show();
                    };
                }
            }
        }
    });

}(esPhinx.ui));
<commit_msg>improves modal behavior<commit_after>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax;

(function ($module) {
    "use strict";

    $module.extend({

        window: {
            // function are object in js
            modal: {

                new: function () {

                    var
                        self = this,
                        $ = jQuery,
                        ajax = Ajax,
                        args = arguments[0],
                        body = $("body"),
                        time = 0,
                        Constructor = $module.window.modal.new,
                        headers = args.header || args.headers || null,
                        params = args.param || args.params || null,

                        modal,
                        mask,
                        main,
                        header,
                        actions,
                        btnClose,
                        container,
                        btnHide,
                        Constructor,

                        setButtonsAction = function () {

                            $(document).off("keydown").on("keydown", function (e) {
                                if (e.keyCode === 27) {
                                    self.hide();
                                }
                            });

                            btnHide.click(function () {
                                self.hide();
                            });

                            btnClose.click(function () {
                                self.close();
                            });

                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            esPhinx(container[0]).observe(function () {
                                // implementar método find em esPhinx
                                imgs = main.find("img");
                                if (imgs.length) {
                                    imgs.each(function (i, img) {
                                        esPhinx(img).on("load", function () {
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function (callback) {
                                            callback(length === imgs.length);
                                        },
                                        ready: function () {
                                            main.centralizeOn($(document));
                                            self.show();
                                        }
                                    })

                                } else {
                                    main.centralizeOn($(document));
                                    self.show();
                                }
                            });
                        },

                        create = function () {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            header = $("");
                            actions = $("

").addClass("actions");
                            btnClose = $('')
                                .addClass("btn-close");
                            btnHide = $('')
                                .addClass("btn-hide");
                            container = $("

").addClass("container");

                            modal
                                .append(mask)
                                .append(main);

                            main
                                .append(header)
                                .css({
                                    "max-height": $(window).height(),
                                    "max-width": $(document).width()
                                });

                            header.append(actions);

                            actions.append(btnClose);
                            actions.append(btnHide);

                            main.append(container);

                            setButtonsAction();

                            observeContent();

                            ajax.new(args.contentSource, {
                                params: params,
                                headers: headers,
                                processing: function (xhr) {
                                    if (args.loading) {
                                        args.loading(modal, xhr);
                                    }
                                },
                                success: function (answer) {
                                    body.append(modal);
                                    container.append(answer);
                                }
                            });

                        };

                    if (!(this instanceof Constructor)) {
                        self = Singleton.instanceExists
                            .apply(Constructor, arguments.flatten());
                        if (self) {
                            self.show();
                        } else {
                            return Constructor.singleton(arguments);
                        }
                    // esse else deverá sair para que o show possa ser usado por quem o instanciou
                    } else {
                        create();
                    }

                    // global scope (public)
                    this.close = function () {
                        // o objeto deveria ser detruído da memória??
                        main.hide();

                        mask.replaceToggleClass("transparent", "opacity-transition");

                        time = parseFloat(
                            mask.css("transition-duration")
                        ) * 1000;
                        setTimeout(function () {
                            modal.remove();
                        }, time);

                        self.deleteSingleton();
                    };

                    this.hide = function () {
                        main.hide();

                        mask.replaceToggleClass("transparent", "opacity-transition");

                        modal.css("zIndex", -1);

                    };

                    this.show = function () {
                        // debugger;
                        // modal = modal || self.domObject;
                        modal.css("zIndex", 0);
                        mask
                            .replaceToggleClass("transparent",
                                "opacity-transition");

                        main.show();
                    };
                }
            }
        }
    });

}(esPhinx.ui));
<|endoftext|>


<commit_before>$.fn.parallaxize = (function (global, $) {
    'use strict';

    function Parallax() {
        this.init.apply(this, Array.prototype.slice.call(arguments));
    }

    Parallax.prototype = {
        init: function (parent, settings) {
            this.initializeConfig(settings);
            this.config('element', parent);
            this.config('width', 1);
            this.config('height', 1);

            this.initializeDOM();
            this.initializeBindings();
        },

        initializeConfig: function (settings) {
            var config = {};
            settings = $.fn.extend({variation: 20}, settings);

            var getGetter = function (object) {
                return function (key, value) {
                    if (typeof key === 'undefined') {
                        return object;
                    }
                    if (typeof value === 'undefined') {
                        return object[key];
                    }
                    return object[key] = value;
                }
            };

            this.config = getGetter(config);
            this.setting = getGetter(settings);
        },

        initializeDOM: function () {
            var elem = this.config('element'),
                image_container = $('<div/>'),
                image = new Image(),
                image_elem = $(image).appendTo(image_container),
                me = this;
            elem.prepend(image_container);
            image_elem.hide();

            var synchronous = true;
            image.onload = function () {
                me.config('height', image_elem.height());
                me.config('width', image_elem.width());
                me.translate(false);

                if (synchronous) {
                    image_elem.show();
                } else {
                    image_elem.fadeIn(250);
                }
            };
            image.src = elem.data('background-image');
            setTimeout(function () {
                synchronous = false;
            }, 150);
            this.config('image', image_elem);

            elem.addClass('parallaxic-container');
            image_elem.addClass('parallaxic-image');
            image_container.addClass('parallax-image-container');

        },

        initializeBindings: function () {
            var me = this;
            $(global).scroll(function () {
                me.translate();
            });

            $(global).resize(function () {
                me.translate(false);
            });
        },

        translate: function (cache) {
            var transform = [
                this.resizeTranslation(cache),
                this.positionTranslation()
            ].join(' ');

            this.config('image').css({
                transform: transform,
                '-webkit-transform': transform,
                '-moz-transform': transform,
                '-o-transform': transform
            });
        },

        resizeTranslation: function (cached) {
            var scale;
            if (cached !== false) {
                scale = this.config('scale');
                if (scale) {
                    return 'scale(' + scale + ')';
                }
            }

            var variation = this.setting('variation'),
                elem = this.config('element'),
                image = this.config('image'),
                height = elem.height(),
                image_height = this.config('height'), image_width = this.config('width'),
                potential_height = height + variation * 2,
                new_width = elem.width(), new_height;

            new_height = (image_height / image_width) * new_width;

            if (new_height < potential_height) {
                new_height = potential_height;
                new_width = (image_width / image_height) * new_height;
            }

            scale = Math.ceil(new_height / image_height * 1000) / 1000;

            //if (Modernizr && !Modernizr.csstransforms) {
            //    image.css({
            //        width: new_width,
            //        height: new_height
            //    });
            //    return '';
            //}

            this.config('scale', scale);
            return 'scale(' + scale + ')';
        },

        positionTranslation: function () {

            var variation = this.setting('variation'),
                scale = this.config('scale'),
                elem = this.config('element'),
                image = this.config('image'),
                height = elem.height(), width = elem.width(),
                image_height = this.config('height'), image_width = this.config('width'),
                top = (height - image_height) / 2,
                left = (width - image_width) / 2,
                scroll_percentage = this.getScrollPercentage();

            top += (variation * 2 * scroll_percentage) - variation;

            // First assume translate
            //var method_start = 'translate(', method_end = ')';
            //
            //if (Modernizr) {
            //    if (Modernizr.csstransforms3d) {
            //        method_start = 'translate3d(';
            //        method_end = ', 0px)';
            //    } else if (!Modernizr.csstransforms) {
            //        return '';
            //    }
            //}
            //return method_start + Math.round(left) + 'px, ' + Math.round(top) + 'px' + method_end;

            return ['translate3d(', Math.round(left / scale), 'px, ', Math.round(top), 'px, ', '0px)'].join('');
        },

        getScrollPercentage: function () {
            var elem = this.config('element'),
                image = this.config('image'),
                main = $(global),
                min = elem.offset().top - main.height(),
                max = elem.offset().top + elem.height() - min,
                scroll = main.scrollTop() - min;

            return Math.max(0, Math.min(1, scroll / max));
        }

    };

    return function (settings) {
        this.data('parallax', new Parallax(this, settings))
    };

}(window, $));
<commit_msg>Revitalize parallax js<commit_after>(function (window, $) {

    /**
     * Parallax class
     *
     *     var parallax = new Parallax(container_div, { speed: 0.25 });
     *     parallax.render();
     *
     * Settings takes:
     * * speed: float between 0 and 1, 0 has no effect, 1 appears stationary. Sweet spot is between 0.2 and 0.7
     * * window: The nearest scrolling parent element to calculate the parallax against, defaults to the window
     *
     * @param HTMLElement element The container
     * @param object settings The settings
     * @constructor
     */
    var Parallax = function Parallax(element, settings) {
        this.$element = $(element);
        this.$image = null;
        this.image = null;

        // Apply the default settings
        this.settings = $.fn.extend({
            variation: 0,
            speed: 0.25,
            window: window
        }, settings);

        /**
         *
         */
        if (this.settings.variation) {
            // Always override speed if the variation is set.
            this.settings.speed = this.settings.variation / this.$element.height() / 5
        }

        this.$window = $(this.settings.window);
    };

    Parallax.prototype = {

        /**
         * Initialize the parallax, this method must be called for the parallax to begin loading.
         */
        init: function () {

            var my = this,
                outer = $('<div/>').addClass('parallax-image-container'),
                image = new Image();

            image.onload = function () {
                my.image = image;
                my.$image = $(image).addClass('parallaxic-image');

                my.handleResize();
                outer.append(my.$image);

                my.bindListeners();
            };

            image.src = this.$element.data('background-image');

            this.$element.addClass('parallaxic-container').prepend(outer);
        },

        /**
         * Bind event listeners
         */
        bindListeners: function () {
            var obj = this;
            this.$window.on('resize', function (e) {
                obj.handleResize();
            }).on('scroll', function (e) {
                obj.handleScroll();
            });
        },

        /**
         * Handle browser resize
         */
        handleResize: function () {
            var frame = this.getFrame();
            frame.determineScale(this);
            frame.determineOffsetLeft(this);

            this.render();
        },

        /**
         * Handle the browser scroll
         */
        handleScroll: function () {
            var window_top = this.$window.scrollTop(),
                window_height = this.$window.height(),
                container_top = this.$element.offset().top,
                container_height = this.$element.height();

            // Only render if this container is within the viewable window
            if (window_top + window_height > container_top &&
                window_top < container_top + container_height) {
                this.render();
            }
        },

        /**
         * Render the parallax
         */
        render: function () {
            var frame = this.getFrame();

            frame.determineOffsetTop(this);
            frame.determineParallax(this);
            frame.render(this);
        },

        /**
         * Get the ParallaxFrame object
         * @returns ParallaxFrame
         */
        getFrame: function () {
            if (!this.frame) {
                this.frame = new ParallaxFrame();
            }

            return this.frame;
        }

    };

    /**
     * The class used for managing parallax state change
     * @constructor
     */
    var ParallaxFrame = function ParallaxFrame() {
        this.scale = 1;
        this.offset = {x: 0, y: 0};
    };

    ParallaxFrame.prototype = {

        /**
         * Determine the images scale to properly satisfy the requirements
         * @param parallax
         */
        determineScale: function (parallax) {
            var image_height = parallax.image.height,
                image_width = parallax.image.width,
                container_height = parallax.$element.height(),
                container_width = parallax.$element.width(),
                speed = parallax.settings.speed,
                required_padding = speed * image_height,
                padded_container_height = container_height + required_padding,
                ratio;

            // If we aren't wide enough, or we are too tall
            if (image_width < container_width || image_height > padded_container_height) {
                // Get the ratio of the container width to the base image width
                ratio = container_width / image_width;

                // If we scale by the ratio, will we be tall enough?
                if (image_height * ratio >= padded_container_height) {
                    this.scale = ratio;
                } else {
                    // Since we weren't tall enough, scale by the height ratio
                    this.scale = padded_container_height / image_height / 2;
                }
            } else {
                // We're too wide and not tall enough, lets just scale by the height ratio
                this.scale = padded_container_height / image_height;
            }

            this.scale = Math.ceil(this.scale * 1000) / 1000;
        },

        /**
         * Figure out how far the image needs to be from the left
         * We need to do this because the image scales away from the center, not the top left
         * @param parallax
         */
        determineOffsetLeft: function (parallax) {
            var image_width = parallax.image.width,
                scaled_width = image_width * this.scale,
                width_difference = scaled_width - image_width;

            this.offset.x = width_difference / 2;
        },

        /**
         * Figure out how far the image needs to be from the top
         * We need to do this because the image scales away from the center, not the top left
         * @param parallax
         */
        determineOffsetTop: function (parallax) {
            var image_height = parallax.image.height,
                scaled_height = image_height * this.scale,
                height_difference = scaled_height - image_height;

            this.offset.y = height_difference / 2;
        },

        /**
         * Modify the offset to simulate parallax effect
         * @param parallax
         */
        determineParallax: function (parallax) {
            var speed = parallax.settings.speed,
                $container = parallax.$element,
                container_offset = $container.offset(),
                window_scroll = parallax.$window.scrollTop(),
                distance_to_top;

            distance_to_top = window_scroll - container_offset.top;
            this.offset.y += distance_to_top * speed;
        },

        /**
         * Set the actual CSS to change the positioning of this image
         * @param parallax
         */
        render: function (parallax) {
            var transformation = "";

            // Apply translation
            transformation += "translate3d(" + this.offset.x + "px," + this.offset.y + "px, 0) ";

            // Apply scale
            transformation += "scale3d(" + this.scale + "," + this.scale + "," + this.scale + ")";

            parallax.$image.get(0).style.transform = transformation;
        }
    };

    /**
     * Jquery parallaxize extension, easily create or retrieve a parallax instance with jQuery.
     *
     * @param object settings
     * @return Parallax
     */
    $.fn.parallaxize = function Parallaxize(settings) {
        var me = $(this), parallax;
        if (!me.data('parallax')) {
            parallax = new Parallax(this, settings);
            $(this).data('parallax', parallax);
            parallax.init();
        } else {
            parallax = me.data('parallax');
        }

        return parallax;
    };

}(this, jQuery));
<|endoftext|>


<commit_before>const
  chalk = require("ansi-colors"),
  os = require("os"),
  env = requireModule("env"),
  gulp = requireModule("gulp"),
  debug = require("debug")("build"),
  promisifyStream = requireModule("promisify"),
  dotnetCli = require("gulp-dotnet-cli"),
  dotnetClean = dotnetCli.clean,
  dotnetBuild = dotnetCli.build,
  throwIfNoFiles = requireModule("throw-if-no-files"),
  xbuild = requireModule("gulp-xbuild"),
  gutil = requireModule("gulp-util"),
  log = requireModule("log"),
  resolveMasks = requireModule("resolve-masks"),
  logConfig = requireModule("log-config"),
  msbuild = require("gulp-msbuild");

gulp.task("prebuild", ["nuget-restore"]);

const myTasks = ["build"],
  myVars = [
    "BUILD_CONFIGURATION",
    "BUILD_PLATFORM",
    "BUILD_ARCHITECTURE",
    "BUILD_TARGETS",
    "BUILD_TOOLSVERSION",
    "BUILD_VERBOSITY",
    "BUILD_MSBUILD_NODE_REUSE",
    "BUILD_MAX_CPU_COUNT",
    "MAX_CONCURRENCY",
    "BUILD_INCLUDE",
    "BUILD_EXCLUDE",
    "BUILD_ADDITIONAL_EXCLUDE",
    "BUILD_SHOW_INFO",
    "BUILD_FAIL_ON_ERROR",
    "BUILD_RETRIES"
  ];
env.associate(myVars, myTasks);

gulp.task(
  "build",
  "Builds Visual Studio solutions in tree",
  ["prebuild"],
  tryBuild
);

gulp.task("quick-build", "Quick build without pre-cursors", tryBuild);

async function tryBuild() {
  let attempts = env.resolveNumber("BUILD_RETRIES") + 1;
  if (attempts < 0) {
    attempts = 1;
  }
  const originalAttempts = attempts;

  while (attempts-- > 0) {
    try {
      await build();
    } catch (e) {
      if (attempts > 0) {
        console.error(chalk.red(`Build fails: ${e}`));
        console.log(`Retrying (${originalAttempts - attempts} / ${originalAttempts})`);
      } else {
        throw e;
      }
    }
  }
}

async function build() {
  const slnMasks = resolveMasks("BUILD_INCLUDE", ["BUILD_EXCLUDE", "BUILD_ADDITIONAL_EXCLUDE"]);
  debug({
    slnMasks,
    cwd: process.cwd()
  });
  const solutions = gulp
    .src(slnMasks, { allowEmpty: true })
    .pipe(throwIfNoFiles(`No solutions found matching masks: ${ slnMasks }}`));

  // TODO: find a reliable, quick way to determine if the projects to be compiled
  //       are all dotnet core -- trawling *.csproj is slow and has caused hangups
  //       here, so for now, DNC build must be requested via env DONET_CORE
  return env.resolveFlag("DOTNET_CORE")
    ? buildForNetCore(solutions)
    : buildForNETFramework(solutions);
}

function buildForNetCore(solutions) {
  log.info(gutil.colors.yellow("Building with dotnet core"));
  const
    configuration = env.resolve("BUILD_CONFIGURATION"),
    msbuildArgs = [];
  if (!env.resolveFlag("BUILD_MSBUILD_NODE_REUSE")) {
    msbuildArgs.push("/nodeReuse:false")
  }
  return promisifyStream(
    solutions
      .pipe(
        dotnetClean({
          configuration
        })
      )
      .pipe(
        dotnetBuild({
          verbosity: env.resolve("BUILD_VERBOSITY"),
          configuration,
          // msbuild attempts to re-use nodes, which causes issues
          // if you're building unrelated projects on the same machine with,
          // eg, different versions of Microsoft.Net.Compilers
          msbuildArgs,
          echo: true
        })
      )
  );
}

function buildForNETFramework(solutions) {
  log.info(chalk.yellowBright("Building with MsBuild"));
  return promisifyStream(buildAsStream(solutions));
}

function buildAsStream(solutions) {
  const builder = os.platform() === "win32" ? msbuild : xbuild;
  const config = {
    toolsVersion: env.resolve("BUILD_TOOLSVERSION"),
    targets: env.resolveArray("BUILD_TARGETS"),
    configuration: env.resolve("BUILD_CONFIGURATION"),
    stdout: true,
    verbosity: env.resolve("BUILD_VERBOSITY"),
    errorOnFail: env.resolveFlag("BUILD_FAIL_ON_ERROR"),
    solutionPlatform: env.resolve("BUILD_PLATFORM"),
    // NB: this is the MSBUILD architecture, NOT your desired output architecture
    architecture: env.resolve("BUILD_ARCHITECTURE"),
    nologo: false,
    logCommand: true,
    nodeReuse: env.resolveFlag("BUILD_MSBUILD_NODE_REUSE"),
    maxcpucount: env.resolveNumber("BUILD_MAX_CPU_COUNT")
  };

  if (env.resolveFlag("BUILD_SHOW_INFO")) {
    logConfig(config, {
      toolsVersion: "Tools version",
      targets: "Build targets",
      configuration: "Build configuration",
      stdout: "Log to stdout",
      verbosity: "Build verbosity",
      errorOnFail: "Any error fails the build",
      solutionPlatform: "Build platform",
      architecture: "Build architecture",
      nodeReuse: "Re-use MSBUILD nodes",
      maxcpucount: "Max CPUs to use for build",
    });
  }
  return solutions
    .pipe(builder(config));
}
<commit_msg>:bug: should report retry count properly<commit_after>const
  chalk = require("ansi-colors"),
  os = require("os"),
  env = requireModule("env"),
  gulp = requireModule("gulp"),
  debug = require("debug")("build"),
  promisifyStream = requireModule("promisify"),
  dotnetCli = require("gulp-dotnet-cli"),
  dotnetClean = dotnetCli.clean,
  dotnetBuild = dotnetCli.build,
  throwIfNoFiles = requireModule("throw-if-no-files"),
  xbuild = requireModule("gulp-xbuild"),
  gutil = requireModule("gulp-util"),
  log = requireModule("log"),
  resolveMasks = requireModule("resolve-masks"),
  logConfig = requireModule("log-config"),
  msbuild = require("gulp-msbuild");

gulp.task("prebuild", ["nuget-restore"]);

const myTasks = ["build"],
  myVars = [
    "BUILD_CONFIGURATION",
    "BUILD_PLATFORM",
    "BUILD_ARCHITECTURE",
    "BUILD_TARGETS",
    "BUILD_TOOLSVERSION",
    "BUILD_VERBOSITY",
    "BUILD_MSBUILD_NODE_REUSE",
    "BUILD_MAX_CPU_COUNT",
    "MAX_CONCURRENCY",
    "BUILD_INCLUDE",
    "BUILD_EXCLUDE",
    "BUILD_ADDITIONAL_EXCLUDE",
    "BUILD_SHOW_INFO",
    "BUILD_FAIL_ON_ERROR",
    "BUILD_RETRIES"
  ];
env.associate(myVars, myTasks);

gulp.task(
  "build",
  "Builds Visual Studio solutions in tree",
  ["prebuild"],
  tryBuild
);

gulp.task("quick-build", "Quick build without pre-cursors", tryBuild);

async function tryBuild() {
  let totalAttempts = env.resolveNumber("BUILD_RETRIES") + 1;
  if (totalAttempts < 0) {
    totalAttempts = 1;
  }
  const totalRetries = totalAttempts - 1;

  while (totalAttempts-- > 0) {
    try {
      await build();
    } catch (e) {
      if (totalAttempts > 0) {
        console.error(chalk.red(`Build fails: ${e}`));
        console.log(chalk.green(`Retrying (${totalRetries - totalAttempts} / ${totalRetries })`));
      } else {
        throw e;
      }
    }
  }
}

async function build() {
  const slnMasks = resolveMasks("BUILD_INCLUDE", ["BUILD_EXCLUDE", "BUILD_ADDITIONAL_EXCLUDE"]);
  debug({
    slnMasks,
    cwd: process.cwd()
  });
  const solutions = gulp
    .src(slnMasks, { allowEmpty: true })
    .pipe(throwIfNoFiles(`No solutions found matching masks: ${ slnMasks }}`));

  // TODO: find a reliable, quick way to determine if the projects to be compiled
  //       are all dotnet core -- trawling *.csproj is slow and has caused hangups
  //       here, so for now, DNC build must be requested via env DONET_CORE
  return env.resolveFlag("DOTNET_CORE")
    ? buildForNetCore(solutions)
    : buildForNETFramework(solutions);
}

function buildForNetCore(solutions) {
  log.info(gutil.colors.yellow("Building with dotnet core"));
  const
    configuration = env.resolve("BUILD_CONFIGURATION"),
    msbuildArgs = [];
  if (!env.resolveFlag("BUILD_MSBUILD_NODE_REUSE")) {
    msbuildArgs.push("/nodeReuse:false")
  }
  return promisifyStream(
    solutions
      .pipe(
        dotnetClean({
          configuration
        })
      )
      .pipe(
        dotnetBuild({
          verbosity: env.resolve("BUILD_VERBOSITY"),
          configuration,
          // msbuild attempts to re-use nodes, which causes issues
          // if you're building unrelated projects on the same machine with,
          // eg, different versions of Microsoft.Net.Compilers
          msbuildArgs,
          echo: true
        })
      )
  );
}

function buildForNETFramework(solutions) {
  log.info(chalk.yellowBright("Building with MsBuild"));
  return promisifyStream(buildAsStream(solutions));
}

function buildAsStream(solutions) {
  const builder = os.platform() === "win32" ? msbuild : xbuild;
  const config = {
    toolsVersion: env.resolve("BUILD_TOOLSVERSION"),
    targets: env.resolveArray("BUILD_TARGETS"),
    configuration: env.resolve("BUILD_CONFIGURATION"),
    stdout: true,
    verbosity: env.resolve("BUILD_VERBOSITY"),
    errorOnFail: env.resolveFlag("BUILD_FAIL_ON_ERROR"),
    solutionPlatform: env.resolve("BUILD_PLATFORM"),
    // NB: this is the MSBUILD architecture, NOT your desired output architecture
    architecture: env.resolve("BUILD_ARCHITECTURE"),
    nologo: false,
    logCommand: true,
    nodeReuse: env.resolveFlag("BUILD_MSBUILD_NODE_REUSE"),
    maxcpucount: env.resolveNumber("BUILD_MAX_CPU_COUNT")
  };

  if (env.resolveFlag("BUILD_SHOW_INFO")) {
    logConfig(config, {
      toolsVersion: "Tools version",
      targets: "Build targets",
      configuration: "Build configuration",
      stdout: "Log to stdout",
      verbosity: "Build verbosity",
      errorOnFail: "Any error fails the build",
      solutionPlatform: "Build platform",
      architecture: "Build architecture",
      nodeReuse: "Re-use MSBUILD nodes",
      maxcpucount: "Max CPUs to use for build",
    });
  }
  return solutions
    .pipe(builder(config));
}
<|endoftext|>


<commit_before>module.exports = function (config) {

	config.set({
		basePath: './dist',
		frameworks: [
			'jspm',
			'mocha',
			'sinon',
			'should',
		],
		plugins: [
			'karma-chrome-launcher',
			'karma-firefox-launcher',
			// 'karma-safari-launcher',
			'karma-mocha',
			'karma-sinon',
			'karma-should',
			'karma-jspm',
	    ],
		browsers: [
			'Chrome',
			'ChromeCanary',
			'Firefox',
			// 'Safari',
			'FirefoxEnableWebComponents',
		],
		customLaunchers: {
		    FirefoxEnableWebComponents: {
		        base: 'Firefox',
		        prefs: {
		            'dom.webcomponents.enabled': true
		        }
		    },
			Chrome_travis_ci: {
	          base: 'Chrome',
	          flags: ['--no-sandbox']
		  },
		},
		files: [{
	        pattern: '**/*.js.map',
	        included: false
		}],
		jspm: {

			browser: "jspm.browser.js",
			config: "jspm.config.js",

		    loadFiles: [
				'test/decorators/*spec.js',
				'test/libs/*spec.js',
				'test/helpers/*spec.js',
				'test/imports/*.js',
			],
			serveFiles: [
				// internal libs/files
				'src/bootstrap.js',
				'src/app-decorators.js',
				'src/decorators/*.js',
				'src/libs/*.js',
				'src/helpers/*.js',
				'src/datas/*.js',
				'src/apps/*.js',
				// external libs/files
				'node_modules/core-js/**/*.js',
				'node_modules/handlebars/dist/handlebars.js',
				'node_modules/immutable/dist/immutable.js',
				'node_modules/webcomponents.js/webcomponents-lite.js',
				'node_modules/pouchdb/dist/pouchdb.js',
				'node_modules/bluebird/js/browser/bluebird.js',
				'node_modules/xregexp/src/index.js',
				'node_modules/xregexp/src/**/*.js',
			]
		},
		autoWatch: true,
		singleRun: false,
		port: 9876,
	    colors: true,
	    logLevel: config.LOG_INFO,
	});

	if(process.env.TRAVIS){
        config.browsers = ['Chrome_travis_ci'];
    }

};
<commit_msg>karma.conf.js: add test/mocks/*.js to jspm.loadFiles<commit_after>module.exports = function (config) {

	config.set({
		basePath: './dist',
		frameworks: [
			'jspm',
			'mocha',
			'sinon',
			'should',
		],
		plugins: [
			'karma-chrome-launcher',
			'karma-firefox-launcher',
			// 'karma-safari-launcher',
			'karma-mocha',
			'karma-sinon',
			'karma-should',
			'karma-jspm',
	    ],
		browsers: [
			'Chrome',
			'ChromeCanary',
			'Firefox',
			// 'Safari',
			'FirefoxEnableWebComponents',
		],
		customLaunchers: {
		    FirefoxEnableWebComponents: {
		        base: 'Firefox',
		        prefs: {
		            'dom.webcomponents.enabled': true
		        }
		    },
			Chrome_travis_ci: {
	          base: 'Chrome',
	          flags: ['--no-sandbox']
		  },
		},
		files: [{
	        pattern: '**/*.js.map',
	        included: false
		}],
		jspm: {

			browser: "jspm.browser.js",
			config: "jspm.config.js",

		    loadFiles: [
				'test/decorators/*spec.js',
				'test/libs/*spec.js',
				'test/helpers/*spec.js',
				'test/imports/*.js',
				'test/mocks/*.js',
			],
			serveFiles: [
				// internal libs/files
				'src/bootstrap.js',
				'src/app-decorators.js',
				'src/decorators/*.js',
				'src/libs/*.js',
				'src/helpers/*.js',
				'src/datas/*.js',
				'src/apps/*.js',
				// external libs/files
				'node_modules/core-js/**/*.js',
				'node_modules/handlebars/dist/handlebars.js',
				'node_modules/immutable/dist/immutable.js',
				'node_modules/webcomponents.js/webcomponents-lite.js',
				'node_modules/pouchdb/dist/pouchdb.js',
				'node_modules/bluebird/js/browser/bluebird.js',
				'node_modules/xregexp/src/index.js',
				'node_modules/xregexp/src/**/*.js',
			]
		},
		autoWatch: true,
		singleRun: false,
		port: 9876,
	    colors: true,
	    logLevel: config.LOG_INFO,
	});

	if(process.env.TRAVIS){
        config.browsers = ['Chrome_travis_ci'];
    }

};
<|endoftext|>


<commit_before>module.exports = function(securityHeaderName, db, featuresProcessor, limitationsProcessor) {
  return function(req, res, next) {

    req.security = { authenticated: false };
    if (req.headers[securityHeaderName] === undefined) {
      return next();
    }

    var securityHeaderValue = req.get(securityHeaderName);
    db.Session.find({ where: { token: securityHeaderValue } }).then(function(session) {
      db.User.find({ where: { username: session.username } }).then(function(user) {
        db.Account.find(user.account).then(function(account) {
          var securityUser = {
            username: user.username,
            roles: user.roles,
            features: featuresProcessor.process(user, account),
            limitations: limitationsProcessor.process(account),
            account: user.account
          };
          req.security = { authenticated: true, user: securityUser, session: session };
          next();
        }, next);
      }, next);
    }, next);

  };
};
<commit_msg>fix a small bug on security middleware<commit_after>module.exports = function(securityHeaderName, db, featuresProcessor, limitationsProcessor) {
  return function(req, res, next) {

    req.security = { authenticated: false };
    if (req.headers[securityHeaderName] === undefined) {
      return next();
    }

    var securityHeaderValue = req.get(securityHeaderName);
    db.Session.find({ where: { token: securityHeaderValue } }).then(function(session) {
      if (null === session) {
        return next();
      }
      db.User.find({ where: { username: session.username } }).then(function(user) {
        if (null === user) {
          return next();
        }
        db.Account.find(user.account).then(function(account) {
          var securityUser = {
            username: user.username,
            roles: user.roles,
            features: featuresProcessor.process(user, account),
            limitations: limitationsProcessor.process(account),
            account: user.account
          };
          req.security = { authenticated: true, user: securityUser, session: session };
          next();
        }, next);
      }, next);
    }, next);
  };
};
<|endoftext|>


<commit_before>// Copyright 2014 Tjatse
// https://github.com/Tjatse/req-fast
//
// 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.

"use strict";

var Stream = require("stream").Stream,
  http = require("http"),
  https = require("https"),
  tunnel = require('tunnel'),
  URI = require("URIjs"),
  util = require("util"),
  dns = require('dns'),
  ua = require("random-ua"),
  qs = require('querystring'),
  zlib = require('zlib');

util.inherits(RequestStream, Stream);

module.exports = RequestStream;

/**
 * RequestStream that streams http response.
 * @param {Object} options settings.
 * @return {Stream} RequestStream
 * @api private
 */
function RequestStream(options) {
  if(!(this instanceof RequestStream)){
    return new RequestStream(options);
  }

  Stream.call(this);

  // check options.
  if (typeof options == 'string') {
    options = { uri:options };
  } else if (typeof options != 'object' || (!options.uri && !options.url)) {
    return this.emit('error', new Error('wrong type of options.'))
  }

  // use uri instead of url.
  if (options.url) {
    options.uri = options.url;
    delete options.url;
  }
  this.genOptions(options);

  // use Name Service Cache Daemon
  if (this.options.isIp || !this.options.NSCD || typeof this.options.NSCD.getIp != 'function') {
    return this.next(this.request);
  }

  // read NSCD.
  this.options.NSCD.getIp(this.options.host, function (error, ip) {
    if (!error && ip) {
      this.options.hostname = ip;
      return this.next(this.request);
    }
    // resolve ip4 of domain.
    dns.resolve4(this.options.host, function (error, addresses) {
      if (error) {
        return this.emit('error', error);
      }
      if(typeof this.options.NSCD.setIp == 'function'){
        // save NSCD.
        this.options.NSCD.setIp({
          domain:this.options.host,
          ip:addresses[1]
        }, function (error, ip) {
          // get A record.
          this.options.hostname = ip;
          this.next(this.request);
        }.bind(this));
      }else{
        this.options.hostname = ip;
        this.next(this.request);
      }
    }.bind(this));
  }.bind(this));
};

// begin http request.
RequestStream.prototype.request = function () {
  if(typeof this.redirects == 'undefined'){
    this.redirects = [];
  }
  var req = this.client.request(this.options, function (res) {
    var status = res.statusCode;
    if(!!~[301,302,303].indexOf(status)){
      if(!this.options.disableRedirect && this.redirects.length < this.options.maxRedirects){
        var nextTarget = URI(res.headers.location).absoluteTo(this.options.uri);
        this.redirects.push(nextTarget.valueOf());
        // reset host
        this.options.headers.host = nextTarget.host();
        this.options.path = nextTarget.path() + nextTarget.search();
        this.options.host = nextTarget.hostname();
        this.options.port = nextTarget.port();
        this.options.isIp = nextTarget.is('ip');

        return this.next(this.request);
      }else{
        // just fake it, no more redirects.
        status = 200;
      }
    }
    if(status != 200){
      // error status
      return this.emit('error', new Error('Status code: ' + res.statusCode));
    }

    // on data was received
    function onData(chunk){
      if (chunk && chunk.length > 0) {
        this.emit("data", this.options.encoding ? chunk.toString(this.options.encoding) : chunk);
      }
    }
    // on error was caught
    function onError(error){
      this.emit('error', error);
    }
    // on the end
    function onEnd() {
      this.emit('end');
    }

    this.emit('extra', {
      headers: res.headers,
      redirects: this.redirects,
      statusCode: res.statusCode
    });

    // gzip,deflate encoding
    var encoding;
    if(!this.options.disableGzip && (encoding = res.headers['content-encoding'])){
      encoding = encoding.toLowerCase();
      var method = {'gzip': 'Gunzip', 'deflate': 'InflateRaw'}[encoding];
      if(method){
        var gz = zlib['create' + method]();
        gz.on('data', onData.bind(this));
        gz.on('end', onEnd.bind(this));
        gz.on('error', onError.bind(this));
        return res.pipe(gz);
      }
    }

    // normalize
    res.on('data', onData.bind(this));
    res.on('end', onEnd.bind(this));
    res.on('error', onError.bind(this));
  }.bind(this));

  // timeout.
  if(typeof this.options.timeout == 'number'){
    req.setTimeout(this.options.timeout, req.abort);
  }

  // on error.
  req.on('error', function (error) {
    this.emit('error', error);
  }.bind(this));

  // send data if necessary.
  if(!!~['POST', 'PUT'].indexOf(this.options.method) && this.options._data){
    req.write(this.options._data);
  }
  delete this.options._data;

  // sent.
  req.end();
};

// next i/o event
RequestStream.prototype.next = function(fn){
  var io;
  if (typeof setImmediate != "undefined") {
    io = setImmediate;
  } else {
    io = process.nextTick;
  }
  io(fn.bind(this));
}

// generate options.
RequestStream.prototype.genOptions = function (options) {
  // reset max redirects to three.
  if (!options.disableRedirect && typeof options.maxRedirects != 'number') {
    options.maxRedirects = 3;
  }

  // cookies
  var cookies = options.cookies && Object.keys(options.cookies).map(function(key){
    return key + '=' + options.cookies[key];
  }).join(';');

  // headers' keys with lowercase.
  var headers = {
    'connection':'keep-alive',
    'accept':'text/html,text/javascript,application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'cookie':cookies || ''
  };
  if (options.headers && typeof options.headers == 'object') {
    for (var k in options.headers) {
      headers[k.toLowerCase()] = options.headers[k];
    }
  }
  delete options.cookies;

  // gzip
  if (!options.disableGzip) {
    headers['accept-encoding'] = 'gzip,deflate';
  } else {
    delete headers['accept-encoding'];
  }

  // http 1.0+ no-cache
  headers.pragma = headers.pragma || 'no-cache';
  // http 1.1 no-cache
  headers['cache-control'] = headers['cache-control'] || 'no-cache';

  if (!options.method && options.data && Object.keys(options.data).length > 0) {
    options.method = 'POST';
  }
  options.method && (options.method = options.method.toUpperCase());

  // generate user-agent.
  if(typeof options.agent != 'boolean'){
    options.agent = true;
  }
  if (options.agent) {
    headers['user-agent'] = ua.generate();
  }
  delete options.agent;

  // raw uri.
  var uriEntity = URI(options.uri);
  headers.host = uriEntity.host();

  if (options.data) {
    if(!!~['POST', 'PUT'].indexOf(options.method)){
      options._data = qs.stringify(options.data);
      // TODO: file, multipart/form-data
      headers['content-type'] = (headers['content-type'] || '') + ';' + 'application/x-www-form-urlencoded';
      headers['content-length'] = Buffer.byteLength(options._data, 'utf-8');
    }else{
      var search = qs.stringify(options.data), query;

      uriEntity.search(search + ((query = uriEntity.query()) ? ('&' + query) : ''));
    }
  }

  options.path = uriEntity.path() + uriEntity.search();
  options.host = uriEntity.hostname();
  options.port = uriEntity.port();
  options.isIp = uriEntity.is('ip');

  // http && https
  if (uriEntity.protocol() == 'https') {
    this.client = https;
    !options.port && (options.port = 443);
    // can not use protocol here, complicated with [http.request]'s options.
    options.__protocol = 'https';
  } else {
    this.client = http;
    !options.port && (options.port = 80);
    options.__protocol = 'http';
  }

  // proxy.
  if (options.proxy) {
    if (typeof options.proxy != 'object' || (!options.proxy.host || !options.proxy.port)) {
      // CAUTION: proxy must be an JSON object, and including "host" and "port" field at least.
      //    https://www.npmjs.org/package/tunnel
      delete options.proxy;
    }
  }

  if (options.proxy) {
    options.agent = tunnel[options.__protocol + 'OverHttp']({
      proxy:options.proxy
    });
    delete options.proxy;
  }
  options.headers = headers;

  this.options = options;
};<commit_msg>Typo Bug: Inflate<commit_after>// Copyright 2014 Tjatse
// https://github.com/Tjatse/req-fast
//
// 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.

"use strict";

var Stream = require("stream").Stream,
  http = require("http"),
  https = require("https"),
  tunnel = require('tunnel'),
  URI = require("URIjs"),
  util = require("util"),
  dns = require('dns'),
  ua = require("random-ua"),
  qs = require('querystring'),
  zlib = require('zlib');

util.inherits(RequestStream, Stream);

module.exports = RequestStream;

/**
 * RequestStream that streams http response.
 * @param {Object} options settings.
 * @return {Stream} RequestStream
 * @api private
 */
function RequestStream(options) {
  if(!(this instanceof RequestStream)){
    return new RequestStream(options);
  }

  Stream.call(this);

  // check options.
  if (typeof options == 'string') {
    options = { uri:options };
  } else if (typeof options != 'object' || (!options.uri && !options.url)) {
    return this.emit('error', new Error('wrong type of options.'))
  }

  // use uri instead of url.
  if (options.url) {
    options.uri = options.url;
    delete options.url;
  }
  this.genOptions(options);

  // use Name Service Cache Daemon
  if (this.options.isIp || !this.options.NSCD || typeof this.options.NSCD.getIp != 'function') {
    return this.next(this.request);
  }

  // read NSCD.
  this.options.NSCD.getIp(this.options.host, function (error, ip) {
    if (!error && ip) {
      this.options.hostname = ip;
      return this.next(this.request);
    }
    // resolve ip4 of domain.
    dns.resolve4(this.options.host, function (error, addresses) {
      if (error) {
        return this.emit('error', error);
      }
      if(typeof this.options.NSCD.setIp == 'function'){
        // save NSCD.
        this.options.NSCD.setIp({
          domain:this.options.host,
          ip:addresses[1]
        }, function (error, ip) {
          // get A record.
          this.options.hostname = ip;
          this.next(this.request);
        }.bind(this));
      }else{
        this.options.hostname = ip;
        this.next(this.request);
      }
    }.bind(this));
  }.bind(this));
};

// begin http request.
RequestStream.prototype.request = function () {
  if(typeof this.redirects == 'undefined'){
    this.redirects = [];
  }
  var req = this.client.request(this.options, function (res) {
    var status = res.statusCode;
    if(!!~[301,302,303].indexOf(status)){
      if(!this.options.disableRedirect && this.redirects.length < this.options.maxRedirects){
        var nextTarget = URI(res.headers.location).absoluteTo(this.options.uri);
        this.redirects.push(nextTarget.valueOf());
        // reset host
        this.options.headers.host = nextTarget.host();
        this.options.path = nextTarget.path() + nextTarget.search();
        this.options.host = nextTarget.hostname();
        this.options.port = nextTarget.port();
        this.options.isIp = nextTarget.is('ip');

        return this.next(this.request);
      }else{
        // just fake it, no more redirects.
        status = 200;
      }
    }
    if(status != 200){
      // error status
      return this.emit('error', new Error('Status code: ' + res.statusCode));
    }

    // on data was received
    function onData(chunk){
      if (chunk && chunk.length > 0) {
        this.emit("data", this.options.encoding ? chunk.toString(this.options.encoding) : chunk);
      }
    }
    // on error was caught
    function onError(error){
      this.emit('error', error);
    }
    // on the end
    function onEnd() {
      this.emit('end');
    }

    this.emit('extra', {
      headers: res.headers,
      redirects: this.redirects,
      statusCode: res.statusCode
    });

    // gzip,deflate encoding
    var encoding;
    if(!this.options.disableGzip && (encoding = res.headers['content-encoding'])){
      encoding = encoding.toLowerCase();
      var method = {'gzip': 'Gunzip', 'deflate': 'Inflate'}[encoding];
      if(method){
        var gz = zlib['create' + method]();
        gz.on('data', onData.bind(this));
        gz.on('end', onEnd.bind(this));
        gz.on('error', onError.bind(this));
        return res.pipe(gz);
      }
    }

    // normalize
    res.on('data', onData.bind(this));
    res.on('end', onEnd.bind(this));
    res.on('error', onError.bind(this));
  }.bind(this));

  // timeout.
  if(typeof this.options.timeout == 'number'){
    req.setTimeout(this.options.timeout, req.abort);
  }

  // on error.
  req.on('error', function (error) {
    this.emit('error', error);
  }.bind(this));

  // send data if necessary.
  if(!!~['POST', 'PUT'].indexOf(this.options.method) && this.options._data){
    req.write(this.options._data);
  }
  delete this.options._data;

  // sent.
  req.end();
};

// next i/o event
RequestStream.prototype.next = function(fn){
  var io;
  if (typeof setImmediate != "undefined") {
    io = setImmediate;
  } else {
    io = process.nextTick;
  }
  io(fn.bind(this));
}

// generate options.
RequestStream.prototype.genOptions = function (options) {
  // reset max redirects to three.
  if (!options.disableRedirect && typeof options.maxRedirects != 'number') {
    options.maxRedirects = 3;
  }

  // cookies
  var cookies = options.cookies && Object.keys(options.cookies).map(function(key){
    return key + '=' + options.cookies[key];
  }).join(';');

  // headers' keys with lowercase.
  var headers = {
    'connection':'keep-alive',
    'accept':'text/html,text/javascript,application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'cookie':cookies || ''
  };
  if (options.headers && typeof options.headers == 'object') {
    for (var k in options.headers) {
      headers[k.toLowerCase()] = options.headers[k];
    }
  }
  delete options.cookies;

  // gzip
  if (!options.disableGzip) {
    headers['accept-encoding'] = 'gzip,deflate';
  } else {
    delete headers['accept-encoding'];
  }

  // http 1.0+ no-cache
  headers.pragma = headers.pragma || 'no-cache';
  // http 1.1 no-cache
  headers['cache-control'] = headers['cache-control'] || 'no-cache';

  if (!options.method && options.data && Object.keys(options.data).length > 0) {
    options.method = 'POST';
  }
  options.method && (options.method = options.method.toUpperCase());

  // generate user-agent.
  if(typeof options.agent != 'boolean'){
    options.agent = true;
  }
  if (options.agent) {
    headers['user-agent'] = ua.generate();
  }
  delete options.agent;

  // raw uri.
  var uriEntity = URI(options.uri);
  headers.host = uriEntity.host();

  if (options.data) {
    if(!!~['POST', 'PUT'].indexOf(options.method)){
      options._data = qs.stringify(options.data);
      // TODO: file, multipart/form-data
      headers['content-type'] = (headers['content-type'] || '') + ';' + 'application/x-www-form-urlencoded';
      headers['content-length'] = Buffer.byteLength(options._data, 'utf-8');
    }else{
      var search = qs.stringify(options.data), query;

      uriEntity.search(search + ((query = uriEntity.query()) ? ('&' + query) : ''));
    }
  }

  options.path = uriEntity.path() + uriEntity.search();
  options.host = uriEntity.hostname();
  options.port = uriEntity.port();
  options.isIp = uriEntity.is('ip');

  // http && https
  if (uriEntity.protocol() == 'https') {
    this.client = https;
    !options.port && (options.port = 443);
    // can not use protocol here, complicated with [http.request]'s options.
    options.__protocol = 'https';
  } else {
    this.client = http;
    !options.port && (options.port = 80);
    options.__protocol = 'http';
  }

  // proxy.
  if (options.proxy) {
    if (typeof options.proxy != 'object' || (!options.proxy.host || !options.proxy.port)) {
      // CAUTION: proxy must be an JSON object, and including "host" and "port" field at least.
      //    https://www.npmjs.org/package/tunnel
      delete options.proxy;
    }
  }

  if (options.proxy) {
    options.agent = tunnel[options.__protocol + 'OverHttp']({
      proxy:options.proxy
    });
    delete options.proxy;
  }
  options.headers = headers;

  this.options = options;
};<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var Guacamole = Guacamole || {};

/**
 * An arbitrary event, emitted by a {@link Guacamole.Event.Target}. This object
 * should normally serve as the base class for a different object that is more
 * specific to the event type.
 *
 * @constructor
 * @param {String} type
 *     The unique name of this event type.
 */
Guacamole.Event = function Event(type) {

    /**
     * The unique name of this event type.
     *
     * @type {String}
     */
    this.type = type;

    /**
     * An arbitrary timestamp in milliseconds, indicating this event's
     * position in time relative to other events.
     *
     * @type {Number}
     */
    this.timestamp = new Date().getTime();

    /**
     * Returns the number of milliseconds elapsed since this event was created.
     *
     * @return {Number}
     *     The number of milliseconds elapsed since this event was created.
     */
    this.getAge = function getAge() {
        return new Date().getTime() - this.timestamp;
    };

    /**
     * Requests that the legacy event handler associated with this event be
     * invoked on the given event target. This function will be invoked
     * automatically by implementations of {@link Guacamole.Event.Target}
     * whenever {@link Guacamole.Event.Target#emit emit()} is invoked.
     *

     * Older versions of Guacamole relied on single event handlers with the
     * prefix "on", such as "onmousedown" or "onkeyup". If a Guacamole.Event
     * implementation is replacing the event previously represented by one of
     * these handlers, this function gives the implementation the opportunity
     * to provide backward compatibility with the old handler.
     *

     * Unless overridden, this function does nothing.
     *
     * @param {Guacamole.Event.Target} eventTarget
     *     The {@link Guacamole.Event.Target} that emitted this event.
     */
    this.invokeLegacyHandler = function invokeLegacyHandler(eventTarget) {
        // Do nothing
    };

};

/**
 * A {@link Guacamole.Event} that relates to one or more DOM events. Continued
 * propagation and default behavior of the related DOM events may be prevented
 * with {@link Guacamole.Event.DOMEvent#stopPropagation stopPropagation()} and
 * {@link Guacamole.Event.DOMEvent#preventDefault preventDefault()}
 * respectively.
 *
 * @constructor
 * @augments Guacamole.Event
 *
 * @param {String} type
 *     The unique name of this event type.
 *
 * @param {Event[]} events
 *     The DOM events that are related to this event. Future calls to
 *     {@link Guacamole.Event.DOMEvent#preventDefault preventDefault()} and
 *     {@link Guacamole.Event.DOMEvent#stopPropagation stopPropagation()} will
 *     affect these events.
 */
Guacamole.Event.DOMEvent = function DOMEvent(type, events) {

    Guacamole.Event.call(this, type);

    /**
     * Requests that the default behavior of related DOM events be prevented.
     * Whether this request will be honored by the browser depends on the
     * nature of those events and the timing of the request.
     */
    this.preventDefault = function preventDefault() {
        events.forEach(function applyPreventDefault(event) {
            if (event.preventDefault) event.preventDefault();
            event.returnValue = false;
        });
    };

    /**
     * Stops further propagation of related events through the DOM. Only events
     * that are directly related to this event will be stopped.
     */
    this.stopPropagation = function stopPropagation() {
        events.forEach(function applyStopPropagation(event) {
            event.stopPropagation();
        });
    };

};

/**
 * An object which can dispatch {@link Guacamole.Event} objects. Listeners
 * registered with {@link Guacamole.Event.Target#on on()} will automatically
 * be invoked based on the type of {@link Guacamole.Event} passed to
 * {@link Guacamole.Event.Target#dispatch dispatch()}. It is normally
 * subclasses of Guacamole.Event.Target that will dispatch events, and usages
 * of those subclasses that will catch dispatched events with on().
 *
 * @constructor
 */
Guacamole.Event.Target = function Target() {

    /**
     * A callback function which handles an event dispatched by an event
     * target.
     *
     * @callback Guacamole.Event.Target~listener
     * @param {Guacamole.Event} event
     *     The event that was dispatched.
     *
     * @param {Guacamole.Event.Target} target
     *     The object that dispatched the event.
     */

    /**
     * All listeners (callback functions) registered for each event type passed
     * to {@link Guacamole.Event.Targer#on on()}.
     *
     * @private
     * @type {Object.<String, Guacamole.Event.Target~listener[]>}
     */
    var listeners = {};

    /**
     * Registers a listener for events having the given type, as dictated by
     * the {@link Guacamole.Event#type type} property of {@link Guacamole.Event}
     * provided to {@link Guacamole.Event.Target#dispatch dispatch()}.
     *
     * @param {String} type
     *     The unique name of this event type.
     *
     * @param {Guacamole.Event.Target~listener} listener
     *     The function to invoke when an event having the given type is
     *     dispatched. The {@link Guacamole.Event} object provided to
     *     {@link Guacamole.Event.Target#dispatch dispatch()} will be passed to
     *     this function, along with the dispatching Guacamole.Event.Target.
     */
    this.on = function on(type, listener) {

        var relevantListeners = listeners[type];
        if (!relevantListeners)
            listeners[type] = relevantListeners = [];

        relevantListeners.push(listener);

    };

    /**
     * Dispatches the given event, invoking all event handlers registered with
     * this Guacamole.Event.Target for that event's
     * {@link Guacamole.Event#type type}.
     *
     * @param {Guacamole.Event} event
     *     The event to dispatch.
     */
    this.dispatch = function dispatch(event) {

        // Invoke any relevant legacy handler for the event
        event.invokeLegacyHandler(this);

        // Invoke all registered listeners
        var relevantListeners = listeners[event.type];
        if (relevantListeners) {
            for (var i = 0; i < relevantListeners.length; i++) {
                relevantListeners[i](event, this);
            }
        }

    };

    /**
     * Unregisters a listener that was previously registered with
     * {@link Guacamole.Event.Target#on on()}. If no such listener was
     * registered, this function has no effect. If multiple copies of the same
     * listener were registered, the first listener still registered will be
     * removerd.
     *
     * @param {String} type
     *     The unique name of the event type handled by the listener being
     *     removed.
     *
     * @param {Guacamole.Event.Target~listener} listener
     *     The listener function previously provided to
     *     {@link Guacamole.Event.Target#on on()}.
     *
     * @returns {Boolean}
     *     true if the specified listener was removed, false otherwise.
     */
    this.off = function off(type, listener) {

        var relevantListeners = listeners[type];
        if (!relevantListeners)
            return false;

        for (var i = 0; i < relevantListeners.length; i++) {
            if (relevantListeners[i] === listener) {
                relevantListeners.splice(i, 1);
                return true;
            }
        }

        return false;

    };

};
<commit_msg>GUACAMOLE-1204: Provide convenience functions for updating multiple event handlers.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

var Guacamole = Guacamole || {};

/**
 * An arbitrary event, emitted by a {@link Guacamole.Event.Target}. This object
 * should normally serve as the base class for a different object that is more
 * specific to the event type.
 *
 * @constructor
 * @param {String} type
 *     The unique name of this event type.
 */
Guacamole.Event = function Event(type) {

    /**
     * The unique name of this event type.
     *
     * @type {String}
     */
    this.type = type;

    /**
     * An arbitrary timestamp in milliseconds, indicating this event's
     * position in time relative to other events.
     *
     * @type {Number}
     */
    this.timestamp = new Date().getTime();

    /**
     * Returns the number of milliseconds elapsed since this event was created.
     *
     * @return {Number}
     *     The number of milliseconds elapsed since this event was created.
     */
    this.getAge = function getAge() {
        return new Date().getTime() - this.timestamp;
    };

    /**
     * Requests that the legacy event handler associated with this event be
     * invoked on the given event target. This function will be invoked
     * automatically by implementations of {@link Guacamole.Event.Target}
     * whenever {@link Guacamole.Event.Target#emit emit()} is invoked.
     *

     * Older versions of Guacamole relied on single event handlers with the
     * prefix "on", such as "onmousedown" or "onkeyup". If a Guacamole.Event
     * implementation is replacing the event previously represented by one of
     * these handlers, this function gives the implementation the opportunity
     * to provide backward compatibility with the old handler.
     *

     * Unless overridden, this function does nothing.
     *
     * @param {Guacamole.Event.Target} eventTarget
     *     The {@link Guacamole.Event.Target} that emitted this event.
     */
    this.invokeLegacyHandler = function invokeLegacyHandler(eventTarget) {
        // Do nothing
    };

};

/**
 * A {@link Guacamole.Event} that relates to one or more DOM events. Continued
 * propagation and default behavior of the related DOM events may be prevented
 * with {@link Guacamole.Event.DOMEvent#stopPropagation stopPropagation()} and
 * {@link Guacamole.Event.DOMEvent#preventDefault preventDefault()}
 * respectively.
 *
 * @constructor
 * @augments Guacamole.Event
 *
 * @param {String} type
 *     The unique name of this event type.
 *
 * @param {Event[]} events
 *     The DOM events that are related to this event. Future calls to
 *     {@link Guacamole.Event.DOMEvent#preventDefault preventDefault()} and
 *     {@link Guacamole.Event.DOMEvent#stopPropagation stopPropagation()} will
 *     affect these events.
 */
Guacamole.Event.DOMEvent = function DOMEvent(type, events) {

    Guacamole.Event.call(this, type);

    /**
     * Requests that the default behavior of related DOM events be prevented.
     * Whether this request will be honored by the browser depends on the
     * nature of those events and the timing of the request.
     */
    this.preventDefault = function preventDefault() {
        events.forEach(function applyPreventDefault(event) {
            if (event.preventDefault) event.preventDefault();
            event.returnValue = false;
        });
    };

    /**
     * Stops further propagation of related events through the DOM. Only events
     * that are directly related to this event will be stopped.
     */
    this.stopPropagation = function stopPropagation() {
        events.forEach(function applyStopPropagation(event) {
            event.stopPropagation();
        });
    };

};

/**
 * An object which can dispatch {@link Guacamole.Event} objects. Listeners
 * registered with {@link Guacamole.Event.Target#on on()} will automatically
 * be invoked based on the type of {@link Guacamole.Event} passed to
 * {@link Guacamole.Event.Target#dispatch dispatch()}. It is normally
 * subclasses of Guacamole.Event.Target that will dispatch events, and usages
 * of those subclasses that will catch dispatched events with on().
 *
 * @constructor
 */
Guacamole.Event.Target = function Target() {

    /**
     * A callback function which handles an event dispatched by an event
     * target.
     *
     * @callback Guacamole.Event.Target~listener
     * @param {Guacamole.Event} event
     *     The event that was dispatched.
     *
     * @param {Guacamole.Event.Target} target
     *     The object that dispatched the event.
     */

    /**
     * All listeners (callback functions) registered for each event type passed
     * to {@link Guacamole.Event.Targer#on on()}.
     *
     * @private
     * @type {Object.<String, Guacamole.Event.Target~listener[]>}
     */
    var listeners = {};

    /**
     * Registers a listener for events having the given type, as dictated by
     * the {@link Guacamole.Event#type type} property of {@link Guacamole.Event}
     * provided to {@link Guacamole.Event.Target#dispatch dispatch()}.
     *
     * @param {String} type
     *     The unique name of this event type.
     *
     * @param {Guacamole.Event.Target~listener} listener
     *     The function to invoke when an event having the given type is
     *     dispatched. The {@link Guacamole.Event} object provided to
     *     {@link Guacamole.Event.Target#dispatch dispatch()} will be passed to
     *     this function, along with the dispatching Guacamole.Event.Target.
     */
    this.on = function on(type, listener) {

        var relevantListeners = listeners[type];
        if (!relevantListeners)
            listeners[type] = relevantListeners = [];

        relevantListeners.push(listener);

    };

    /**
     * Registers a listener for events having the given types, as dictated by
     * the {@link Guacamole.Event#type type} property of {@link Guacamole.Event}
     * provided to {@link Guacamole.Event.Target#dispatch dispatch()}.
     *

     * Invoking this function is equivalent to manually invoking
     * {@link Guacamole.Event.Target#on on()} for each of the provided types.
     *
     * @param {String[]} types
     *     The unique names of the event types to associate with the given
     *     listener.
     *
     * @param {Guacamole.Event.Target~listener} listener
     *     The function to invoke when an event having any of the given types
     *     is dispatched. The {@link Guacamole.Event} object provided to
     *     {@link Guacamole.Event.Target#dispatch dispatch()} will be passed to
     *     this function, along with the dispatching Guacamole.Event.Target.
     */
    this.onEach = function onEach(types, listener) {
        types.forEach(function addListener(type) {
            this.on(type, listener);
        }, this);
    };

    /**
     * Dispatches the given event, invoking all event handlers registered with
     * this Guacamole.Event.Target for that event's
     * {@link Guacamole.Event#type type}.
     *
     * @param {Guacamole.Event} event
     *     The event to dispatch.
     */
    this.dispatch = function dispatch(event) {

        // Invoke any relevant legacy handler for the event
        event.invokeLegacyHandler(this);

        // Invoke all registered listeners
        var relevantListeners = listeners[event.type];
        if (relevantListeners) {
            for (var i = 0; i < relevantListeners.length; i++) {
                relevantListeners[i](event, this);
            }
        }

    };

    /**
     * Unregisters a listener that was previously registered with
     * {@link Guacamole.Event.Target#on on()} or
     * {@link Guacamole.Event.Target#onEach onEach()}. If no such listener was
     * registered, this function has no effect. If multiple copies of the same
     * listener were registered, the first listener still registered will be
     * removed.
     *
     * @param {String} type
     *     The unique name of the event type handled by the listener being
     *     removed.
     *
     * @param {Guacamole.Event.Target~listener} listener
     *     The listener function previously provided to
     *     {@link Guacamole.Event.Target#on on()}or
     *     {@link Guacamole.Event.Target#onEach onEach()}.
     *
     * @returns {Boolean}
     *     true if the specified listener was removed, false otherwise.
     */
    this.off = function off(type, listener) {

        var relevantListeners = listeners[type];
        if (!relevantListeners)
            return false;

        for (var i = 0; i < relevantListeners.length; i++) {
            if (relevantListeners[i] === listener) {
                relevantListeners.splice(i, 1);
                return true;
            }
        }

        return false;

    };

    /**
     * Unregisters listeners that were previously registered with
     * {@link Guacamole.Event.Target#on on()} or
     * {@link Guacamole.Event.Target#onEach onEach()}. If no such listeners
     * were registered, this function has no effect. If multiple copies of the
     * same listener were registered for the same event type, the first
     * listener still registered will be removed.
     *

     * Invoking this function is equivalent to manually invoking
     * {@link Guacamole.Event.Target#off off()} for each of the provided types.
     *
     * @param {String[]} types
     *     The unique names of the event types handled by the listeners being
     *     removed.
     *
     * @param {Guacamole.Event.Target~listener} listener
     *     The listener function previously provided to
     *     {@link Guacamole.Event.Target#on on()} or
     *     {@link Guacamole.Event.Target#onEach onEach()}.
     *
     * @returns {Boolean}
     *     true if any of the specified listeners were removed, false
     *     otherwise.
     */
    this.offEach = function offEach(types, listener) {

        var changed = false;

        types.forEach(function removeListener(type) {
            changed |= this.off(type, listener);
        }, this);

        return changed;

    };

};
<|endoftext|>


<commit_before>// Javascript UI for surveyor
jQuery(document).ready(function(){
  // if(jQuery.browser.msie){
  //  // IE has trouble with the change event for form radio/checkbox elements - bind click instead
  //  jQuery("form#survey_form input[type=radio], form#survey_form [type=checkbox]").bind("click", function(){
  //    jQuery(this).parents("form").ajaxSubmit({dataType: 'json', success: successfulSave});
  //  });
  //  // IE fires the change event for all other (not radio/checkbox) elements of the form
  //  jQuery("form#survey_form *").not("input[type=radio], input[type=checkbox]").bind("change", function(){
  //    jQuery(this).parents("form").ajaxSubmit({dataType: 'json', success: successfulSave});
  //  });
  // }else{
  //  // Other browsers just use the change event on the form

  //
  // Uncomment the following to use the jQuery Tools Datepicker (http://jquerytools.org/demos/dateinput/index.html)
  // instead of the default jQuery UI Datepicker (http://jqueryui.com/demos/datepicker/)
  //
  // For a date input, i.e. using dateinput from jQuery tools, the value is not updated
  // before the onChange or change event is fired, so we hang this in before the update is
  // sent to the server and set the correct value from the dateinput object.
  // jQuery('li.date input').change(function(){
  //     if ( $(this).data('dateinput') ) {
  //         var date_obj = $(this).data('dateinput').getValue();
  //         this.value = date_obj.getFullYear() + "-" + (date_obj.getMonth()+1) + "-" +
  //             date_obj.getDate() + " 00:00:00 UTC";
  //     }
  // });
  //
  // $('li input.date').dateinput({
  //     format: 'dd mmm yyyy'
  // });

  // Default Datepicker uses jQuery UI Datepicker
  jQuery("input[type='text'].datetime").datetimepicker({
    showSecond: true,
    showMillisec: false,
    timeFormat: 'hh:mm:ss',
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("li.date input").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("input[type='text'].date").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("input[type='text'].datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("input[type='text'].time").timepicker({});

  jQuery('.surveyor_check_boxes input[type=text]').change(function(){
    var textValue = $(this).val()
    if (textValue.length > 0) {
      $(this).parent().children().has('input[type="checkbox"]')[0].children[0].checked = true;
    }
  });

  jQuery('.surveyor_radio input[type=text]').change(function(){
    var textValue = $(this).val()
    if (textValue.length > 0) {
      $(this).parent().children().has('input[type="radio"]')[0].children[0].checked = true;
    }
  });

  jQuery("form#survey_form input, form#survey_form select, form#survey_form textarea").change(function(){
    var elements = [$('[type="submit"]').parent(), $('[name="' + this.name +'"]').closest('li')];

    question_data = $(this).parents('fieldset[id^="q_"],tr[id^="q_"]').
      find("input, select, textarea").
      add($("form#survey_form input[name='authenticity_token']")).
      serialize();
    $.ajax({
      type: "PUT",
      url: $(this).parents('form#survey_form').attr("action"),
      data: question_data, dataType: 'json',
      success: function(response) {
        successfulSave(response);
      }
    });
  });

  // http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/
  $('fieldset.q_slider select').each(function(i,e) {
    $(e).selectToUISlider({"labelSrc": "text"}).hide()
  });

  // If javascript works, we don't need to show dependents from
  // previous sections at the top of the page.
  jQuery("#dependents").remove();

  function successfulSave(responseText) {
    // surveyor_controller returns a json object to show/hide elements
    // e.g. {"hide":["question_12","question_13"],"show":["question_14"]}
    jQuery.each(responseText.show, function(){ showElement(this) });
    jQuery.each(responseText.hide, function(){ hideElement(this) });
    return false;
  }

  function showElement(id){
    group = id.match('^g_') ? true : false;
    if (group) {
      jQuery('#' + id).removeClass("g_hidden");
    } else {
      jQuery('#' + id).removeClass("q_hidden");
    }
  }

  function hideElement(id){
    group = id.match('^g_') ? true : false;
    if (group) {
      jQuery('#' + id).addClass("g_hidden");
    } else {
      jQuery('#' + id).addClass("q_hidden");
    }
  }

  // is_exclusive checkboxes should disble sibling checkboxes
  $('input.exclusive:checked').parents('fieldset[id^="q_"]').
    find(':checkbox').
    not(".exclusive").
    attr('checked', false).
    attr('disabled', true);

  $('input.exclusive:checkbox').click(function(){
    var e = $(this);
    var others = e.parents('fieldset[id^="q_"]').find(':checkbox').not(e);
    if(e.is(':checked')){
      others.attr('checked', false).attr('disabled', 'disabled');
    }else{
      others.attr('disabled', false);
    }
  });

  jQuery("input[data-input_mask]").each(function(i,e){
    var inputMask = $(e).attr('data-input_mask');
    var placeholder = $(e).attr('data-placeholder');
    var options = {};
    if (placeholder) {
      options = {placeholder: placeholder}
    }
    $(e).mask(inputMask, options);
  });

});
<commit_msg>Simplify. #415<commit_after>// Javascript UI for surveyor
jQuery(document).ready(function(){
  // if(jQuery.browser.msie){
  //  // IE has trouble with the change event for form radio/checkbox elements - bind click instead
  //  jQuery("form#survey_form input[type=radio], form#survey_form [type=checkbox]").bind("click", function(){
  //    jQuery(this).parents("form").ajaxSubmit({dataType: 'json', success: successfulSave});
  //  });
  //  // IE fires the change event for all other (not radio/checkbox) elements of the form
  //  jQuery("form#survey_form *").not("input[type=radio], input[type=checkbox]").bind("change", function(){
  //    jQuery(this).parents("form").ajaxSubmit({dataType: 'json', success: successfulSave});
  //  });
  // }else{
  //  // Other browsers just use the change event on the form

  //
  // Uncomment the following to use the jQuery Tools Datepicker (http://jquerytools.org/demos/dateinput/index.html)
  // instead of the default jQuery UI Datepicker (http://jqueryui.com/demos/datepicker/)
  //
  // For a date input, i.e. using dateinput from jQuery tools, the value is not updated
  // before the onChange or change event is fired, so we hang this in before the update is
  // sent to the server and set the correct value from the dateinput object.
  // jQuery('li.date input').change(function(){
  //     if ( $(this).data('dateinput') ) {
  //         var date_obj = $(this).data('dateinput').getValue();
  //         this.value = date_obj.getFullYear() + "-" + (date_obj.getMonth()+1) + "-" +
  //             date_obj.getDate() + " 00:00:00 UTC";
  //     }
  // });
  //
  // $('li input.date').dateinput({
  //     format: 'dd mmm yyyy'
  // });

  // Default Datepicker uses jQuery UI Datepicker
  jQuery("input[type='text'].datetime").datetimepicker({
    showSecond: true,
    showMillisec: false,
    timeFormat: 'hh:mm:ss',
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("li.date input").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("input[type='text'].date").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("input[type='text'].datepicker").datepicker({
    dateFormat: 'yy-mm-dd',
    changeMonth: true,
    changeYear: true
  });
  jQuery("input[type='text'].time").timepicker({});

  jQuery('.surveyor_check_boxes input[type=text]').change(function(){
    var textValue = $(this).val()
    if (textValue.length > 0) {
      $(this).parent().children().has('input[type="checkbox"]')[0].children[0].checked = true;
    }
  });

  jQuery('.surveyor_radio input[type=text]').change(function(){
    var textValue = $(this).val()
    if (textValue.length > 0) {
      $(this).parent().children().has('input[type="radio"]')[0].children[0].checked = true;
    }
  });

  jQuery("form#survey_form input, form#survey_form select, form#survey_form textarea").change(function(){
    var elements = [$('[type="submit"]').parent(), $('[name="' + this.name +'"]').closest('li')];

    question_data = $(this).parents('fieldset[id^="q_"],tr[id^="q_"]').
      find("input, select, textarea").
      add($("form#survey_form input[name='authenticity_token']")).
      serialize();
    $.ajax({
      type: "PUT",
      url: $(this).parents('form#survey_form').attr("action"),
      data: question_data, dataType: 'json',
      success: function(response) {
        successfulSave(response);
      }
    });
  });

  // http://www.filamentgroup.com/lab/update_jquery_ui_slider_from_a_select_element_now_with_aria_support/
  $('fieldset.q_slider select').each(function(i,e) {
    $(e).selectToUISlider({"labelSrc": "text"}).hide()
  });

  // If javascript works, we don't need to show dependents from
  // previous sections at the top of the page.
  jQuery("#dependents").remove();

  function successfulSave(responseText) {
    // surveyor_controller returns a json object to show/hide elements
    // e.g. {"hide":["question_12","question_13"],"show":["question_14"]}
    jQuery.each(responseText.show, function(){ showElement(this) });
    jQuery.each(responseText.hide, function(){ hideElement(this) });
    return false;
  }

  function showElement(id){
    group = id.match('^g_') ? true : false;
    if (group) {
      jQuery('#' + id).removeClass("g_hidden");
    } else {
      jQuery('#' + id).removeClass("q_hidden");
    }
  }

  function hideElement(id){
    group = id.match('^g_') ? true : false;
    if (group) {
      jQuery('#' + id).addClass("g_hidden");
    } else {
      jQuery('#' + id).addClass("q_hidden");
    }
  }

  // is_exclusive checkboxes should disble sibling checkboxes
  $('input.exclusive:checked').parents('fieldset[id^="q_"]').
    find(':checkbox').
    not(".exclusive").
    attr('checked', false).
    attr('disabled', true);

  $('input.exclusive:checkbox').click(function(){
    var e = $(this);
    var others = e.parents('fieldset[id^="q_"]').find(':checkbox').not(e);
    if(e.is(':checked')){
      others.attr('checked', false).attr('disabled', 'disabled');
    }else{
      others.attr('disabled', false);
    }
  });

  jQuery("input[data-input_mask]").each(function(i,e){
    var inputMask = $(e).attr('data-input_mask');
    var placeholder = $(e).attr('data-placeholder');
    var options = { placeholder: placeholder };
    $(e).mask(inputMask, options);
  });

});
<|endoftext|>


<commit_before>/**
 * RequireJS build configuration.
 */
({

  baseUrl:                 'app',
  dir:                     'dist',
  optimize:                'uglify2',
  findNestedDependencies:  true,
  removeCombined:          true,
  preserveLicenseComments: false,
  generateSourceMaps:      true,
  keepBuildDir:            true,
  wrapShim:                true,

  // Exclude non-JS files.
  // TODO: In the future, consider moving all JS sources to a common directory.
  fileExclusionRegExp: /^\.|^README$|\.(map|css|less|sass|scss|jpg|jpeg|png|gif|ico|dust|svg|ttf|otf|eot|woff)$/i,

  paths: {
    'jquery':               '../lib/jquery',
    'jqueryui':             '../lib/jquery-ui',
    'underscore':           '../lib/lodash.compat',
    'backbone':             '../lib/backbone',
    'backbone.wreqr':       '../lib/backbone.wreqr',
    'backbone.babysitter':  '../lib/backbone.babysitter',
    'marionette':           '../lib/backbone.marionette',
    'dust':                 '../lib/dust-full.min',
    'dust.helpers':         '../lib/dust-helpers.min',
    'dust.marionette':      '../lib/backbone.marionette.dust',
    'backbone.validateAll': '../lib/Backbone.validateAll.min',
    'bootstrap':            '../lib/bootstrap',
    'bootstrap.notify':     '../lib/bootstrap-notify',
    'text':                 '../lib/text',
    'moment':               '../lib/moment',
    'i18n':                 '../lib/i18n',
    'templates':            'templates-compiled'
  },

  shim: {
      'jqueryui':             ['jquery'],
      'bootstrap':            ['jquery'],
      'backbone':             ['underscore'],
      'marionette':           ['underscore', 'backbone', 'jquery'],
      'dust.helpers':         ['dust'],
      'dust.marionette':      ['marionette', 'dust'],
      'backbone.validateAll': ['backbone'],
      'bootstrap.notify':     ['bootstrap'],
      'templates':            ['dust'],
      'dust':                 {'exports': 'dust'}
  },

  modules: [
    {
      name: 'main'/*,
      exclude: [
        'infrastructure'
      ]
    },
    {
      name: 'infrastructure'*/
    }
  ]
})
<commit_msg>Split infrastructure modules<commit_after>/**
 * RequireJS build configuration.
 */
({

  baseUrl:                 'app',
  dir:                     'dist',
  optimize:                'uglify2',
  findNestedDependencies:  true,
  removeCombined:          true,
  preserveLicenseComments: false,
  generateSourceMaps:      true,
  keepBuildDir:            true,
  wrapShim:                true,

  // Exclude non-JS files.
  // TODO: In the future, consider moving all JS sources to a common directory.
  fileExclusionRegExp: /^\.|^README$|\.(map|css|less|sass|scss|jpg|jpeg|png|gif|ico|dust|svg|ttf|otf|eot|woff)$/i,

  paths: {
    'jquery':               '../lib/jquery',
    'jqueryui':             '../lib/jquery-ui',
    'underscore':           '../lib/lodash.compat',
    'backbone':             '../lib/backbone',
    'backbone.wreqr':       '../lib/backbone.wreqr',
    'backbone.babysitter':  '../lib/backbone.babysitter',
    'marionette':           '../lib/backbone.marionette',
    'dust':                 '../lib/dust-full.min',
    'dust.helpers':         '../lib/dust-helpers.min',
    'dust.marionette':      '../lib/backbone.marionette.dust',
    'backbone.validateAll': '../lib/Backbone.validateAll.min',
    'bootstrap':            '../lib/bootstrap',
    'bootstrap.notify':     '../lib/bootstrap-notify',
    'text':                 '../lib/text',
    'moment':               '../lib/moment',
    'i18n':                 '../lib/i18n',
    'templates':            'templates-compiled'
  },

  shim: {
      'jqueryui':             ['jquery'],
      'bootstrap':            ['jquery'],
      'backbone':             ['underscore'],
      'marionette':           ['underscore', 'backbone', 'jquery'],
      'dust.helpers':         ['dust'],
      'dust.marionette':      ['marionette', 'dust'],
      'backbone.validateAll': ['backbone'],
      'bootstrap.notify':     ['bootstrap'],
      'templates':            ['dust'],
      'dust':                 {'exports': 'dust'}
  },

  modules: [
    {
      name: 'main',
      exclude: [
        'infrastructure'
      ]
    },
    {
      name: 'infrastructure'
    }
  ]
})
<|endoftext|>