<commit_before>/*jslint sloppy: true, forin: true*/
/*global define*/

/**
 * Classify - Sugar syntax for Prototypal Inheritance
 *
 * @author Luís Couto <lcouto87@gmail.com>
 * @author André Cruz <andremiguelcruz@msn.com>
 * @version 1.0.0
 *
 * @example
 *
 *      var MyClass = Classify({
 *          Implements: [SomeInterface, OtherInterface],
 *          Extends: ParentClass,
 *          Borrows: [SomeMixin, OtherMixin],
 *          Binds: ['method1', 'method2'],
 *          Statics: {
 *              staticMethod1: function () {},
 *              staticMethod2: function () {},
 *              staticMethod3: function () {},
 *          },
 *          initialize: function () {
 *              MyClass.Super.initialize.call(this);
 *          },
 *          method1: function () {},
 *          method2: function () {},
 *          method3: function () {}
 *      });
 */
define('Trinity/Classify', [
    //>>includeStart('checks', pragmas.checks);
    'Utils/lang/isFunction',
    'Utils/lang/isString',
    'Utils/array/intersection',
    'Utils/array/unique',
    //>>includeEnd('checks');
    'Utils/lang/isObject',
    'Utils/lang/isArray',
    'Utils/lang/isUndefined',
    'Utils/lang/createObject',
    'Utils/object/mixIn',
    'Utils/object/keys',
    'Utils/array/forEach',
    'Utils/lang/bind',
    'Utils/lang/toArray',
    'Classify.Abstract',
    'Classify.Interface'
], function (
    //>>includeStart('checks', pragmas.checks);
    isFunction,
    isString,
    intersection,
    unique,
    //>>includeEnd('checks');
    isObject,
    isArray,
    isUndefined,
    createObject,
    mixIn,
    keys,
    forEach,
    bind,
    toArray,
    Abstract,
    Interface
) {

    /**
     * Create a class definition.
     *
     * @param {Object} params An object containing methods and properties
     *
     * @returns {Function} The constructor
     */
    function Classify(params) {

        //>>includeStart('checks', pragmas.checks);
        if (!isObject(params)) {
            throw new TypeError('Argument "params" must be an object.');
        }

        params.Name = params.Name || 'Unnamed';

        if (params.Abstracts && !params.$abstract) {
            throw new Error('Class "' + params.Name + '" has abstract methods, therefore it must be defined as abstract.');
        }
        //>>includeEnd('checks');

        //>>excludeStart('checks', pragmas.checks);
        delete params.Name;
        //>>excludeEnd('checks');

        var classify,
            parent;

        /**
         * Borrows the properties and methods of various source objects to the target.
         *
         * @param {Array}  sources Array of objects that will give their methods
         * @param {Object} target  Target that will receive the methods
         */
        function borrows(sources, target) {

            sources = toArray(sources);

            var i, length = sources.length,
                current,
                key;

            for (i = 0; i < length; i += 1) {

                current = sources[i];

                //>>includeStart('checks', pragmas.checks);
                if ((!isFunction(current) || !current.$class) && !isObject(current)) {
                    throw new TypeError('Entry at index ' + i + ' in Borrows of class "' + target.prototype.Name + '" is not a valid class/object.');
                }
                //>>includeEnd('checks');

                // Do the mixin manually because we need to ignore already defined methods
                current = isObject(current) ? current : current.prototype;

                for (key in current) {
                    if (isUndefined(target.prototype[key])) {    // Besides ignoring already defined, also reserved words like $constructor are also preserved
                        target.prototype[key] = current[key];
                    }
                }
            }
        }

        /**
         * Fixes the context in given methods.
         *
         * @param {Array}  fns     The array of functions to be bound
         * @param {Object} context The context that will be bound
         * @param {Object} target  The target class that will have these methods
         */
        function binds(fns, context, target) {

            var i = fns.length - 1;

            for (i; i >= 0; i -= 1) {    // We don't use forEach here due to performance
                target[fns[i]] = bind(target[fns[i]], context);
            }
        }

        //>>includeStart('checks', pragmas.checks);
        /**
         * Checks a target against interfaces methods.
         *
         * @param {Array}  interfaces The array of interfaces
         * @param {Object} target     The target that will be check
         */
        function checkInterfaces(interfaces, target) {

            interfaces = toArray(interfaces);

            var checkStatic = function (value) {
                    if (!isFunction(target[value])) {
                        throw new Error('Class "' + target.prototype.Name + '" does not implement interface "' + this.prototype.Name + '" correctly, static method "' + value + '()" was not found.');
                    }
                };

            forEach(interfaces, function (curr, i) {

                var k;

                if (!isFunction(curr) || !curr.$interface) {
                    throw new TypeError('Entry at index ' + i + ' in Implements of class "' + params.Name + '" is not a valid interface.');
                }

                // Check normal functions
                for (k in curr.prototype) {
                    if (isFunction(curr.prototype[k]) && !isFunction(target.prototype[k])) {
                        throw new Error('Class "' + target.prototype.Name + '" does not implement interface "' + curr.prototype.Name + '" correctly, method "' + k + '()" was not found.');
                    }
                }

                // Check static functions
                if (curr.$statics) {
                    forEach(curr.$statics, checkStatic, curr);
                }
            });
        }

        /**
         * Checks a target against an abstract class.
         *
         * @param {Function} abstractClass The abstract class
         * @param {Object}   target        The target that will be check
         */
        function checkAbstract(abstractClass, target) {

            var abstracts = abstractClass.$abstract;

            forEach(abstracts.normal, function (func) {
                if (!isFunction(target.prototype[func])) {
                    throw new Error('Class "' + target.prototype.Name + '" does not implement abstract class "' + abstractClass.prototype.Name + '" correctly, method "' + func + '()" was not found.');
                }
            });

            forEach(abstracts.statics, function (func) {
                if (!isFunction(target[func])) {
                    throw new Error('Class "' + target.prototype.Name + '" does not implement abstract class "' + abstractClass.prototype.Name + '" correctly, static method "' + func + '()" was not found.');
                }
            });
        }
        //>>includeEnd('checks');

        /**
         * Grab all the bound from the constructor parent and itself and merges them for later use.
         *
         * @param {Function} constructor The constructor
         */
        function grabBinds(constructor) {

            var parent = constructor.Super ? constructor.Super.$constructor : null,
                prototype = constructor.prototype;

            //>>includeStart('checks', pragmas.checks);
            if ((prototype.Binds || []).length !== unique(prototype.Binds || []).length) {
                throw new Error('There are duplicate binds in "' + prototype.Name + '".');
            }
            //>>includeEnd('checks');

            if (parent && parent.$binds) {

                //>>includeStart('checks', pragmas.checks);
                if (intersection(prototype.Binds || [], parent.$binds).length > 0) {
                    throw new Error('There are binds in "' + prototype.Name + '" that are already being bound in the parent class.');
                }
                //>>includeEnd('checks');

                constructor.$binds = (prototype.Binds || []).concat(parent.$binds);
            } else if (params.Binds) {
                constructor.$binds = prototype.Binds;
            }

            //>>includeStart('checks', pragmas.checks);
            if (constructor.$binds) {

                forEach(constructor.$binds, function (value) {

                    if (!isString(value)) {
                        throw new TypeError('All bind entries of "' + prototype.Name + '" must be a string.');
                    }

                    if (!isFunction(prototype[value])) {
                        throw new Error('Method "' + value + '()" referenced in "' + prototype.Name + '" binds does not exist.');
                    }
                });
            }
            //>>includeEnd('checks');

            delete prototype.Binds;
        }

        /**
         * Grabs the static methods from the constructor parent and itself and merges them.
         *
         * @param {Function} constructor The constructor
         */
        function grabStatics(constructor) {

            var parent = constructor.Super ? constructor.Super.$constructor : null;

            // TODO: Shall we improve this function due to performance?
            if (constructor.prototype.Statics) {

                //>>includeStart('checks', pragmas.checks);
                if (!isObject(constructor.prototype.Statics)) {
                    throw new TypeError('Statics definition for "' + params.Name + '" must be an object.');
                }
                //>>includeEnd('checks');

                mixIn(constructor, constructor.prototype.Statics);
                constructor.$statics = keys(constructor.prototype.Statics);
            }

            if (parent && parent.$statics) {

                if (!constructor.$statics) {
                    constructor.$statics = [];
                }

                forEach(parent.$statics, function (value) {
                    if (isUndefined(constructor[value])) {    // Besides ignoring already defined, also reserved words like $abstract are also preserved
                        constructor[value] = parent[value];
                        constructor.$statics.push(value);
                    }
                });
            }
        }

        /**
         * Reset some properties in order to make them unique for the instance.
         * This solves the shared properties for types like objects or arrays.
         *
         * @param {Object} object The instance
         */
        function reset(object) {

            var key;

            for (key in object) {
                if (isArray(object[key])) {    // If is array, clone it
                    object[key] = [].concat(object[key]);
                } else if (isObject(object[key])) {    // If is an object, clone it
                    object[key] = mixIn({}, object[key]);
                }
            }
        }

        /**
         * Builds the constructor function that calls the initialize and do
         * more things internally.
         *
         * @param {Funciton} initialize The initialize function
         *
         * @return {Function} The constructor function
         */
        function constructor(initialize) {

            return function initializer() {

                // Reset some types of the object in order for each instance to have their variables
                reset(this);

                // Apply binds
                if (this.$constructor.$binds) {
                    binds(this.$constructor.$binds, this, this);
                }

                //>>includeStart('checks', pragmas.checks);
                // Call initialize
                if (!this.$constructor.$abstract) {
                    this.$initializing = true;
                }
                //>>includeEnd('checks');
                initialize.apply(this, arguments);
                //>>includeStart('checks', pragmas.checks);
                delete this.$initializing;
                //>>includeEnd('checks');
            };
        }

        if (params.Extends) {

            //>>includeStart('checks', pragmas.checks);
            if (!isFunction(params.Extends) || !params.Extends.$class) {
                throw new TypeError('Specified parent class in Extends of "' + params.Name + '" is not a valid class.');
            }
            //>>includeEnd('checks');

            parent = params.Extends;
            delete params.Extends;

            params.initialize = params.initialize || function () { parent.prototype.initialize.apply(this, arguments); };
            classify = constructor(params.initialize);
            classify.Super = parent.prototype;
            classify.prototype = createObject(parent.prototype, params);
        } else {
            params.initialize = params.initialize || function () {};
            classify = constructor(params.initialize);
            classify.prototype = params;
        }

        classify.prototype.$constructor = classify;
        //>>includeStart('checks', pragmas.checks);
        classify.$class = true;
        //>>includeEnd('checks');

        // Grab all the defined mixins
        if (params.Borrows) {
            borrows(params.Borrows, classify);
            delete classify.prototype.Borrows;
        }

        // Grab all the defined binds
        if (params.Binds) {
            grabBinds(classify);
            delete classify.prototype.Binds;
        }

        // Grab static methods from the parent and itself
        grabStatics(classify);
        //>>excludeStart('checks', pragmas.checks);
        if (params.Statics) {
            delete classify.prototype.Statics;  // If we got checks enabled, we can't delete the Statics yet (see bellow)
        }
        //>>excludeEnd('checks');

        //>>includeStart('checks', pragmas.checks);
        // If we are a concrete class that extends an abstract class, we need to verify the methods existence
        if (parent && parent.$abstract && !params.$abstract) {
            checkAbstract(parent, classify);
        }
        //>>includeEnd('checks');

        // If the class implement some interfaces and is not abstract then
        if (params.Implements) {

            //>>includeStart('checks', pragmas.checks);
            if (!params.$abstract) {
                checkInterfaces(params.Implements, classify);
            }
            //>>includeEnd('checks');

            delete classify.prototype.Implements;
        }

        //>>includeStart('checks', pragmas.checks);
        if (params.Statics) {
            delete classify.prototype.Statics;  // Delete statics now
        }
        //>>includeEnd('checks');

        return classify;
    }

    Classify.Abstract = Abstract;
    Classify.Interface = Interface;

    return Classify;
});
<commit_msg>Fix comment typo.<commit_after>/*jslint sloppy: true, forin: true*/
/*global define*/

/**
 * Classify - Sugar syntax for Prototypal Inheritance
 *
 * @author Luís Couto <lcouto87@gmail.com>
 * @author André Cruz <andremiguelcruz@msn.com>
 * @version 1.0.0
 *
 * @example
 *
 *      var MyClass = Classify({
 *          Implements: [SomeInterface, OtherInterface],
 *          Extends: ParentClass,
 *          Borrows: [SomeMixin, OtherMixin],
 *          Binds: ['method1', 'method2'],
 *          Statics: {
 *              staticMethod1: function () {},
 *              staticMethod2: function () {},
 *              staticMethod3: function () {},
 *          },
 *          initialize: function () {
 *              MyClass.Super.initialize.call(this);
 *          },
 *          method1: function () {},
 *          method2: function () {},
 *          method3: function () {}
 *      });
 */
define('Trinity/Classify', [
    //>>includeStart('checks', pragmas.checks);
    'Utils/lang/isFunction',
    'Utils/lang/isString',
    'Utils/array/intersection',
    'Utils/array/unique',
    //>>includeEnd('checks');
    'Utils/lang/isObject',
    'Utils/lang/isArray',
    'Utils/lang/isUndefined',
    'Utils/lang/createObject',
    'Utils/object/mixIn',
    'Utils/object/keys',
    'Utils/array/forEach',
    'Utils/lang/bind',
    'Utils/lang/toArray',
    'Classify.Abstract',
    'Classify.Interface'
], function (
    //>>includeStart('checks', pragmas.checks);
    isFunction,
    isString,
    intersection,
    unique,
    //>>includeEnd('checks');
    isObject,
    isArray,
    isUndefined,
    createObject,
    mixIn,
    keys,
    forEach,
    bind,
    toArray,
    Abstract,
    Interface
) {

    /**
     * Create a class definition.
     *
     * @param {Object} params An object containing methods and properties
     *
     * @returns {Function} The constructor
     */
    function Classify(params) {

        //>>includeStart('checks', pragmas.checks);
        if (!isObject(params)) {
            throw new TypeError('Argument "params" must be an object.');
        }

        params.Name = params.Name || 'Unnamed';

        if (params.Abstracts && !params.$abstract) {
            throw new Error('Class "' + params.Name + '" has abstract methods, therefore it must be defined as abstract.');
        }
        //>>includeEnd('checks');

        //>>excludeStart('checks', pragmas.checks);
        delete params.Name;
        //>>excludeEnd('checks');

        var classify,
            parent;

        /**
         * Borrows the properties and methods of various source objects to the target.
         *
         * @param {Array}  sources Array of objects that will give their methods
         * @param {Object} target  Target that will receive the methods
         */
        function borrows(sources, target) {

            sources = toArray(sources);

            var i, length = sources.length,
                current,
                key;

            for (i = 0; i < length; i += 1) {

                current = sources[i];

                //>>includeStart('checks', pragmas.checks);
                if ((!isFunction(current) || !current.$class) && !isObject(current)) {
                    throw new TypeError('Entry at index ' + i + ' in Borrows of class "' + target.prototype.Name + '" is not a valid class/object.');
                }
                //>>includeEnd('checks');

                // Do the mixin manually because we need to ignore already defined methods
                current = isObject(current) ? current : current.prototype;

                for (key in current) {
                    if (isUndefined(target.prototype[key])) {    // Besides ignoring already defined members, reserved words like $constructor are also preserved
                        target.prototype[key] = current[key];
                    }
                }
            }
        }

        /**
         * Fixes the context in given methods.
         *
         * @param {Array}  fns     The array of functions to be bound
         * @param {Object} context The context that will be bound
         * @param {Object} target  The target class that will have these methods
         */
        function binds(fns, context, target) {

            var i = fns.length - 1;

            for (i; i >= 0; i -= 1) {    // We don't use forEach here due to performance
                target[fns[i]] = bind(target[fns[i]], context);
            }
        }

        //>>includeStart('checks', pragmas.checks);
        /**
         * Checks a target against interfaces methods.
         *
         * @param {Array}  interfaces The array of interfaces
         * @param {Object} target     The target that will be check
         */
        function checkInterfaces(interfaces, target) {

            interfaces = toArray(interfaces);

            var checkStatic = function (value) {
                    if (!isFunction(target[value])) {
                        throw new Error('Class "' + target.prototype.Name + '" does not implement interface "' + this.prototype.Name + '" correctly, static method "' + value + '()" was not found.');
                    }
                };

            forEach(interfaces, function (curr, i) {

                var k;

                if (!isFunction(curr) || !curr.$interface) {
                    throw new TypeError('Entry at index ' + i + ' in Implements of class "' + params.Name + '" is not a valid interface.');
                }

                // Check normal functions
                for (k in curr.prototype) {
                    if (isFunction(curr.prototype[k]) && !isFunction(target.prototype[k])) {
                        throw new Error('Class "' + target.prototype.Name + '" does not implement interface "' + curr.prototype.Name + '" correctly, method "' + k + '()" was not found.');
                    }
                }

                // Check static functions
                if (curr.$statics) {
                    forEach(curr.$statics, checkStatic, curr);
                }
            });
        }

        /**
         * Checks a target against an abstract class.
         *
         * @param {Function} abstractClass The abstract class
         * @param {Object}   target        The target that will be check
         */
        function checkAbstract(abstractClass, target) {

            var abstracts = abstractClass.$abstract;

            forEach(abstracts.normal, function (func) {
                if (!isFunction(target.prototype[func])) {
                    throw new Error('Class "' + target.prototype.Name + '" does not implement abstract class "' + abstractClass.prototype.Name + '" correctly, method "' + func + '()" was not found.');
                }
            });

            forEach(abstracts.statics, function (func) {
                if (!isFunction(target[func])) {
                    throw new Error('Class "' + target.prototype.Name + '" does not implement abstract class "' + abstractClass.prototype.Name + '" correctly, static method "' + func + '()" was not found.');
                }
            });
        }
        //>>includeEnd('checks');

        /**
         * Grab all the bound from the constructor parent and itself and merges them for later use.
         *
         * @param {Function} constructor The constructor
         */
        function grabBinds(constructor) {

            var parent = constructor.Super ? constructor.Super.$constructor : null,
                prototype = constructor.prototype;

            //>>includeStart('checks', pragmas.checks);
            if ((prototype.Binds || []).length !== unique(prototype.Binds || []).length) {
                throw new Error('There are duplicate binds in "' + prototype.Name + '".');
            }
            //>>includeEnd('checks');

            if (parent && parent.$binds) {

                //>>includeStart('checks', pragmas.checks);
                if (intersection(prototype.Binds || [], parent.$binds).length > 0) {
                    throw new Error('There are binds in "' + prototype.Name + '" that are already being bound in the parent class.');
                }
                //>>includeEnd('checks');

                constructor.$binds = (prototype.Binds || []).concat(parent.$binds);
            } else if (params.Binds) {
                constructor.$binds = prototype.Binds;
            }

            //>>includeStart('checks', pragmas.checks);
            if (constructor.$binds) {

                forEach(constructor.$binds, function (value) {

                    if (!isString(value)) {
                        throw new TypeError('All bind entries of "' + prototype.Name + '" must be a string.');
                    }

                    if (!isFunction(prototype[value])) {
                        throw new Error('Method "' + value + '()" referenced in "' + prototype.Name + '" binds does not exist.');
                    }
                });
            }
            //>>includeEnd('checks');

            delete prototype.Binds;
        }

        /**
         * Grabs the static methods from the constructor parent and itself and merges them.
         *
         * @param {Function} constructor The constructor
         */
        function grabStatics(constructor) {

            var parent = constructor.Super ? constructor.Super.$constructor : null;

            // TODO: Shall we improve this function due to performance?
            if (constructor.prototype.Statics) {

                //>>includeStart('checks', pragmas.checks);
                if (!isObject(constructor.prototype.Statics)) {
                    throw new TypeError('Statics definition for "' + params.Name + '" must be an object.');
                }
                //>>includeEnd('checks');

                mixIn(constructor, constructor.prototype.Statics);
                constructor.$statics = keys(constructor.prototype.Statics);
            }

            if (parent && parent.$statics) {

                if (!constructor.$statics) {
                    constructor.$statics = [];
                }

                forEach(parent.$statics, function (value) {
                    if (isUndefined(constructor[value])) {    // Besides ignoring already defined members, reserved words like $abstract are also preserved
                        constructor[value] = parent[value];
                        constructor.$statics.push(value);
                    }
                });
            }
        }

        /**
         * Reset some properties in order to make them unique for the instance.
         * This solves the shared properties for types like objects or arrays.
         *
         * @param {Object} object The instance
         */
        function reset(object) {

            var key;

            for (key in object) {
                if (isArray(object[key])) {    // If is array, clone it
                    object[key] = [].concat(object[key]);
                } else if (isObject(object[key])) {    // If is an object, clone it
                    object[key] = mixIn({}, object[key]);
                }
            }
        }

        /**
         * Builds the constructor function that calls the initialize and do
         * more things internally.
         *
         * @param {Funciton} initialize The initialize function
         *
         * @return {Function} The constructor function
         */
        function constructor(initialize) {

            return function initializer() {

                // Reset some types of the object in order for each instance to have their variables
                reset(this);

                // Apply binds
                if (this.$constructor.$binds) {
                    binds(this.$constructor.$binds, this, this);
                }

                //>>includeStart('checks', pragmas.checks);
                // Call initialize
                if (!this.$constructor.$abstract) {
                    this.$initializing = true;
                }
                //>>includeEnd('checks');
                initialize.apply(this, arguments);
                //>>includeStart('checks', pragmas.checks);
                delete this.$initializing;
                //>>includeEnd('checks');
            };
        }

        if (params.Extends) {

            //>>includeStart('checks', pragmas.checks);
            if (!isFunction(params.Extends) || !params.Extends.$class) {
                throw new TypeError('Specified parent class in Extends of "' + params.Name + '" is not a valid class.');
            }
            //>>includeEnd('checks');

            parent = params.Extends;
            delete params.Extends;

            params.initialize = params.initialize || function () { parent.prototype.initialize.apply(this, arguments); };
            classify = constructor(params.initialize);
            classify.Super = parent.prototype;
            classify.prototype = createObject(parent.prototype, params);
        } else {
            params.initialize = params.initialize || function () {};
            classify = constructor(params.initialize);
            classify.prototype = params;
        }

        classify.prototype.$constructor = classify;
        //>>includeStart('checks', pragmas.checks);
        classify.$class = true;
        //>>includeEnd('checks');

        // Grab all the defined mixins
        if (params.Borrows) {
            borrows(params.Borrows, classify);
            delete classify.prototype.Borrows;
        }

        // Grab all the defined binds
        if (params.Binds) {
            grabBinds(classify);
            delete classify.prototype.Binds;
        }

        // Grab static methods from the parent and itself
        grabStatics(classify);
        //>>excludeStart('checks', pragmas.checks);
        if (params.Statics) {
            delete classify.prototype.Statics;  // If we got checks enabled, we can't delete the Statics yet (see bellow)
        }
        //>>excludeEnd('checks');

        //>>includeStart('checks', pragmas.checks);
        // If we are a concrete class that extends an abstract class, we need to verify the methods existence
        if (parent && parent.$abstract && !params.$abstract) {
            checkAbstract(parent, classify);
        }
        //>>includeEnd('checks');

        // If the class implement some interfaces and is not abstract then
        if (params.Implements) {

            //>>includeStart('checks', pragmas.checks);
            if (!params.$abstract) {
                checkInterfaces(params.Implements, classify);
            }
            //>>includeEnd('checks');

            delete classify.prototype.Implements;
        }

        //>>includeStart('checks', pragmas.checks);
        if (params.Statics) {
            delete classify.prototype.Statics;  // Delete statics now
        }
        //>>includeEnd('checks');

        return classify;
    }

    Classify.Abstract = Abstract;
    Classify.Interface = Interface;

    return Classify;
});
<|endoftext|>


<commit_before>/*
    Documentation:
    https://github.com/robmonie/jquery-week-calendar/wiki
    Latest build at this date(2015/10/14:
    https://github.com/calvera/jquery-week-calendar/blob/master/jquery.weekcalendar.js
*/

$(document).ready(function() {

    var screenWidth = $(window).width();
    var calendar = quickSetCalender();
    var daysToShow =

    //Status message window, useful for debugging/Information
    //$('

').prependTo($('body'));

    //Size change listener, changes days depending on resolution
    $(window).resize(function(event) {
        var newWidth = $(window).width();

        //Reduces load on client when resizing, can't instantiate nonstop
        if (newWidth > 640 && screenWidth <640) {
            calendar = quickSetCalender(7);
            screenWidth=newWidth;
        }
        else if (newWidth < 640 && screenWidth >640){
            calendar = quickSetCalender(3);
            screenWidth=newWidth;
        }
    });

});

var widthSettings = function(){
    var screenWidth = $(window).width();
    if (screenWidth > 640) {
            return 7;
        }
        else {
            return 3;
        }
};

var quickSetCalender = function(daysToShow) {

    var year = new Date().getFullYear();
    var month = new Date().getMonth();
    var day = new Date().getDate();

    var eventData = {
        events: [{
            'id': 1,
            'start': new Date(year, month, 16, 9),
            'end': new Date(year, month, 16, 10),
            'title': 'Presentation'
        }, {
            'id': 2,
            'start': new Date(year, month, 16, 19),
            'end': new Date(year, month, 16, 22),
            'title': 'Trolig utgång'
        }]
    };
    var calendar = $('#calendar').weekCalendar({
        daysToShow: widthSettings(),
        timeslotsPerHour: 4,
        timeslotHeigh: 30,
        //add 'a' to string to add am/pm
        timeFormat: "h:i",
        hourLine: true,
        data: eventData,
        //remove title
        title: 'Kalender',
        textSize: 13,
        timeSeparator: '-',
        allowCalEventOverlap: true,
        allowEventDelete: true,
        height: function($calendar) {
            return $(window).height() - $('h1').outerHeight(true);
        },
        /* Needs a styling here*/
        eventRender: function(calEvent, $event) {
            if (calEvent.end.getTime() < new Date().getTime()) {
                $event.css('backgroundColor', '#aaa');
                $event.find('.time').css({
                    'backgroundColor': '#999',
                    'border': '1px solid #888'
                });
            }
        },
        eventNew: function(calEvent, $event) {
            displayMessage('La till en händelse
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventDrop: function(calEvent, $event) {
            displayMessage('Moved Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventResize: function(calEvent, $event) {
            displayMessage('Resized Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventClick: function(calEvent, $event) {
            displayMessage('Clicked Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventMouseover: function(calEvent, $event) {
            displayMessage('Mouseover Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventMouseout: function(calEvent, $event) {
            displayMessage('Mouseout Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        noEvents: function() {
            displayMessage('There are no events for this week');
        }

    });

    function displayMessage(message) {
        $('#message').html(message).fadeIn();
    }
};<commit_msg>Fixed bad code that reinstatiated the calender every time the screen changed size to only change the viewed days instead with calender method<commit_after>/*
    Documentation:
    https://github.com/robmonie/jquery-week-calendar/wiki
    Latest build at this date(2015/10/14:
    https://github.com/calvera/jquery-week-calendar/blob/master/jquery.weekcalendar.js
*/

$(document).ready(function() {

    var screenWidth = $(window).width();
    var calendar = quickSetCalender();

    //Status message window, useful for debugging/Information
    //$('

').prependTo($('body'));

    //Size change listener, changes days depending on resolution
    $(window).resize(function(event) {
        var newWidth = $(window).width();

        //Reduces load on client when resizing
        if (newWidth > 640 && screenWidth <640) {
            calendar.weekCalendar("setDaysToShow",7);
            //calendar.weekCalendar("refresh");
            screenWidth=newWidth;
        }
        else if (newWidth < 640 && screenWidth >640){
            calendar.weekCalendar("setDaysToShow",3);
            //calendar.weekCalendar("refresh");
            screenWidth=newWidth;
        }
    });

});

var widthSettings = function(){
    var screenWidth = $(window).width();
    if (screenWidth > 640) {
            return 7;
        }
        else {
            return 3;
        }
};

var quickSetCalender = function(daysToShow) {

    var year = new Date().getFullYear();
    var month = new Date().getMonth();
    var day = new Date().getDate();

    var eventData = {
        events: [{
            'id': 1,
            'start': new Date(year, month, 16, 9),
            'end': new Date(year, month, 16, 10),
            'title': 'Presentation'
        }, {
            'id': 2,
            'start': new Date(year, month, 16, 19),
            'end': new Date(year, month, 16, 22),
            'title': 'Trolig utgång'
        }]
    };
    var calendar = $('#calendar').weekCalendar({
        daysToShow: widthSettings(),
        timeslotsPerHour: 4,
        timeslotHeigh: 30,
        //add 'a' to string to add am/pm
        timeFormat: "h:i",
        hourLine: true,
        data: eventData,
        //remove title
        title: 'Kalender',
        textSize: 13,
        timeSeparator: '-',
        allowCalEventOverlap: true,
        allowEventDelete: true,
        height: function($calendar) {
            return $(window).height() - $('h1').outerHeight(true);
        },
        /* Needs a styling here*/
        eventRender: function(calEvent, $event) {
            if (calEvent.end.getTime() < new Date().getTime()) {
                $event.css('backgroundColor', '#aaa');
                $event.find('.time').css({
                    'backgroundColor': '#999',
                    'border': '1px solid #888'
                });
            }
        },
        eventNew: function(calEvent, $event) {
            displayMessage('La till en händelse
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventDrop: function(calEvent, $event) {
            displayMessage('Moved Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventResize: function(calEvent, $event) {
            displayMessage('Resized Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventClick: function(calEvent, $event) {
            displayMessage('Clicked Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventMouseover: function(calEvent, $event) {
            displayMessage('Mouseover Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        eventMouseout: function(calEvent, $event) {
            displayMessage('Mouseout Event
Start: ' + calEvent.start + '
End: ' + calEvent.end);
        },
        noEvents: function() {
            displayMessage('There are no events for this week');
        }

    });

    function displayMessage(message) {
        $('#message').html(message).fadeIn();
    }
    return calendar;
};<|endoftext|>


<commit_before>/**
 * ownCloud - Music app
 *
 * @author Morris Jobke
 * @copyright 2013 Morris Jobke <morris.jobke@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

angular.module('Music').controller('PlayerController',
	['$scope', '$routeParams', '$rootScope', 'playlistService', 'Audio', 'Artists', 'Restangular', 'gettext',
	function ($scope, $routeParams, $rootScope, playlistService, Audio, Artists, Restangular, gettext) {

	$scope.artists = Artists;

	$scope.playing = false;
	$scope.loading = false;
	$scope.player = Audio;
	$scope.position = 0.0;
	$scope.duration = 0.0;
	$scope.currentTrack = null;
	$scope.currentArtist = null;
	$scope.currentAlbum = null;

	$scope.repeat = false;
	$scope.shuffle = false;

	// will be invoked by the audio factory
	$rootScope.$on('SoundManagerReady', function() {
		if($scope.$parent.started) {
			// invoke play after the flash gets unblocked
			$scope.$apply(function(){
				$scope.next();
			});
		}
	});

	// display a play icon in the title if a song is playing
	$scope.$watch('playing', function(newValue) {
		var title = $('title').html().trim();
		if(newValue) {
			$('title').html('▶ ' + title);
		} else {
			if(title.substr(0, 1) === '▶') {
				$('title').html(title.substr(1).trim());
			}
		}
	});

	$scope.getPlayableFileURL = function (track) {
		var isChrome = (navigator && navigator.userAgent &&
			navigator.userAgent.indexOf('Chrome') !== -1) ?
				true : false;
		for(var mimeType in track.files) {
			if(mimeType === 'audio/ogg' && isChrome) {
				// TODO inject this
				OC.Notification.showHtml(gettext(
					'Chrome is just able to playback MP3 files - see wiki'
				));
			}
			if(Audio.canPlayMIME(mimeType)) {
				return track.files[mimeType];
			}
		}

		return null;
	};

	$scope.$watch('currentTrack', function(newValue, oldValue) {
		$scope.player.stopAll();
		$scope.player.destroySound('ownCloudSound');
		if(newValue !== null) {
			// switch initial state
			$scope.$parent.started = true;
			// find artist
			$scope.currentArtist = _.find($scope.artists.$$v, // TODO Why do I have to use $$v?
										function(artist){
											return artist.id === newValue.artist.id;
										});
			// find album
			$scope.currentAlbum = _.find($scope.currentArtist.albums,
										function(album){
											return album.id === newValue.album.id;
										});

			$scope.player.createSound({
				id: 'ownCloudSound',
				url: $scope.getPlayableFileURL($scope.currentTrack),
				whileplaying: function() {
					$scope.setTime(this.position/1000, this.duration/1000);
				},
				onstop: function() {
					$scope.setPlay(false);
				},
				onfinish: function() {
					$scope.setPlay(false);
					// determine if already inside of an $apply or $digest
					// see http://stackoverflow.com/a/12859093
					if($scope.$$phase) {
						$scope.next();
					} else {
						$scope.$apply(function(){
							$scope.next();
						});
					}
				},
				onresume: function() {
					$scope.setPlay(true);
				},
				onplay: function() {
					$scope.setPlay(true);
				},
				onpause: function() {
					$scope.setPlay(false);
				},
				onload: function(success) {
					if(!success) {
						$scope.setPlay(false);
						Restangular.all('log').post({message: JSON.stringify($scope.currentTrack)});
						// determine if already inside of an $apply or $digest
						// see http://stackoverflow.com/a/12859093
						if($scope.$$phase) {
							$scope.next();
						} else {
							$scope.$apply(function(){
								$scope.next();
							});
						}
					}
				},
				onbufferchange: function() {
					$scope.setLoading(this.isBuffering);
				},
				volume: 50
			});
			$scope.player.play('ownCloudSound');
		} else {
			$scope.currentArtist = null;
			$scope.currentAlbum = null;
			// switch initial state
			$scope.$parent.started = false;
		}
	});

	// only call from external script
	$scope.setPlay = function(playing) {
		// determine if already inside of an $apply or $digest
		// see http://stackoverflow.com/a/12859093
		if($scope.$$phase) {
			$scope.playing = playing;
		} else {
			$scope.$apply(function(){
				$scope.playing = playing;
			});
		}
	};

	// only call from external script
	$scope.setLoading = function(loading) {
		// determine if already inside of an $apply or $digest
		// see http://stackoverflow.com/a/12859093
		if($scope.$$phase) {
			$scope.loading = loading;
		} else {
			$scope.$apply(function(){
				$scope.loading = loading;
			});
		}
	};

	// only call from external script
	$scope.setTime = function(position, duration) {
		// determine if already inside of an $apply or $digest
		// see http://stackoverflow.com/a/12859093
		if($scope.$$phase) {
			$scope.duration = duration;
			$scope.position = position;
		} else {
			$scope.$apply(function(){
				$scope.duration = duration;
				$scope.position = position;
			});
		}
	};

	$scope.toggle = function(forcePlay) {
		forcePlay = forcePlay || false;
		if($scope.currentTrack === null) {
			// nothing to do
			return null;
		}
		if(forcePlay) {
			$scope.player.play('ownCloudSound');
		} else {
			$scope.player.togglePause('ownCloudSound');
		}
	};

	$scope.next = function() {
		var track = playlistService.getNextTrack($scope.repeat, $scope.shuffle);

		// get the next track as long as the current one contains no playable
		// audio mimetype
		while(track !== null && !$scope.getPlayableFileURL(track)) {
			track = playlistService.getNextTrack($scope.repeat, $scope.shuffle);
		}
		$scope.currentTrack = track;
	};

	$scope.prev = function() {
		var track = playlistService.getPrevTrack();
		if(track !== null) {
			$scope.currentTrack = track;
		}
	};

	playlistService.subscribe('play', function(){
		// fetch track and start playing
		$scope.next();
	});
}]);<commit_msg>fix english string<commit_after>/**
 * ownCloud - Music app
 *
 * @author Morris Jobke
 * @copyright 2013 Morris Jobke <morris.jobke@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

angular.module('Music').controller('PlayerController',
	['$scope', '$routeParams', '$rootScope', 'playlistService', 'Audio', 'Artists', 'Restangular', 'gettext',
	function ($scope, $routeParams, $rootScope, playlistService, Audio, Artists, Restangular, gettext) {

	$scope.artists = Artists;

	$scope.playing = false;
	$scope.loading = false;
	$scope.player = Audio;
	$scope.position = 0.0;
	$scope.duration = 0.0;
	$scope.currentTrack = null;
	$scope.currentArtist = null;
	$scope.currentAlbum = null;

	$scope.repeat = false;
	$scope.shuffle = false;

	// will be invoked by the audio factory
	$rootScope.$on('SoundManagerReady', function() {
		if($scope.$parent.started) {
			// invoke play after the flash gets unblocked
			$scope.$apply(function(){
				$scope.next();
			});
		}
	});

	// display a play icon in the title if a song is playing
	$scope.$watch('playing', function(newValue) {
		var title = $('title').html().trim();
		if(newValue) {
			$('title').html('▶ ' + title);
		} else {
			if(title.substr(0, 1) === '▶') {
				$('title').html(title.substr(1).trim());
			}
		}
	});

	$scope.getPlayableFileURL = function (track) {
		var isChrome = (navigator && navigator.userAgent &&
			navigator.userAgent.indexOf('Chrome') !== -1) ?
				true : false;
		for(var mimeType in track.files) {
			if(mimeType === 'audio/ogg' && isChrome) {
				// TODO inject this
				OC.Notification.showHtml(gettext(
					'Chrome is only able to playback MP3 files - see wiki'
				));
			}
			if(Audio.canPlayMIME(mimeType)) {
				return track.files[mimeType];
			}
		}

		return null;
	};

	$scope.$watch('currentTrack', function(newValue, oldValue) {
		$scope.player.stopAll();
		$scope.player.destroySound('ownCloudSound');
		if(newValue !== null) {
			// switch initial state
			$scope.$parent.started = true;
			// find artist
			$scope.currentArtist = _.find($scope.artists.$$v, // TODO Why do I have to use $$v?
										function(artist){
											return artist.id === newValue.artist.id;
										});
			// find album
			$scope.currentAlbum = _.find($scope.currentArtist.albums,
										function(album){
											return album.id === newValue.album.id;
										});

			$scope.player.createSound({
				id: 'ownCloudSound',
				url: $scope.getPlayableFileURL($scope.currentTrack),
				whileplaying: function() {
					$scope.setTime(this.position/1000, this.duration/1000);
				},
				onstop: function() {
					$scope.setPlay(false);
				},
				onfinish: function() {
					$scope.setPlay(false);
					// determine if already inside of an $apply or $digest
					// see http://stackoverflow.com/a/12859093
					if($scope.$$phase) {
						$scope.next();
					} else {
						$scope.$apply(function(){
							$scope.next();
						});
					}
				},
				onresume: function() {
					$scope.setPlay(true);
				},
				onplay: function() {
					$scope.setPlay(true);
				},
				onpause: function() {
					$scope.setPlay(false);
				},
				onload: function(success) {
					if(!success) {
						$scope.setPlay(false);
						Restangular.all('log').post({message: JSON.stringify($scope.currentTrack)});
						// determine if already inside of an $apply or $digest
						// see http://stackoverflow.com/a/12859093
						if($scope.$$phase) {
							$scope.next();
						} else {
							$scope.$apply(function(){
								$scope.next();
							});
						}
					}
				},
				onbufferchange: function() {
					$scope.setLoading(this.isBuffering);
				},
				volume: 50
			});
			$scope.player.play('ownCloudSound');
		} else {
			$scope.currentArtist = null;
			$scope.currentAlbum = null;
			// switch initial state
			$scope.$parent.started = false;
		}
	});

	// only call from external script
	$scope.setPlay = function(playing) {
		// determine if already inside of an $apply or $digest
		// see http://stackoverflow.com/a/12859093
		if($scope.$$phase) {
			$scope.playing = playing;
		} else {
			$scope.$apply(function(){
				$scope.playing = playing;
			});
		}
	};

	// only call from external script
	$scope.setLoading = function(loading) {
		// determine if already inside of an $apply or $digest
		// see http://stackoverflow.com/a/12859093
		if($scope.$$phase) {
			$scope.loading = loading;
		} else {
			$scope.$apply(function(){
				$scope.loading = loading;
			});
		}
	};

	// only call from external script
	$scope.setTime = function(position, duration) {
		// determine if already inside of an $apply or $digest
		// see http://stackoverflow.com/a/12859093
		if($scope.$$phase) {
			$scope.duration = duration;
			$scope.position = position;
		} else {
			$scope.$apply(function(){
				$scope.duration = duration;
				$scope.position = position;
			});
		}
	};

	$scope.toggle = function(forcePlay) {
		forcePlay = forcePlay || false;
		if($scope.currentTrack === null) {
			// nothing to do
			return null;
		}
		if(forcePlay) {
			$scope.player.play('ownCloudSound');
		} else {
			$scope.player.togglePause('ownCloudSound');
		}
	};

	$scope.next = function() {
		var track = playlistService.getNextTrack($scope.repeat, $scope.shuffle);

		// get the next track as long as the current one contains no playable
		// audio mimetype
		while(track !== null && !$scope.getPlayableFileURL(track)) {
			track = playlistService.getNextTrack($scope.repeat, $scope.shuffle);
		}
		$scope.currentTrack = track;
	};

	$scope.prev = function() {
		var track = playlistService.getPrevTrack();
		if(track !== null) {
			$scope.currentTrack = track;
		}
	};

	playlistService.subscribe('play', function(){
		// fetch track and start playing
		$scope.next();
	});
}]);<|endoftext|>


<commit_before>// Get output string.
let output = "y\n";
if (process.argv.length !== 2) {
	output = process.argv.slice(2).join(' ') + "\n";
}

// Write.
function flood() {
	while (process.stdout.write(buffer) !== false);
}

const buffer = output.repeat(Math.floor(4096 / output.length));
process.stdout.on('drain', flood);
flood();

<commit_msg>yes.js: Fixed bug where argv > 4096 writes nothing.<commit_after>// Get output string.
let output = "y\n";
if (process.argv.length !== 2) {
	output = process.argv.slice(2).join(' ') + "\n";
}

// Write.
function flood() {
	while (process.stdout.write(buffer) !== false);
}

const buffer = output.repeat(Math.max(1, Math.floor(4096 / output.length)));
process.stdout.on('drain', flood);
flood();

<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

//TODO Copied from GRAPHING_LINES/common/view/EquationAccordionBox
//TODO extend AccordionBox, not Panel
/**
 * Accordion box that contains the interactive equation and associated controls.
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  const AccordionBox = require( 'SUN/AccordionBox' );
  const EraserButton = require( 'SCENERY_PHET/buttons/EraserButton' );
  const FontAwesomeNode = require( 'SUN/FontAwesomeNode' );
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const HBox = require( 'SCENERY/nodes/HBox' );
  const HSeparator = require( 'SUN/HSeparator' );
  const PhetColorScheme = require( 'SCENERY_PHET/PhetColorScheme' );
  const RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  // constants
  const BUTTON_ICON_WIDTH = 30;
  const SEPARATOR_OPTIONS = { stroke: GQColors.SEPARATOR };

  class EquationAccordionBox extends AccordionBox {

    /**
     * @param {Node} interactiveEquationNode - interactive equation
     * @param {function} saveFunction
     * @param {function} eraseFunction
     * @param {NumberProperty} numberOfSavedLinesProperty
     * @param {Object} [options]
     */
    constructor( interactiveEquationNode, saveFunction, eraseFunction, numberOfSavedLinesProperty, options ) {

      options = _.extend( {

        // superclass options
        fill: GQColors.CONTROL_PANEL_BACKGROUND,
        titleYMargin: 10,
        buttonLength: 25,
        buttonXMargin: 10,
        contentXMargin: 20,
        contentYMargin: 10
      }, options );

      // Save button
      const saveButton = new RectangularPushButton( {
        content: new FontAwesomeNode( 'camera', { maxWidth: BUTTON_ICON_WIDTH } ),
        baseColor: PhetColorScheme.BUTTON_YELLOW,
        listener: saveFunction
      } );

      // Erase button
      const eraseButton = new EraserButton( {
        iconWidth: BUTTON_ICON_WIDTH,
        listener: eraseFunction
      } );

      // horizontal layout of buttons
      const buttons = new HBox( {
        children: [ saveButton, eraseButton ],
        spacing: 40
      } );

      const content = new VBox( {
        align: 'center',
        spacing: 10,
        children: [
          new HSeparator( interactiveEquationNode.width, SEPARATOR_OPTIONS ),
          interactiveEquationNode,
          new HSeparator( interactiveEquationNode.width, SEPARATOR_OPTIONS ),
          buttons
        ]
      } );

      super( content, options );

      // Disable the erase button when there are no saved lines.
      numberOfSavedLinesProperty.link( numberOfSavedLines => {
        eraseButton.enabled = ( numberOfSavedLines > 0 );
      } );
    }
  }

  return graphingQuadratics.register( 'EquationAccordionBox', EquationAccordionBox );
} );<commit_msg>remove TODOs<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * Accordion box that contains the interactive equation and associated controls.
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  const AccordionBox = require( 'SUN/AccordionBox' );
  const EraserButton = require( 'SCENERY_PHET/buttons/EraserButton' );
  const FontAwesomeNode = require( 'SUN/FontAwesomeNode' );
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const HBox = require( 'SCENERY/nodes/HBox' );
  const HSeparator = require( 'SUN/HSeparator' );
  const PhetColorScheme = require( 'SCENERY_PHET/PhetColorScheme' );
  const RectangularPushButton = require( 'SUN/buttons/RectangularPushButton' );
  const VBox = require( 'SCENERY/nodes/VBox' );

  // constants
  const BUTTON_ICON_WIDTH = 30;
  const SEPARATOR_OPTIONS = { stroke: GQColors.SEPARATOR };

  class EquationAccordionBox extends AccordionBox {

    /**
     * @param {Node} interactiveEquationNode - interactive equation
     * @param {function} saveFunction
     * @param {function} eraseFunction
     * @param {NumberProperty} numberOfSavedLinesProperty
     * @param {Object} [options]
     */
    constructor( interactiveEquationNode, saveFunction, eraseFunction, numberOfSavedLinesProperty, options ) {

      options = _.extend( {

        // superclass options
        fill: GQColors.CONTROL_PANEL_BACKGROUND,
        titleYMargin: 10,
        buttonLength: 25,
        buttonXMargin: 10,
        contentXMargin: 20,
        contentYMargin: 10
      }, options );

      // Save button
      const saveButton = new RectangularPushButton( {
        content: new FontAwesomeNode( 'camera', { maxWidth: BUTTON_ICON_WIDTH } ),
        baseColor: PhetColorScheme.BUTTON_YELLOW,
        listener: saveFunction
      } );

      // Erase button
      const eraseButton = new EraserButton( {
        iconWidth: BUTTON_ICON_WIDTH,
        listener: eraseFunction
      } );

      // horizontal layout of buttons
      const buttons = new HBox( {
        children: [ saveButton, eraseButton ],
        spacing: 40
      } );

      const content = new VBox( {
        align: 'center',
        spacing: 10,
        children: [
          new HSeparator( interactiveEquationNode.width, SEPARATOR_OPTIONS ),
          interactiveEquationNode,
          new HSeparator( interactiveEquationNode.width, SEPARATOR_OPTIONS ),
          buttons
        ]
      } );

      super( content, options );

      // Disable the erase button when there are no saved lines.
      numberOfSavedLinesProperty.link( numberOfSavedLines => {
        eraseButton.enabled = ( numberOfSavedLines > 0 );
      } );
    }
  }

  return graphingQuadratics.register( 'EquationAccordionBox', EquationAccordionBox );
} );<|endoftext|>


<commit_before>_p.show_dialog = function() {
	if(!_p.dialog) {
		_p.make_dialog();
	}
	_p.dialog.show();
}

_p.make_dialog = function() {
	var d = new Dialog(360, 140, "Print Formats");
	d.make_body(
		[['HTML','Select']
		,['Check','No Letterhead','Will ignore letterhead if it can be set. May not work for all formats']
		,['HTML', 'Buttons']
		]);

	d.widgets['No Letterhead'].checked = 1;

	// prints
	$btn(d.widgets.Buttons, 'Print',
		function() { _p.build(sel_val(cur_frm.print_sel), _p.go, d.widgets['No Letterhead'].checked); },
		{cssFloat:'right', marginBottom:'16px', marginLeft:'7px'}, 'green');

	// preview
	$btn(d.widgets.Buttons, 'Preview',
		function() { _p.build(sel_val(cur_frm.print_sel), _p.preview, d.widgets['No Letterhead'].checked); },
		{cssFloat:'right', marginBottom:'16px'}, '');

	_p.dialog = d;
	d.onshow = function() {
		var c = d.widgets['Select'];
		if(c.cur_sel && c.cur_sel.parentNode == c)
			c.removeChild(c.cur_sel);
		c.appendChild(cur_frm.print_sel);
		c.cur_sel = cur_frm.print_sel;
	}
}

_p.field_tab = function(layout_cell) {
	var t = $a(layout_cell, 'table', '', {width:'100%'});
	var r = t.insertRow(0); this.r = r;
	r.insertCell(0); r.insertCell(1);
	r.cells[0].className='datalabelcell';
	r.cells[1].className='datainputcell';
	return r
}

// standard layout
// ==========================================================================

_p.print_std_add_table = function(t, layout, pf_list, dt, no_letterhead) {
	if(t.appendChild) {
		// one table only
		layout.cur_cell.appendChild(t);
	} else {
		// multiple tables
		for(var ti=0;ti<t.length-1;ti++) {
			// add to current page
			layout.cur_cell.appendChild(t[ti]);
			layout.close_borders();
			pf_list[pf_list.length] = '

';

			// new page
			layout = _p.add_layout(dt, no_letterhead);
			pf_list[pf_list.length]=layout;

			layout.addrow();
			layout.addcell();

			var div = $a(layout.cur_cell, 'div');
			div.innerHTML = 'Continued from previous page...';
			div.style.padding = '4px';
		}
		// last table
		layout.cur_cell.appendChild(t[t.length-1]);
	}
	return layout;
}

// --------------------------------------------------------------------

_p.print_std_add_field = function(dt, dn, f, layout) {

	var v = _f.get_value(dt,dn,f.fieldname);
	if(f.fieldtype!="Button") {
		if(!v && !in_list(['Float','Int','Currency'], f.fieldtype)) {
			// no value and non-numberic - do nothing
		} else {
			r = _p.field_tab(layout.cur_cell)
			// label
			r.cells[0].innerHTML=f.label?f.label:f.fieldname;

			$s(r.cells[1], v, f.fieldtype);

			// left align currency in normal display
			if(f.fieldtype=='Currency')
				$y(r.cells[1],{textAlign: 'left'});
			}
	}
}

_p.get_letter_head = function() {
	// add letter head
	var cp = locals['Control Panel']['Control Panel'];
	if(cur_frm.doc.letter_head)
		var lh= cstr(_p.letter_heads[cur_frm.doc.letter_head]);
	else if(cp.letter_head)
		var lh= cp.letter_head;
	else
		var lh= '';

	return lh;
}

// --------------------------------------------------------------------

_p.add_layout = function(dt, no_letterhead) {
	var l = new Layout();
	l.addrow();

	if(locals['DocType'][dt].print_outline=='Yes') l.with_border = 1;

	return l;
}

// --------------------------------------------------------------------

_p.print_std = function(no_letterhead) {
	var dn = cur_frm.docname;
	var dt = cur_frm.doctype;
	var pf_list = [];

	var layout = _p.add_layout(dt, no_letterhead);
	pf_list[pf_list.length]=layout;

	// heading
	var h1 = $a(layout.cur_row.header, 'h1', '', {fontSize:'22px', marginBottom:'8px'});
	h1.innerHTML = cur_frm.pformat[dn] ? cur_frm.pformat[dn] : get_doctype_label(dt);

	var h2 = $a(layout.cur_row.header, 'div', '', {fontSize:'16px', color:'#888', marginBottom:'8px', paddingBottom:'8px', borderBottom:(layout.with_border ? '0px' : '1px solid #000' )});
	h2.innerHTML = dn;

	var fl = getchildren('DocField', dt, 'fields', 'DocType');

	if(fl[0]&&fl[0].fieldtype!="Section Break") {
		layout.addrow(); // default section break
		if(fl[0].fieldtype!="Column Break") // without column too
			layout.addcell();
	}

	// build each field
	for(var i=0;i<fl.length;i++) {
		var fn = fl[i].fieldname?fl[i].fieldname:fl[i].label;
		if(fn)
			var f = get_field(dt, fn, dn);
		else
			var f = fl[i];

		if(!f.print_hide){

			// if there is a custom method to generate the HTML then use it
			if(cur_frm.pformat[f.fieldname]) {

				var tmp = $a(layout.cur_cell, 'div');
				tmp.innerHTML = cur_frm.pformat[f.fieldname](locals[dt][dn]);

			} else {
				// do the normal thing

				switch(f.fieldtype){
				 case 'Section Break':
					layout.addrow();
					// if no column break after this field then add a column
					if(fl[i+1]&&(fl[i+1].fieldtype!='Column Break')) {
						layout.addcell(); }

					// add label ---- no labels for section breaks!
					//if(f.label) layout.cur_row.header.innerHTML = '
'+f.label+'
';
					break;
				 case 'Column Break':
					layout.addcell(f.width, f.label);
					//if(f.label) layout.cur_cell.header.innerHTML = '
'+f.label+'
';
					break;
				 case 'Table':
					var t = print_table(dt, dn,f.fieldname,f.options,null,null,null,null);
					layout = _p.print_std_add_table(t, layout, pf_list, dt, no_letterhead);
				 	break;
				 case 'HTML':
				 	var tmp = $a(layout.cur_cell, 'div');
				 	tmp.innerHTML = f.options;
				 	break;
				 case 'Code':
				 	var tmp = $a(layout.cur_cell, 'div');
				 	var v= _f.get_value(dt,dn,f.fieldname);
				 	tmp.innerHTML = '
'+ f.label + ':
' + '
'+(v?v:'')+'
';
				 	break;
				 case 'Text Editor':
				 	var tmp = $a(layout.cur_cell, 'div');
				 	var v= _f.get_value(dt,dn,f.fieldname);
				 	tmp.innerHTML = v?v:'';
				 	break;
				 default:
				 	// add cell data
				 	_p.print_std_add_field(dt, dn, f, layout);

				}
			}
		}
	}

	layout.close_borders();

	// build html for each page
	var html = '';
	for(var i=0;i<pf_list.length;i++) {
		if(pf_list[i].wrapper) {
			html += pf_list[i].wrapper.innerHTML;
		} else if(pf_list[i].innerHTML) {
			html += pf_list[i].innerHTML;
		} else {
			html += pf_list[i];
		}
	}

	pf_list = []; // cleanup
	return html;
}

_p.print_style = ".datalabelcell {padding: 2px 0px; width: 38%;vertical-align:top; }"
	+".datainputcell { padding: 2px 0px; width: 62%; text-align:left; }"
	+".sectionHeading { font-size: 16px; font-weight: bold; margin: 8px 0px }"
	+".columnHeading { font-size: 14px; font-weight: bold; margin: 8px 0px; }"

_p.formats = {}

_p.build = function(fmtname, onload, no_letterhead, only_body) {
	if(!cur_frm) { alert('No Document Selected'); return; }
	var doc = locals[cur_frm.doctype][cur_frm.docname];
	if(fmtname=='Standard') {
		onload(_p.render(_p.print_std(no_letterhead), _p.print_style, doc, doc.name, no_letterhead, only_body));
	} else {
		if(!_p.formats[fmtname]) // not loaded, get data
			$c('webnotes.widgets.form.get_print_format', {'name':fmtname },
				function(r,rt) {
					_p.formats[fmtname] = r.message;
					onload(_p.render(_p.formats[fmtname], '', doc, doc.name, no_letterhead, only_body));
				}
			);
		else // loaded
			onload(_p.render(_p.formats[fmtname], '', doc, doc.name, no_letterhead, only_body));
	}
}

_p.render = function(body, style, doc, title, no_letterhead, only_body) {
	var block = document.createElement('div');
	var tmp_html = '';

	if(doc && cint(doc.docstatus)==0 && cur_frm.perm[0][SUBMIT])  {
		var tmp_html = '

DRAFT
This box will go away after the document is submitted.
';
	}
	if(doc && doc.__archived)  {
		var tmp_html = '

ARCHIVED
You must restore this document to make it editable.
';
	}

	style = (only_body ? '' : _p.def_print_style_body) + _p.def_print_style_other + style;

	block.innerHTML = body;

	// run embedded javascript
	var jslist = block.getElementsByTagName('script');
	while(jslist.length>0) {
		for(var i=0; i<jslist.length; i++) {
			var code = jslist[i].innerHTML;
			var p = jslist[i].parentNode;
			var sp = $a(p, 'span');
			p.replaceChild(sp, jslist[i]);
			var h = eval(code); if(!h)h='';
			sp.innerHTML = h;
		}
		jslist = block.getElementsByTagName('script');
	}

	// show letterhead?
	if(only_body)
		show_lh = false;
	else {
		if(!no_letterhead) show_lh = true;
		else show_lh = false;
	}

	// add letter head
	if(show_lh) {
		block.innerHTML = '
' + _p.get_letter_head() + '
' + block.innerHTML;
	}

	if(only_body) {
		return tmp_html + block.innerHTML.replace(/<td/g, '\n<td').replace(/<div/g, '\n<div');
	} else {
		// print block
		return '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n'
			+ ''
			+ '<title>'+title+'</title>'
			+ ''
			+ ''
			+ tmp_html
			+ block.innerHTML.replace(/<td/g, '\n<td')
			+ '';
	}
}

print_table = function(dt, dn, fieldname, tabletype, cols, head_labels, widths, condition, cssClass) {
	var fl = fields_list[tabletype];
	var ds = getchildren(tabletype, dn, fieldname, dt);
	var tl = [];
	var cell_style = {border:'1px solid #000', padding:'2px', verticalAlign:'top'};
	var head_cell_style = {border:'1px solid #000', padding:'2px', verticalAlign:'top', backgroundColor:'#ddd'};

	var make_table = function(fl) {
		var w = document.createElement('div');
		var t = $a(w, 'table', '', {width:'100%', borderCollapse:'collapse', marginBottom:'10px'});
		t.wrapper = w;

		// head row
		t.insertRow(0);
		var c_start = 0;
	 	if(fl[0]=='SR') {
			var cell = t.rows[0].insertCell(0)
			cell.innerHTML = head_labels?head_labels[0]:'Sr';
	 		$y(cell, {width:'30px'});
	 		$y(cell, head_cell_style)

			c_start = 1;
		}

		for(var c=c_start;c<fl.length;c++) {
			var cell = t.rows[0].insertCell(c);
			$y(cell, head_cell_style)
			if(head_labels)
				cell.innerHTML = head_labels[c];
			else
				cell.innerHTML = fl[c].label;
			if(fl[c].width)
				$y(cell, {width:fl[c].width});
			if(widths)
				$y(cell, {width: widths[c]});
			if(fl[c].fieldtype=='Currency')
				$y(cell,{textAlign: 'right'});
			cell.style.fontWeight = 'bold';
		}
		return t;
	}

	// no headings if not entries

	if(!ds.length) return document.createElement('div');

	// make column list
	var newfl = [];
	if(cols&&cols.length) { // custom
		if(cols[0]=='SR')newfl[0]='SR';
		for(var i=0;i<cols.length;i++) {
			for(var j=0;j<fl.length;j++) {
				if(fl[j].fieldname==cols[i]) {
					newfl[newfl.length] = fl[j];
					break;
				}
			}
		}
	} else { // remove hidden cols
		newfl = ['SR']
		for(var j=0;j<fl.length;j++) {
			if(!fl[j].print_hide) {
				newfl[newfl.length] = fl[j];
			}
		}
	}
	fl = newfl;

	var t = make_table(fl);
	tl.push(t.wrapper);

	// setup for auto "Sr No" -> SR
	var c_start = 0;
	if(fl[0]=='SR') { c_start = 1; }

	// data
	var sr = 0;
	for(var r=0;r<ds.length;r++) {
		if((!condition)||(condition(ds[r]))) {

			// check for page break
			if(ds[r].page_break) { var t = make_table(fl); tl.push(t.wrapper); }

			var rowidx = t.rows.length;
			sr++
			var row = t.insertRow(rowidx);
			if(c_start) {
				var cell = row.insertCell(0);
				cell.innerHTML = sr;
				$y(cell, cell_style);
			}

			// add values
			for(var c=c_start;c<fl.length;c++) {
				var cell = row.insertCell(c);
				$y(cell, cell_style);

				$s(cell, ds[r][fl[c].fieldname], fl[c].fieldtype);
				if(fl[c].fieldtype=='Currency')
					cell.style.textAlign = 'right';
			}
		}
	}
	if(tl.length>1) return tl; // multiple tables with page breakes
	else return tl[0];
}
<commit_msg>Working on print_format.js refactoring<commit_after>// _p can be referenced as this inside $.extend
$.extend(_p, {
	show_dialog: function() {
		if(!_p.dialog) {
			_p.make_dialog();
		}
		_p.dialog.show();
	},

	make_dialog: function() {
		// Prepare Dialog Box Layout
		var d = new Dialog(
			w = 360,
			h = 140,
			title = 'Print Formats',
			content = [
				['HTML', 'Select'],
				['Check', 'No Letterhead'],
				['HTML', 'Buttons']
			]);
		d.widgets['No Letterhead'].checked = 1;

		// Print Button
		$btn(
			parent = d.widgets.Buttons,
			label = 'Print',
			onclick = function() {
				_p.build({
					fmtname: sel_val(cur_frm.print_sel),
					onload: _p.go,
					no_letterhead: d.widgets['No Letterhead'].checked,
					only_body: undefined
				});
			},
			style = {
				cssFloat: 'right',
				marginBottom: '16px',
				marginLeft: '7px'
			},
			css_class = 'green'
		);

		// Print Preview
		$btn(
			parent = d.widgets.Buttons,
			label = 'Preview',
			onclick = function() {
				_p.build({
					fmtname: sel_val(cur_frm.print_sel),
					onload: _p.preview,
					no_letterhead: d.widgets['No Letterhead'].checked,
					only_body: undefined
				});
			},
			style = {
				cssFloat: 'right',
				marginBottom: '16px'
			},
			css_class = ''
		);

		_p.dialog = d;

		// Delete previous print format select list and Reload print format list from current form
		d.onshow = function() {
			var c = _p.dialog.widgets['Select'];
			if(c.cur_sel && c.cur_sel.parentNode == c) {
				c.removeChild(c.cur_sel);
			}
			c.appendChild(cur_frm.print_sel);
			c.cur_sel = cur_frm.print_sel;
		}
	},

	// Define formats dict
	formats: {},

	/* args dict can contain:
			+ fmtname --> print format name
			+ onload
			+ no_letterhead
			+ only_body
	*/
	build: function(args) {
		if(!cur_frm) {
			alert('No Document Selected');
			return;
		}

		// Get current doc (record)
		var doc = locals[cur_frm.doctype][cur_frm.docname];
		if(args.fmtname == 'Standard') {
			/*
				Render standard print layout
				The function passed as args.onload is then called using these parameters
			*/
			args.onload(_p.render({
				body: _p.print_std(args.no_letterhead),
				style: _p.print_style,
				doc: doc,
				title: doc.name,
				no_letterhead: args.no_letterhead,
				only_body: args.only_body
			}));
		} else {
			if (!_p.formats[args.fmtname]) {
				/*
					If print formats are not loaded, then load them and call the args.onload function on callback.
					I think, this case happens when preview is invoked directly
				*/
				$c(
					command = 'webnotes.widgets.form.get_print_format',
					args = { 'name': args.fmtname	},
					fn = function(r, rt) {
						_p.formats[args.fmtname] = r.message;
						args.onload(_p.render({
							body: _p.formats[args.fmtname],
							style: '',
							doc: doc,
							title: doc.name,
							no_letterhead: args.no_letterhead,
							only_body: args.only_body
						}));
					}
				);
			} else {
				// If print format is already loaded, go ahead with args.onload function call
				args.onload(_p.render({
					body: _p.formats[args.fmtname],
					style: '',
					doc: doc,
					title: doc.name,
					no_letterhead: args.no_letterhead,
					only_body: args.only_body
				}));
			}
		}
	},

	/*
		args dict can contain:
			+ body
			+ style
			+ doc
			+ title
			+ no_letterhead
			+ only_body

	*/
	render: function(args) {
		var container = document.createElement('div');
		var stat = '';

		// if draft/archived, show draft/archived banner
		stat += _p.show_draft(args);
		stat += _p.show_archived(args);

		// Append args.body's content as a child of container
		container.innerHTML = args.body;

		_p.run_embedded_js(container, args.doc);
		var style = _p.consolidate_css(container, args);

		// Show letterhead?
		_p.show_letterhead(container, args);

		_p.render_final(style, stat, container, args);
	},

	head_banner_format: function() {
		return "\

 \

\
					{{TITLE}}\

\
				{{DESCRIPTION}}\

"
	},

	/*
		Check if doc's status is not submitted (docstatus == 0)
		and submission is pending

		Display draft in header if true
	*/
	show_draft: function(args) {
		if(args.doc && cint(args.doc.docstatus)==0 && cur_frm.perm[0][SUBMIT]) {
			draft = _p.head_banner_format();
			draft = draft.replace("{{HEAD}}", "DRAFT");
			draft = draft.replace("{{DESCRIPTION}}", "This box will go away after the document is submitted.");
			return draft;
		} else {
			return "";
		}
	},

	/*
		Check if doc is archived
		Display archived in header if true
	*/
	show_archived: function(args) {
		if(args.doc && args.doc.__archived) {
			archived = _p.head_banner_format();
			archived = archived.replace("{{HEAD}}", "ARCHIVED");
			archived = archived.replace("{{DESCRIPTION}}", "You must restore this document to make it editable.");
		} else {
			return "";
		}
	},

	consolidate_css: function(container, args) {
		// Extract \
						\
						\n';

			footer = '\n\n\
					';
		}
		return header
			+ stat
			+ container.innerHTML.replace(/<div/g, '\n<div').replace(/<td/g, '\n<td')
			+ footer;

	},

	// fetches letter head from current doc or control panel
	get_letter_head: function() {
		var cp = locals['Control Panel']['Control Panel'];
		var lh = '';
		if(cur_frm.doc.letter_head) {
			lh = cstr(_p.letter_heads[cur_frm.doc.letter_head]);
		} else if (cp.letter_head) {
			lh = cp.letter_head
		}
		return lh;
	},

	// common print style setting
	print_style: "\
		.datalabelcell { \
			padding: 2px 0px; \
			width: 38%; \
			vertical-align: top; \
			} \
		.datainputcell { \
			padding: 2px 0px; \
			width: 62%; \
			text-align: left; \
			}\
		.sectionHeading { \
			font-size: 16px; \
			font-weight: bold; \
			margin: 8px 0px; \
			} \
		.columnHeading { \
			font-size: 14px; \
			font-weight: bold; \
			margin: 8px 0px; \
			}"

	/*print_std_add_table: function() {

	},

	field_tab: function(layout_cell) {
		var tab = $a(layout_cell, 'table', '', {width:'100%'});
		var row = tab.insertRow(0);
		_p.row = row; // Don't know this line's purpose
		row.insertCell(0);
		row.insertCell(1);
		row.cells[0].className = 'datalabelcell';
		row.cells[1].className = 'datainputcell';
		return row;
	}*/
});

print_table = function(args) {

}<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import Reflux from 'reflux';
import {actions} from '../actions';
import {bem} from '../bem';
import {stores} from '../stores';
import mixins from '../mixins';
import DocumentTitle from 'react-document-title';
import SharingForm from './permissions/sharingForm';
import ProjectSettings from './modalForms/projectSettings';
import DataTable from './table';
import ui from '../ui';
import {ProjectDownloads} from './formEditors';

import {PROJECT_SETTINGS_CONTEXTS} from '../constants';

import FormMap from './map';
import RESTServices from './RESTServices';

import {
  t
} from '../utils';

export class FormSubScreens extends React.Component {
  constructor(props){
    super(props);
    this.state = {};
    autoBind(this);
  }
  componentDidMount () {
    this.listenTo(stores.asset, this.dmixAssetStoreChange);
    var uid = this.props.params.assetid || this.props.uid || this.props.params.uid;
    if (this.props.randdelay && uid) {
      window.setTimeout(()=>{
        actions.resources.loadAsset({id: uid});
      }, Math.random() * 3000);
    } else if (uid) {
      actions.resources.loadAsset({id: uid});
    }
  }
  render () {
    let permAccess = this.userCan('view_submissions', this.state) || this.userCan('partial_submissions', this.state);

    if (!this.state.permissions)
      return false;

    if (this.props.location.pathname == `/forms/${this.state.uid}/settings` &&
        !this.userCan('change_asset', this.state)) {
      return (<ui.AccessDeniedMessage/>);
    }

    if (this.props.location.pathname == `/forms/${this.state.uid}/settings/rest` && !permAccess) {
      return (<ui.AccessDeniedMessage/>);
    }

    var iframeUrl = '';
    var report__base = '';
    var deployment__identifier = '';

    if (this.state.uid != undefined) {
      if (this.state.deployment__identifier != undefined) {
        deployment__identifier = this.state.deployment__identifier;
        report__base = deployment__identifier.replace('/forms/', '/reports/');
      }
      switch(this.props.location.pathname) {
        case `/forms/${this.state.uid}/data/report-legacy`:
          iframeUrl = report__base+'/digest.html';
          break;
        case `/forms/${this.state.uid}/data/table`:
          return <DataTable asset={this.state} />;
        case `/forms/${this.state.uid}/data/table-legacy`:
          iframeUrl = report__base+'/export.html';
          break;
        case `/forms/${this.state.uid}/data/gallery`:
          iframeUrl = deployment__identifier+'/photos';
          break;
        case `/forms/${this.state.uid}/data/map`:
          return <FormMap asset={this.state} />;
        case `/forms/${this.state.uid}/data/map/${this.props.params.viewby}`:
          return <FormMap asset={this.state} viewby={this.props.params.viewby}/>;
        case `/forms/${this.state.uid}/data/downloads`:
          return this.renderProjectDownloads();
        case `/forms/${this.state.uid}/settings`:
          return this.renderSettingsEditor();
        case `/forms/${this.state.uid}/settings/media`:
          iframeUrl = deployment__identifier+'/form_settings';
          break;
        case `/forms/${this.state.uid}/settings/sharing`:
          return this.renderSharing();
        case `/forms/${this.state.uid}/settings/rest`:
          return <RESTServices asset={this.state} />;
        case `/forms/${this.state.uid}/settings/rest/${this.props.params.hookUid}`:
          return <RESTServices asset={this.state} hookUid={this.props.params.hookUid}/>;
        case `/forms/${this.state.uid}/settings/kobocat`:
          iframeUrl = deployment__identifier+'/form_settings';
          break;
        case `/forms/${this.state.uid}/reset`:
          return this.renderReset();
      }
    }

    var docTitle = this.state.name || t('Untitled');

    return (
        <DocumentTitle title={`${docTitle} | KoboToolbox`}>
          <bem.FormView>
            <bem.FormView__cell m='iframe'>
              <iframe src={iframeUrl} />
            </bem.FormView__cell>
          </bem.FormView>
        </DocumentTitle>
      );
  }
  renderSettingsEditor() {
    var docTitle = this.state.name || t('Untitled');
    return (
        <DocumentTitle title={`${docTitle} | KoboToolbox`}>
          <bem.FormView m='form-settings'>
            <ProjectSettings
              context={PROJECT_SETTINGS_CONTEXTS.EXISTING}
              formAsset={this.state}
            />
          </bem.FormView>
        </DocumentTitle>
    );
  }
  renderProjectDownloads() {
    var docTitle = this.state.name || t('Untitled');
    return (
      <DocumentTitle title={`${docTitle} | KoboToolbox`}>
        <ProjectDownloads asset={this.state} />
      </DocumentTitle>
    );
  }
  renderSharing() {
    return (
      <bem.FormView m='form-settings-sharing'>
        <SharingForm uid={this.props.params.assetid} />
      </bem.FormView>
    );
  }
  renderReset() {
    return (
      <bem.Loading>
        <bem.Loading__inner>
          <i />
          {t('loading...')}
        </bem.Loading__inner>
      </bem.Loading>
    );
  }
}

reactMixin(FormSubScreens.prototype, Reflux.ListenerMixin);
reactMixin(FormSubScreens.prototype, mixins.dmix);
reactMixin(FormSubScreens.prototype, mixins.permissions);
reactMixin(FormSubScreens.prototype, mixins.contextRouter);

FormSubScreens.contextTypes = {
  router: PropTypes.object
};

export default FormSubScreens;
<commit_msg>Only owner can see settings/media<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import reactMixin from 'react-mixin';
import autoBind from 'react-autobind';
import Reflux from 'reflux';
import {actions} from '../actions';
import {bem} from '../bem';
import {stores} from '../stores';
import mixins from '../mixins';
import DocumentTitle from 'react-document-title';
import SharingForm from './permissions/sharingForm';
import ProjectSettings from './modalForms/projectSettings';
import DataTable from './table';
import ui from '../ui';
import {ProjectDownloads} from './formEditors';

import {PROJECT_SETTINGS_CONTEXTS} from '../constants';

import FormMap from './map';
import RESTServices from './RESTServices';

import {
  t
} from '../utils';

export class FormSubScreens extends React.Component {
  constructor(props){
    super(props);
    this.state = {};
    autoBind(this);
  }
  componentDidMount () {
    this.listenTo(stores.asset, this.dmixAssetStoreChange);
    var uid = this.props.params.assetid || this.props.uid || this.props.params.uid;
    if (this.props.randdelay && uid) {
      window.setTimeout(()=>{
        actions.resources.loadAsset({id: uid});
      }, Math.random() * 3000);
    } else if (uid) {
      actions.resources.loadAsset({id: uid});
    }
  }
  render () {
    let permAccess = this.userCan('view_submissions', this.state) || this.userCan('partial_submissions', this.state);

    if (!this.state.permissions)
      return false;

    if (this.props.location.pathname == `/forms/${this.state.uid}/settings` &&
        !this.userCan('change_asset', this.state)) {
      return (<ui.AccessDeniedMessage/>);
    }

    if (this.props.location.pathname == `/forms/${this.state.uid}/settings/rest` && !permAccess) {
      return (<ui.AccessDeniedMessage/>);
    }

    if (this.props.location.pathname == `/forms/${this.state.uid}/settings/media`) {
      return (<ui.AccessDeniedMessage/>);
    }

    var iframeUrl = '';
    var report__base = '';
    var deployment__identifier = '';

    if (this.state.uid != undefined) {
      if (this.state.deployment__identifier != undefined) {
        deployment__identifier = this.state.deployment__identifier;
        report__base = deployment__identifier.replace('/forms/', '/reports/');
      }
      switch(this.props.location.pathname) {
        case `/forms/${this.state.uid}/data/report-legacy`:
          iframeUrl = report__base+'/digest.html';
          break;
        case `/forms/${this.state.uid}/data/table`:
          return <DataTable asset={this.state} />;
        case `/forms/${this.state.uid}/data/table-legacy`:
          iframeUrl = report__base+'/export.html';
          break;
        case `/forms/${this.state.uid}/data/gallery`:
          iframeUrl = deployment__identifier+'/photos';
          break;
        case `/forms/${this.state.uid}/data/map`:
          return <FormMap asset={this.state} />;
        case `/forms/${this.state.uid}/data/map/${this.props.params.viewby}`:
          return <FormMap asset={this.state} viewby={this.props.params.viewby}/>;
        case `/forms/${this.state.uid}/data/downloads`:
          return this.renderProjectDownloads();
        case `/forms/${this.state.uid}/settings`:
          return this.renderSettingsEditor();
        case `/forms/${this.state.uid}/settings/media`:
          iframeUrl = deployment__identifier+'/form_settings';
          break;
        case `/forms/${this.state.uid}/settings/sharing`:
          return this.renderSharing();
        case `/forms/${this.state.uid}/settings/rest`:
          return <RESTServices asset={this.state} />;
        case `/forms/${this.state.uid}/settings/rest/${this.props.params.hookUid}`:
          return <RESTServices asset={this.state} hookUid={this.props.params.hookUid}/>;
        case `/forms/${this.state.uid}/settings/kobocat`:
          iframeUrl = deployment__identifier+'/form_settings';
          break;
        case `/forms/${this.state.uid}/reset`:
          return this.renderReset();
      }
    }

    var docTitle = this.state.name || t('Untitled');

    return (
        <DocumentTitle title={`${docTitle} | KoboToolbox`}>
          <bem.FormView>
            <bem.FormView__cell m='iframe'>
              <iframe src={iframeUrl} />
            </bem.FormView__cell>
          </bem.FormView>
        </DocumentTitle>
      );
  }
  renderSettingsEditor() {
    var docTitle = this.state.name || t('Untitled');
    return (
        <DocumentTitle title={`${docTitle} | KoboToolbox`}>
          <bem.FormView m='form-settings'>
            <ProjectSettings
              context={PROJECT_SETTINGS_CONTEXTS.EXISTING}
              formAsset={this.state}
            />
          </bem.FormView>
        </DocumentTitle>
    );
  }
  renderProjectDownloads() {
    var docTitle = this.state.name || t('Untitled');
    return (
      <DocumentTitle title={`${docTitle} | KoboToolbox`}>
        <ProjectDownloads asset={this.state} />
      </DocumentTitle>
    );
  }
  renderSharing() {
    return (
      <bem.FormView m='form-settings-sharing'>
        <SharingForm uid={this.props.params.assetid} />
      </bem.FormView>
    );
  }
  renderReset() {
    return (
      <bem.Loading>
        <bem.Loading__inner>
          <i />
          {t('loading...')}
        </bem.Loading__inner>
      </bem.Loading>
    );
  }
}

reactMixin(FormSubScreens.prototype, Reflux.ListenerMixin);
reactMixin(FormSubScreens.prototype, mixins.dmix);
reactMixin(FormSubScreens.prototype, mixins.permissions);
reactMixin(FormSubScreens.prototype, mixins.contextRouter);

FormSubScreens.contextTypes = {
  router: PropTypes.object
};

export default FormSubScreens;
<|endoftext|>


<commit_before>export default class Option {
  static of(value) {
    return isDefined(value) ? new Just(value) : new Nothing();
  }

  static from(generator, ...args) {
    const iterator = generator(...args);
  	let step;
    let value;

  	while (true) {
      step = iterator.next(value);

      if (step.done || !isDefined(step.value)) {
        iterator.return();
        break;
      }

      if (step.value instanceof Just) {
        value = step.value.valueOf();
      } else {
        value = step.value;
      }
  	}

  	return Option.of(step.value);
  }
}

export class Just {
  constructor(value) {
    this.value = value;
  }

  map(morphism) {
    return Option.of(morphism(this.value));
  }

  valueOf() {
    return this.value;
  }

  [Symbol.iterator]() {
    return new OptionIterator(this.value);
  }
}

export class Nothing {
  map() {
    return new Nothing();
  }

  valueOf() {
    return null;
  }

  [Symbol.iterator]() {
    return new OptionIterator(null);
  }
}

class OptionIterator {
  constructor(value) {
    this.value = value;
  }

  next() {
    return { value: this.value, done: true };
  }

  return() {
    return null;
  }

  throw() {
    return null;
  }
}

function isDefined(value) {
  return value !== null && value !== undefined && !(value instanceof Nothing);
}
<commit_msg>implement Option.match method<commit_after>export default class Option {
  static of(value) {
    return isDefined(value) ? new Just(value) : new Nothing();
  }

  static from(generator, ...args) {
    const iterator = generator(...args);
  	let step;
    let value;

  	while (true) {
      step = iterator.next(value);

      if (step.done || !isDefined(step.value)) {
        iterator.return();
        break;
      }

      // TODO: if Nothing — return Nothing immediately
      if (step.value instanceof Just) {
        value = step.value.valueOf();
      } else {
        value = step.value;
      }
  	}

  	return Option.of(step.value);
  }

  static match(value, matchers) {
    if (value instanceof Just) {
      return matchers.Just(value);
    }

    if (value instanceof Nothing) {
      return matchers.Nothing();
    }

    throw new Error(`Unable to match ${value}`);
  }
}

export class Just {
  constructor(value) {
    this.value = value;
  }

  map(morphism) {
    return Option.of(morphism(this.value));
  }

  valueOf() {
    return this.value;
  }

  [Symbol.iterator]() {
    return new OptionIterator(this.value);
  }
}

export class Nothing {
  map() {
    return new Nothing();
  }

  valueOf() {
    return null;
  }

  [Symbol.iterator]() {
    return new OptionIterator(null);
  }
}

class OptionIterator {
  constructor(value) {
    this.value = value;
  }

  next() {
    return { value: this.value, done: true };
  }

  return() {
    return null;
  }

  throw() {
    return null;
  }
}

function isDefined(value) {
  return value !== null && value !== undefined && !(value instanceof Nothing);
}
<|endoftext|>