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

    $(".view_more_comments").on("click",function() {

        var avatar = $(this).data('avatar');

        try {

            var numOfComments = $(".load_comment").find("div#show_comment");

            alert(numOfComments.size());

            $.ajax({

            url:'/comment',
            type:'GET',
            data:{'offset': 10},

            success: function(data) {

                for(i = 0 ; i < data.comments.length; i++)
                {
                    var comments = data.comments[i];

                    console.log("data", data.comments[i]);

                    $('#comment-count').html(' ' + numOfComments);

                     var newComment = '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '' + comments.comments + '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '

';

                     $('.load_comment').last().append(newComment);
                     $('#new-comment-field').val('');

                }
            }

        });

        } catch (e) {

            console.log(e);
        }

        return false;
    });

    $('.comment-submit').on('click', function() {

        var comment = $('#new-comment-field').val();
        var avatar = $(this).data('avatar');
        var comment_count = parseInt($(this).data('comment-count')) + 1;
        var token = $(this).data('token');

        var url = '/comment';
        var user_id = $('#user_id').val();
        var episode_id = $('#episode_id').val();

        var data = {
            parameter: {
                _token: token,
                episode_id: episode_id,
                comment: comment
            }
        }
        if (comment.length > 0) {
            //Process AJAX request
            $.ajax({
                url: url,
                type: 'POST',
                data: data.parameter,

                success: function(response) {

                    switch (response.status_code) {
                        case 200:

                            //Increment comment upon successful submission
                            $('#comment-count').html(' ' + comment_count);

                            var newComment = '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '' + comment + '';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '

';

                            $('.load_comment').last().append(newComment);
                            $('#new-comment-field').val('');

                            break;

                        default:
                            return false;
                    }
                }
            });
        }

        return false;
    });

});
<commit_msg>[feature #113846287] Load previous comments and append them to existing comments<commit_after>$(document).ready(function() {

    $(".view_more_comments").on("click",function() {

        var avatar = $(this).data('avatar');

        try {

            var numOfComments = $(".load_comment").find("div#show_comment");

            $.ajax({

            url:'/comment',
            type:'GET',
            data:{'offset': 10},

            success: function(data) {

                for (i = 0 ; i < data.comments.length; i++)
                {
                    var comments = data.comments[i];

                    console.log("data", data.comments[i]);

                    $('#comment-count').html(' ' + numOfComments);

                     var newComment = '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '' + comments.comments + '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '';
                     newComment    += '';
                     newComment    += '
';
                     newComment    += '
';
                     newComment    += '

';

                     $('.load_comment').last().append(newComment);
                     $('#new-comment-field').val('');

                }
            }

        });

        } catch (e) {

            console.log(e);
        }

        return false;
    });

    $('.comment-submit').on('click', function() {

        var comment = $('#new-comment-field').val();
        var avatar = $(this).data('avatar');
        var comment_count = parseInt($(this).data('comment-count')) + 1;
        var token = $(this).data('token');

        var url = '/comment';
        var user_id = $('#user_id').val();
        var episode_id = $('#episode_id').val();

        var data = {
            parameter: {
                _token: token,
                episode_id: episode_id,
                comment: comment
            }
        }
        if (comment.length > 0) {
            //Process AJAX request
            $.ajax({
                url: url,
                type: 'POST',
                data: data.parameter,

                success: function(response) {

                    switch (response.status_code) {
                        case 200:

                            //Increment comment upon successful submission
                            $('#comment-count').html(' ' + comment_count);

                            var newComment = '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '
';
                            newComment += '' + comment + '';
                            newComment += '
';
                            newComment += '';
                            newComment += '
';
                            newComment += '';
                            newComment += '';
                            newComment += '
';
                            newComment += '
';
                            newComment += '

';

                            $('.load_comment').last().append(newComment);
                            $('#new-comment-field').val('');

                            break;

                        default:
                            return false;
                    }
                }
            });
        }

        return false;
    });

});
<|endoftext|>


<commit_before>$(document).ready(function() {
	$('#yearInSchoolDropdown').change(function() {
		console.log($(this).val());
	});

	$('#autocomplete-input-uniName').uniInput(function()){
		console.log($(this).val());
	});
});

<commit_msg>Fixing Ben's endless mistakes<commit_after>$(document).ready(function() {
	$('#yearInSchoolDropdown').change(function() {
		console.log($(this).val());
	});

	$('#autocomplete-input-uniName').uniInput(function() {
		console.log($(this).val());
	});
});
<|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey
 * http://scratchdisk.com/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

 /**
  * @name Component
  * @class
  */
var Component = Base.extend(Callback, /** @lends Component# */{
    _class: 'Component',
    _events: [ 'onChange', 'onClick' ],

    // DOCS: All!

    // Meta-information, by type. This is stored in _meta on the components.
    _types: {
        'boolean': {
            type: 'checkbox',
            value: 'checked'
        },

        string: {
            type: 'text'
        },

        number: {
            type: 'number',
            number: true
        },

        button: {
            type: 'button'
        },

        text: {
            tag: 'div',
            // This will return the native textContent through DomElement.get():
            value: 'text'
        },

        slider: {
            type: 'range',
            number: true
        },

        list: {
            tag: 'select',

            setOptions: function() {
                DomElement.removeChildren(this._input);
                DomElement.create(Base.each(this._options, function(option) {
                    this.push('option', { value: option, text: option });
                }, []), this._input);
            }
        },

        color: {
            type: 'color',

            getValue: function(value) {
                // Always convert internal string representation back to a
                // paper.js color object.
                return new Color(value);
            },

            setValue: function(value) {
                // Only enfore hex values if the input field is indeed of
                // color type. This allows sketch.paperjs.org to plug in
                // the Spectrum.js library with alpha support.
                return new Color(value).toCSS(
                        DomElement.get(this._input, 'type') === 'color');
            }
        },

        row: {}
    },

    // Default values for internals
    _visible: true,
    _enabled: true,

    initialize: function Component(pane, name, props, value, row, parent) {
        if (value === undefined)
            value = props.value;
        if (!name)
            name = 'component-' + this._id,
        this._id = Component._id = (Component._id || 0) + 1;
        this._pane = pane;
        this._name = name;
        this._row = row;
        this._parent = parent; // The parent component, if any.
        var type = this._type = props.type in this._types
                ? props.type
                : 'options' in props
                    ? 'list'
                    : 'onClick' in props
                        ? 'button'
                        : typeof value,
            meta = this._meta = this._types[type] || { type: type },
            that = this,
            create = DomElement.create;
        if (type === 'row') {
            var components = this._components = [];
            for (var key in props) {
                var entry = props[key];
                if (Base.isPlainObject(entry))
                    components.push(new Component(pane, key, entry,
                            pane._values[key], row, this));
            }
            pane._maxComponents = Math.max(components.length,
                    pane._maxComponents || 0);
        } else {
            DomElement.addChildren(row, [
                this._labelCell = create('td', {
                    class: 'palettejs-label',
                    id: 'palettejs-label-' + name
                }),
                this._inputCell = create('td', {
                    class: 'palettejs-input',
                    id: 'palettejs-input-' + name
                }, [
                    this._input = create(meta.tag || 'input', {
                        type: meta.type,
                        events: {
                            change: function() {
                                that.setValue(DomElement.get(this,
                                        meta.value || 'value'));
                            },
                            click: function() {
                                that.fire('click');
                            }
                        }
                    })
                ])
            ]);
        }
        // Attach default 'change' even that delegates to palette
        this.attach('change', function(value) {
            if (!this._dontFire)
                pane.fire('change', this, this._name, value);
        });
        this._dontFire = true;
        // Now that everything is set up, copy over values fro, props.
        // NOTE: This triggers setters, which is why we set _dontFire = true,
        // and why we can only call this after everything else is set up (e.g.
        // setLabel() requires this._labelCell).
        // Exclude name because it's already set, and value since we want to set
        // it after range.
        Base.set(this, props, { name: true, value: true });
        this.setValue(value);
        // Start firing change events after we have initialized.
        this._dontFire = false;
        //  Store link to component in the pane's components object.
        pane._components[name] = this;
        // Make sure each component has an entry in values also, so observers
        // get installed correctly in the Pane constructor.
        pane._values[name] = this._defaultValue = this._value;
    },

    getType: function() {
        return this._type;
    },

    getName: function() {
        return this._name;
    },

    getLabel: function() {
        return this._label;
    },

    setLabel: function(label) {
        this._label = label;
        DomElement.set(this._labelNode = this._labelNode
                || this._labelCell.appendChild(DomElement.create('label',
                    { 'for': 'palettejs-input-' + this._name })),
                'text', label);
    },

    getSuffix: function() {
        return this._suffix;
    },

    setSuffix: function(suffix) {
        this._suffix = suffix;
        DomElement.set(this._suffixNode = this._suffixNode
                || this._inputCell.appendChild(DomElement.create('label',
                    { 'for': 'palettejs-input-' + this._name })),
                'text', suffix);
    },

    getOptions: function() {
        return this._options;
    },

    setOptions: function(options) {
        this._options = options;
        var setOptions = this._meta.setOptions;
        if (setOptions)
            setOptions.call(this);
    },

    getValue: function() {
        var value = this._value,
            getValue = this._meta.getValue;
        return getValue ? getValue.call(this, value) : value;
    },

    setValue: function(value) {
        var meta = this._meta,
            key = meta.value || 'value',
            setValue = meta.setValue;
        if (setValue)
            value = setValue.call(this, value);
        DomElement.set(this._input, key, value);
        // Read back and convert from input again, to make sure we're in sync
        value = DomElement.get(this._input, key);
        if (meta.number)
            value = parseFloat(value, 10);
        if (this._value !== value) {
            this._value = value;
            if (!this._dontFire)
                this.fire('change', this.getValue());
        }
    },

    getVisible: function() {
        return this._visible;
    },

    setVisible: function(visible) {
        // NOTE: Only set the visibility of the whole row if this is a row item,
        // in which case this._input is not defined.
        DomElement.toggleClass(this._inputCell || this._row, 'hidden', !visible);
        DomElement.toggleClass(this._labelCell, 'hidden', !visible);
        this._visible = !!visible;
    },

    getEnabled: function() {
        return this._enabled;
    },

    setEnabled: function(enabled, _fromPalette) {
        if (_fromPalette) {
            // When called from Palette#setEnabled, we have to remember the
            // component's previous enabled state when disabling the palette,
            // so we can restore it when enabling the palette again.
            var prev = Base.pick(this._previousEnabled, this._enabled);
            this._previousEnabled = enabled ? undefined : prev; // clear
            enabled = enabled && prev;
        }
        DomElement.set(this._input, 'disabled', !enabled);
        this._enabled = !!enabled;
    },

    getRange: function() {
        return [parseFloat(DomElement.get(this._input, 'min')),
                parseFloat(DomElement.get(this._input, 'max'))];
    },

    setRange: function(min, max) {
        var range = Array.isArray(min) ? min : [min, max];
        DomElement.set(this._input, { min: range[0], max: range[1] });
    },

    getMin: function() {
        return this.getRange()[0];
    },

    setMin: function(min) {
        this.setRange(min, this.getMax());
    },

    getMax: function() {
        return this.getRange()[1];
    },

    setMax: function(max) {
        this.setRange(this.getMin(), max);
    },

    getStep: function() {
        return parseFloat(DomElement.get(this._input, 'step'));
    },

    setStep: function(step) {
        DomElement.set(this._input, 'step', step);
    },

    reset: function() {
        this.setValue(this._defaultValue);
    }
});
<commit_msg>Fix palette labels and improve CSS id / class structure.<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey
 * http://scratchdisk.com/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

 /**
  * @name Component
  * @class
  */
var Component = Base.extend(Callback, /** @lends Component# */{
    _class: 'Component',
    _events: [ 'onChange', 'onClick' ],

    // DOCS: All!

    // Meta-information, by type. This is stored in _meta on the components.
    _types: {
        'boolean': {
            type: 'checkbox',
            value: 'checked'
        },

        string: {
            type: 'text'
        },

        number: {
            type: 'number',
            number: true
        },

        button: {
            type: 'button'
        },

        text: {
            tag: 'div',
            // This will return the native textContent through DomElement.get():
            value: 'text'
        },

        slider: {
            type: 'range',
            number: true
        },

        list: {
            tag: 'select',

            setOptions: function() {
                DomElement.removeChildren(this._input);
                DomElement.create(Base.each(this._options, function(option) {
                    this.push('option', { value: option, text: option });
                }, []), this._input);
            }
        },

        color: {
            type: 'color',

            getValue: function(value) {
                // Always convert internal string representation back to a
                // paper.js color object.
                return new Color(value);
            },

            setValue: function(value) {
                // Only enfore hex values if the input field is indeed of
                // color type. This allows sketch.paperjs.org to plug in
                // the Spectrum.js library with alpha support.
                return new Color(value).toCSS(
                        DomElement.get(this._input, 'type') === 'color');
            }
        },

        row: {}
    },

    // Default values for internals
    _visible: true,
    _enabled: true,

    initialize: function Component(pane, name, props, value, row, parent) {
        if (value === undefined)
            value = props.value;
        if (!name)
            name = 'component-' + this._id,
        this._id = Component._id = (Component._id || 0) + 1;
        this._pane = pane;
        this._name = name;
        this._row = row;
        this._parent = parent; // The parent component, if any.
        this._nested = !!parent;
        var type = this._type = props.type in this._types
                ? props.type
                : 'options' in props
                    ? 'list'
                    : 'onClick' in props
                        ? 'button'
                        : typeof value,
            meta = this._meta = this._types[type] || { type: type },
            that = this,
            create = DomElement.create;
        if (type === 'row') {
            var components = this._components = [];
            for (var key in props) {
                var entry = props[key];
                if (Base.isPlainObject(entry))
                    components.push(new Component(pane, key, entry,
                            pane._values[key], row, this));
            }
            pane._numCells = Math.max(components.length * 2, pane._numCells || 0);
        } else {
            DomElement.addChildren(row, [
                this._labelCell = create('td', {
                    class: 'palettejs-label',
                    id: 'palettejs-label-' + name
                }),
                this._cell = create('td', {
                    class: 'palettejs-component',
                    id: 'palettejs-component-' + name
                }, [
                    this._input = create(meta.tag || 'input', {
                        class: 'palettejs-input',
                        id: 'palettejs-input-' + name,
                        type: meta.type,
                        events: {
                            change: function() {
                                that.setValue(DomElement.get(this,
                                        meta.value || 'value'));
                            },
                            click: function() {
                                that.fire('click');
                            }
                        }
                    })
                ])
            ]);
        }
        // Attach default 'change' even that delegates to palette
        this.attach('change', function(value) {
            if (!this._dontFire)
                pane.fire('change', this, this._name, value);
        });
        this._dontFire = true;
        // Now that everything is set up, copy over values fro, props.
        // NOTE: This triggers setters, which is why we set _dontFire = true,
        // and why we can only call this after everything else is set up (e.g.
        // setLabel() requires this._labelCell).
        // Exclude name because it's already set, and value since we want to set
        // it after range.
        Base.set(this, props, { name: true, value: true });
        this.setValue(value);
        // Start firing change events after we have initialized.
        this._dontFire = false;
        //  Store link to component in the pane's components object.
        pane._components[name] = this;
        // Make sure each component has an entry in values also, so observers
        // get installed correctly in the Pane constructor.
        pane._values[name] = this._defaultValue = this._value;
    },

    getType: function() {
        return this._type;
    },

    getName: function() {
        return this._name;
    },

    _setLabel: function(label, nodeName, parent) {
        this[nodeName] = DomElement.set(this[nodeName]
                || parent.appendChild(DomElement.create('label',
                    { 'for': 'palettejs-input-' + this._name })),
                'text', label);
    },

    getLabel: function() {
        return this._label;
    },

    setLabel: function(label) {
        this._label = label;
        this._setLabel(label, '_labelNode', this._labelCell);
    },

    getSuffix: function() {
        return this._suffix;
    },

    setSuffix: function(suffix) {
        this._suffix = suffix;
        this._setLabel(label, '_suffixNode', this._cell);
    },

    getOptions: function() {
        return this._options;
    },

    setOptions: function(options) {
        this._options = options;
        var setOptions = this._meta.setOptions;
        if (setOptions)
            setOptions.call(this);
    },

    getValue: function() {
        var value = this._value,
            getValue = this._meta.getValue;
        return getValue ? getValue.call(this, value) : value;
    },

    setValue: function(value) {
        var meta = this._meta,
            key = meta.value || 'value',
            setValue = meta.setValue;
        if (setValue)
            value = setValue.call(this, value);
        DomElement.set(this._input, key, value);
        // Read back and convert from input again, to make sure we're in sync
        value = DomElement.get(this._input, key);
        if (meta.number)
            value = parseFloat(value, 10);
        if (this._value !== value) {
            this._value = value;
            if (!this._dontFire)
                this.fire('change', this.getValue());
        }
    },

    getVisible: function() {
        return this._visible;
    },

    setVisible: function(visible) {
        // NOTE: Only set the visibility of the whole row if this is a row item,
        // in which case this._input is not defined.
        DomElement.toggleClass(this._cell || this._row, 'hidden', !visible);
        DomElement.toggleClass(this._labelCell, 'hidden', !visible);
        this._visible = !!visible;
    },

    getEnabled: function() {
        return this._enabled;
    },

    setEnabled: function(enabled, _fromPalette) {
        if (_fromPalette) {
            // When called from Palette#setEnabled, we have to remember the
            // component's previous enabled state when disabling the palette,
            // so we can restore it when enabling the palette again.
            var prev = Base.pick(this._previousEnabled, this._enabled);
            this._previousEnabled = enabled ? undefined : prev; // clear
            enabled = enabled && prev;
        }
        DomElement.set(this._input, 'disabled', !enabled);
        this._enabled = !!enabled;
    },

    getRange: function() {
        return [parseFloat(DomElement.get(this._input, 'min')),
                parseFloat(DomElement.get(this._input, 'max'))];
    },

    setRange: function(min, max) {
        var range = Array.isArray(min) ? min : [min, max];
        DomElement.set(this._input, { min: range[0], max: range[1] });
    },

    getMin: function() {
        return this.getRange()[0];
    },

    setMin: function(min) {
        this.setRange(min, this.getMax());
    },

    getMax: function() {
        return this.getRange()[1];
    },

    setMax: function(max) {
        this.setRange(this.getMin(), max);
    },

    getStep: function() {
        return parseFloat(DomElement.get(this._input, 'step'));
    },

    setStep: function(step) {
        DomElement.set(this._input, 'step', step);
    },

    reset: function() {
        this.setValue(this._defaultValue);
    }
});
<|endoftext|>


<commit_before>$(function() {

function NewProperty(propName, bed, price, pets, location, imageName, description) {
    this.propName = propName;
    this.bed = bed;
    this.price = price;
    this.pets = pets;
    this.location = location;
    this.imageName = imageName;
    this.description = description;
  }

NewProperty.prototype.toHtml = function() {
  return '

' + this.propName + '

$ ' + this.price + '

Beds: ' + this.bed + '

Pets Allowed: ' + this.pets + '

'
}

var addProperty = function(propName, bed, price, pets, location, imageName, description) {
    var property = new NewProperty(propName, bed, price, pets, location, imageName, description);
    $("#listings").append(property.toHtml());
  }

addProperty("Trendy Apartment",     0, 1100, "Yes", "Seattle",      "property1.jpg",  "This is a dope ass apartment");
addProperty("Total Dive",           0, 1800, "No",  "Capitol-Hill", "property2.jpg",  "This place is horrifically dirty but if you're a tough sob it'll do.");
addProperty("Charming Space",       0, 950,  "Yes", "Renton",       "property3.jpg",  "Cute little apartment in the heart of of Renton.");
addProperty("Modern Lodge",         2, 1800, "Yes",  "Renton",       "property4.jpg",  "It's old and creeky but it looks cool!");
addProperty("Fremont Manor",        3, 2100, "Yes", "Fremont",      "property5.jpg",  "Group living at its best. And optional orgies every Tuesday night.");
addProperty("The Love Pad",         1, 750,  "Yes", "Capitol-Hill", "property6.jpg",  "Only the sexy need apply");
addProperty("Castle",               1, 850,  "Yes",  "Seattle",      "property7.jpg",  "It's a castle, 'nuff said. Rent it and be a baller who live in a castle.");
addProperty("Capitol-Hill Home",    2, 5000, "No",  "Capitol-Hill", "property8.jpg",  "Great house in a friendly neighbourhood.");
addProperty("Room from Saw",        1, 300,  "Yes",  "Renton",       "property9.jpg",  "This place is comparable to a nightmare, you won't be able to sleep much.");
addProperty("Pope's Palace",        1, 1800, "No",  "Seattle",      "property10.jpg", "Availability is extremely limited but it's a wonderful space if you are accepted.");
addProperty("Survivor Hut",         0, 200,  "No",  "Fremont",      "property11.jpg", "Test your wit and deception by living underneath this leaf hut.");
addProperty("Homey Home",           3, 1750, "No",  "Capitol-Hill", "property12.jpg", "Spacious and loving home perfect for a close group of friends.");
addProperty("Haunted House",        2, 1100, "No",  "Capitol-Hill",  "property13.jpg", "Frequently frequented by ghoules and ghosts but other than that it is a wonderful house.");
addProperty("Trendy Space",         3, 1700, "Yes",  "Renton",       "property14.jpg", "This place is perfect for hipsters.");
addProperty("The Shire",            1, 5000,  "No",  "Seattle",      "property15.jpg", "Stay warm in the winter and cool in the summer while living under this cozy grassy knoll. ");
addProperty("Cozy Igloo",           2, 750,  "No",  "Seattle",      "property16.jpg", "This place is great eh!");
addProperty("Master suite",         0, 1250, "No",  "Fremont",      "property17.jpg", "Upscale and very fancy. Only rich people who walk their cats will be accepted.");
addProperty("Cool Apartment",       2, 1200, "No",  "Seattle",      "property18.jpg", "It's pretty cool so you should apply quickly.");
addProperty("Renton Home",          3, 1900, "Yes",  "Renton",       "property19.jpg", "Big home with lots of bathrooms and a hot tub time machine.");
addProperty("Biggest Loser House",  3, 2100, "No",  "Fremont",      "property20.jpg", "Get temporarily fit in this intense living arrangement. Only +300 pounders need apply.");

if (localStorage.getItem !== null) {
    // JSON.parse(localStorage.getItem("userLocation")).location
    $("#locationSelect").val(JSON.parse(localStorage.getItem("userLocation")).location)
    // JSON.parse(localStorage.getItem("userBeds")).beds
    $("#bed").val(JSON.parse(localStorage.getItem("userBeds")).beds)
    }
//~~~~~~~~~~~~ FILTERS START HERE!!!!!!!!!!!!!!!!!! ~~~~~~~~~~~~~~~~

/* this function is used for a basic filter search by the user. The user only searches using the city drop down list */
  function locationSearch() {
      localStorage.setItem('userLocation', JSON.stringify({
        location: document.getElementById("locationSelect").value
      }));
    $(".propertyBox").each(function() {
      if (($(this).data("location")) != ($("#locationSelect").val())) {
          $(this).fadeOut(1000);
      }
      if ($("input:checkbox").is(":checked")) {
        //call this function only if checkbox is selected
        petCheckbox();
      }
      if ($("#bed option:selected")) {
        //call this function if bed selector is selected
        bedSelector();
      }
      if (($("#min-price").val() != "") || ($("#max-price").val() != "")) {
        //call this function if input text has values
        priceFilter();
        // console.log("i'm working");
      }

    });
  }
  /*this function will be called if user selects checkbox that states
  he or she owns a pet and would like to filter the apartment listings based off pet availability*/
  function petCheckbox() {
    $(".propertyBox").each(function() {
      if ($(this).data("pets") != "Yes") {
        $(this).fadeOut(1000);
      }
    });
  }
  /*this function will be called in the locationSearch function. depending on the user's selection, a specific case will be run. */
  function bedSelector() {
    localStorage.setItem('userBeds', JSON.stringify({
      beds : document.getElementById("bed").value
    }));
    $(".propertyBox").each(function() {
      if ($(this).data("bed") != ($("#bed").val())) {
        $(this).fadeOut(1000);
      }
    });
  }

/*this function is to filter listings based off of the user's minimum price and maximum price that are placed in the input text element */
  function priceFilter() {
    //get the value for each input text: Min Price & Max Price
    var minPrice = document.getElementById('min-price').value;
    var maxPrice = document.getElementById('max-price').value;

    $(".propertyBox").each(function() {
      if ($(this).data("price") < minPrice && minPrice != "") {
        $(this).fadeOut(1000);
      }
      if ($(this).data("price") > maxPrice && maxPrice != "") {
        $(this).fadeOut(1000);
      }
    });
  }

  $("#list").on("click", locationSearch);
});
<commit_msg>testing 3<commit_after>$(function() {

function NewProperty(propName, bed, price, pets, location, imageName, description) {
    this.propName = propName;
    this.bed = bed;
    this.price = price;
    this.pets = pets;
    this.location = location;
    this.imageName = imageName;
    this.description = description;
  }

NewProperty.prototype.toHtml = function() {
  return '

' + this.propName + '

$ ' + this.price + '

Beds: ' + this.bed + '

Pets Allowed: ' + this.pets + '

'
}

var addProperty = function(propName, bed, price, pets, location, imageName, description) {
    var property = new NewProperty(propName, bed, price, pets, location, imageName, description);
    $("#listings").append(property.toHtml());
  }

addProperty("Trendy Apartment",     0, 1100, "Yes", "Seattle",      "property1.jpg",  "This is a dope ass apartment");
addProperty("Total Dive",           0, 1800, "No",  "Capitol-Hill", "property2.jpg",  "This place is horrifically dirty but if you're a tough sob it'll do.");
addProperty("Charming Space",       0, 950,  "Yes", "Renton",       "property3.jpg",  "Cute little apartment in the heart of of Renton.");
addProperty("Modern Lodge",         2, 1800, "Yes",  "Renton",       "property4.jpg",  "It's old and creeky but it looks cool!");
addProperty("Fremont Manor",        3, 2100, "Yes", "Fremont",      "property5.jpg",  "Group living at its best. And optional orgies every Tuesday night.");
addProperty("The Love Pad",         1, 750,  "Yes", "Capitol-Hill", "property6.jpg",  "Only the sexy need apply");
addProperty("Castle",               1, 850,  "Yes",  "Seattle",      "property7.jpg",  "It's a castle, 'nuff said. Rent it and be a baller who live in a castle.");
addProperty("Capitol-Hill Home",    2, 5000, "No",  "Capitol-Hill", "property8.jpg",  "Great house in a friendly neighbourhood.");
addProperty("Room from Saw",        1, 300,  "Yes",  "Renton",       "property9.jpg",  "This place is comparable to a nightmare, you won't be able to sleep much.");
addProperty("Pope's Palace",        1, 1800, "No",  "Seattle",      "property10.jpg", "Availability is extremely limited but it's a wonderful space if you are accepted.");
addProperty("Survivor Hut",         0, 200,  "No",  "Fremont",      "property11.jpg", "Test your wit and deception by living underneath this leaf hut.");
addProperty("Homey Home",           3, 1750, "No",  "Capitol-Hill", "property12.jpg", "Spacious and loving home perfect for a close group of friends.");
addProperty("Haunted House",        2, 1100, "No",  "Capitol-Hill",  "property13.jpg", "Frequently frequented by ghoules and ghosts but other than that it is a wonderful house.");
addProperty("Trendy Space",         3, 1700, "Yes",  "Renton",       "property14.jpg", "This place is perfect for hipsters.");
addProperty("The Shire",            1, 5000,  "No",  "Seattle",      "property15.jpg", "Stay warm in the winter and cool in the summer while living under this cozy grassy knoll. ");
addProperty("Cozy Igloo",           2, 750,  "No",  "Seattle",      "property16.jpg", "This place is great eh!");
addProperty("Master suite",         0, 1250, "No",  "Fremont",      "property17.jpg", "Upscale and very fancy. Only rich people who walk their cats will be accepted.");
addProperty("Cool Apartment",       2, 1200, "No",  "Seattle",      "property18.jpg", "It's pretty cool so you should apply quickly.");
addProperty("Renton Home",          3, 1900, "Yes",  "Renton",       "property19.jpg", "Big home with lots of bathrooms and a hot tub time machine.");
addProperty("Biggest Loser House",  3, 2100, "No",  "Fremont",      "property20.jpg", "Get temporarily fit in this intense living arrangement. Only +300 pounders need apply.");

if (localStorage.getItem == null) {
    // JSON.parse(localStorage.getItem("userLocation")).location
    $("#locationSelect").val(JSON.parse(localStorage.getItem("userLocation")).location)
    // JSON.parse(localStorage.getItem("userBeds")).beds
    $("#bed").val(JSON.parse(localStorage.getItem("userBeds")).beds)
    }
//~~~~~~~~~~~~ FILTERS START HERE!!!!!!!!!!!!!!!!!! ~~~~~~~~~~~~~~~~

/* this function is used for a basic filter search by the user. The user only searches using the city drop down list */
  function locationSearch() {
      localStorage.setItem('userLocation', JSON.stringify({
        location: document.getElementById("locationSelect").value
      }));
    $(".propertyBox").each(function() {
      if (($(this).data("location")) != ($("#locationSelect").val())) {
          $(this).fadeOut(1000);
      }
      if ($("input:checkbox").is(":checked")) {
        //call this function only if checkbox is selected
        petCheckbox();
      }
      if ($("#bed option:selected")) {
        //call this function if bed selector is selected
        bedSelector();
      }
      if (($("#min-price").val() != "") || ($("#max-price").val() != "")) {
        //call this function if input text has values
        priceFilter();
        // console.log("i'm working");
      }

    });
  }
  /*this function will be called if user selects checkbox that states
  he or she owns a pet and would like to filter the apartment listings based off pet availability*/
  function petCheckbox() {
    $(".propertyBox").each(function() {
      if ($(this).data("pets") != "Yes") {
        $(this).fadeOut(1000);
      }
    });
  }
  /*this function will be called in the locationSearch function. depending on the user's selection, a specific case will be run. */
  function bedSelector() {
    localStorage.setItem('userBeds', JSON.stringify({
      beds : document.getElementById("bed").value
    }));
    $(".propertyBox").each(function() {
      if ($(this).data("bed") != ($("#bed").val())) {
        $(this).fadeOut(1000);
      }
    });
  }

/*this function is to filter listings based off of the user's minimum price and maximum price that are placed in the input text element */
  function priceFilter() {
    //get the value for each input text: Min Price & Max Price
    var minPrice = document.getElementById('min-price').value;
    var maxPrice = document.getElementById('max-price').value;

    $(".propertyBox").each(function() {
      if ($(this).data("price") < minPrice && minPrice != "") {
        $(this).fadeOut(1000);
      }
      if ($(this).data("price") > maxPrice && maxPrice != "") {
        $(this).fadeOut(1000);
      }
    });
  }

  $("#list").on("click", locationSearch);
});
<|endoftext|>


<commit_before>var React = require('react/addons'),
	classnames = require('classnames');

module.exports = React.createClass({
	displayName: 'ItemMedia',
	propTypes: {
		avatar: React.PropTypes.string,
		avatarInitials: React.PropTypes.string,
		className: React.PropTypes.string,
		icon: React.PropTypes.string,
		thumbnail: React.PropTypes.string
	},

	render () {
		var className = classnames({
			'Item__media': true,
			'Item__media--icon': this.props.icon,
			'Item__media--avatar': this.props.avatar || this.props.avatarInitials,
			'Item__media--thumbnail': this.props.thumbnail
		}, this.props.className);

		// media types
		var icon = this.props.icon ? (

		) : null;
		var avatar = this.props.avatar || this.props.avatarInitials ? (

				{this.props.avatar ?  : this.props.avatarInitials}

		) : null;
		var thumbnail = this.props.thumbnail ? (

		) : null;

		return (

				{icon}
				{avatar}
				{thumbnail}

		);
	}
});
<commit_msg>more happiness nits<commit_after>var React = require('react/addons');
var classnames = require('classnames');

module.exports = React.createClass({
	displayName: 'ItemMedia',
	propTypes: {
		avatar: React.PropTypes.string,
		avatarInitials: React.PropTypes.string,
		className: React.PropTypes.string,
		icon: React.PropTypes.string,
		thumbnail: React.PropTypes.string
	},

	render () {
		var className = classnames({
			'Item__media': true,
			'Item__media--icon': this.props.icon,
			'Item__media--avatar': this.props.avatar || this.props.avatarInitials,
			'Item__media--thumbnail': this.props.thumbnail
		}, this.props.className);

		// media types
		var icon = this.props.icon ? (

		) : null;
		var avatar = this.props.avatar || this.props.avatarInitials ? (

				{this.props.avatar ?  : this.props.avatarInitials}

		) : null;
		var thumbnail = this.props.thumbnail ? (

		) : null;

		return (

				{icon}
				{avatar}
				{thumbnail}

		);
	}
});
<|endoftext|>


<commit_before>

var mapping = {
  mapDiv:"",
  map:{},
  currentCoords:{
    latitude:51.505,
    longitude: -0.09
  },

  create: function (mapDiv){
    this.mapDiv=mapDiv;
    this.setPosition();
    this.drawMap();
  },

  drawMap:function(){
    this.map = L.map('mapid').setView([this.currentCoords.latitude,this.currentCoords.longitude], 13);
    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(this.map);
  },

  setPosition: function (){
    var me = this;
    if (navigator.geolocation) {
      // Get the user's current position
      navigator.geolocation.getCurrentPosition(
        function(position){
          me.coords = position.coords;
        }, function(){
          alert("your browser doesn't support geolocation, defaulting to London");
          this.coords = {
            latitude:51.505,
            longitude: -0.09
          };
        }
      );
    } else {
      alert('Geolocation is not supported in your browser');
    }
  },

  showSomethingAtPosition : function (position, text){
    //L.marker([51.5, -0.09]).addTo(map).bindPopup('manual popup');
    L.marker([position.latitude,position.longitude]).addTo(map).bindPopup(text);
  }
};
<commit_msg>mapping now works. Class with a constructor.<commit_after>var Mapping = function (mapDiv){
  this.mapDiv = mapDiv;
  this.map = {};
  this.currentCoords = {
    latitude:51.505,
    longitude: -0.09
  };
  this.drawMap();
  this.setPosition();
};

Mapping.prototype.create = function (){
  this.setPosition();
  this.drawMap();
};

Mapping.prototype.drawMap = function(){
  this.map = L.map('mapid').setView([this.currentCoords.latitude,this.currentCoords.longitude], 13);
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors'
  }).addTo(this.map);
};

Mapping.prototype.setPosition = function (){
  var me = this;
  if (navigator.geolocation) {
    // Get the user's current position
    navigator.geolocation.getCurrentPosition(
      function(position){
        me.coords = position.coords;
        me.moveTo(position.coords);
      }, function(){
        alert("your browser doesn't support geolocation, defaulting to London");
        this.coords = {
          latitude:51.505,
          longitude: -0.09
        };
      }
    );
  } else {
    alert('Geolocation is not supported in your browser');
  }
};

Mapping.prototype.moveTo = function (coords){
  this.map.setView([coords.latitude,coords.longitude]);
};

Mapping.prototype.showSomethingAtPosition = function (position, text){
  //L.marker([51.5, -0.09]).addTo(map).bindPopup('manual popup');
  L.marker([position.latitude,position.longitude]).addTo(map).bindPopup(text);
};
<|endoftext|>


<commit_before>function mostrar() {
  var tinteres = 0;
  var vprincipal = 0;
  var bandera = false;
    if( $("#cajita").is(':checked')){
      bandera = true;
    }
    var x = parseInt($("#droplistbox").val());
    if(parseInt($("#tasainteres").val())<0 || parseInt($("#tasainteres").val())>100){
      alert("Por favor inserta una tasa de interés válida");
      return;
    }else if($("#principal").val()!=""){
      tinteres = parseInt($("#tasainteres").val());
    }
    if($("#principal").val()!=""){
      vprincipal = parseInt($("#principal").val());
      $("#cajita").prop('checked', true);
      bandera = true;
    }
    agregar(x,bandera,vprincipal);
}

function agregar(limite,bandera,principal){
  var codigo='

PERIOD

OUTFLOWS

INFLOWS

CUMULATIVE CASH FLOW

';
  if(bandera){
    codigo +='

0
<input type="number" class="col-md-4" id="outflow0" value="'+principal+'"><input type="number" class="col-md-4" id="inflow0"><input type="number" class="col-md-3" id="comulativecash0" disabled>

';
  }
  for(i=1;i<limite+1;i++){
    codigo += '

'+i+'
<input type="number" class="col-md-4" id="outflow'+i+'"><input type="number" class="col-md-4" id="inflow'+i+'"><input type="number" class="col-md-3" id="comulativecash'+i+'" disabled>

';
  }
  codigo+='

<button type="button" class="btn btn-default" onclick="imprimirresultados()">Show payback period</button>

<input type="number" class="col-md-5" id="netpresentvalue" disabled>

'
  $("#contenedor").html(codigo);
}

function valores(){
    var returnPeriod = -1
    var interest = parseFloat($("#tasainteres").val()) / 100;
    var length = parseInt($("#droplistbox").val());
    var inflow = parseFloat($("#inflow0").val());
    var outflow = parseFloat($("#outflow0").val());

    if (isNaN(inflow)) {
      inflow = 0;
    }

    if (isNaN(outflow)) {
      outflow = 0;
    }

    var net = inflow - outflow;
    var COF = 0;
    var cum = net;

    // Set cumulative de period 0.
    $("#comulativecash0").val(cum);

    if (isNaN(interest)) {
      interest = 0;
    }

    // Recorrer desde 1 hasta length.
    for (var i = 1; i < length + 1; i++) {

        // Calcular net (inflow - outflow)
        inflow = parseFloat($('#inflow' + i).val());
        outflow = parseFloat($('#outflow' + i).val());

        if (isNaN(inflow)) {
          inflow = 0;
        }

        if (isNaN(outflow)) {
          outflow = 0;
        }

        //console.log(inflow);
        //console.log(outflow);

        net = inflow - outflow;

        // Calcular COF
        if (cum < 0) {
            COF = cum * interest;
        } else {
            COF = 0;
        }

        // Calcular Cumulative.
        cum += (net + COF);

        if (cum >= 0 && returnPeriod == -1) {
          returnPeriod = i;
        }

        // Set net and cumulative.
        $('#comulativecash' + i).val(cum);
    }
    return returnPeriod;
}

function imprimirresultados() {
    var returnPeriod = valores();
    $("#netpresentvalue").val(returnPeriod);
}
function netcashflow(inflow, outflow) {
  return inflow - outflow;
}

function printpdf(){
  var x = parseInt($("#droplistbox").val());
  var url ="http://generatepdf-ddnsnet.rhcloud.com/?periods="+x;
  contenedoroutflow = "&outflow[]=a";
  contenedorinflow = "&inflow[]=b";
  contenedorcomu = "&comu[]=c";
  url +=contenedoroutflow+contenedorinflow+contenedorcomu;

  window.open(url);
}
<commit_msg>agrego botones<commit_after>function mostrar() {
  var tinteres = 0;
  var vprincipal = 0;
  var bandera = false;
    if( $("#cajita").is(':checked')){
      bandera = true;
    }
    var x = parseInt($("#droplistbox").val());
    if(parseInt($("#tasainteres").val())<0 || parseInt($("#tasainteres").val())>100){
      alert("Por favor inserta una tasa de interés válida");
      return;
    }else if($("#principal").val()!=""){
      tinteres = parseInt($("#tasainteres").val());
    }
    if($("#principal").val()!=""){
      vprincipal = parseInt($("#principal").val());
      $("#cajita").prop('checked', true);
      bandera = true;
    }
    agregar(x,bandera,vprincipal);
}

function agregar(limite,bandera,principal){
  var codigo='

PERIOD

OUTFLOWS

INFLOWS

CUMULATIVE CASH FLOW

';
  if(bandera){
    codigo +='

0
<input type="number" class="col-md-4" id="outflow0" value="'+principal+'"><input type="number" class="col-md-4" id="inflow0"><input type="number" class="col-md-3" id="comulativecash0" disabled>

';
  }
  for(i=1;i<limite+1;i++){
    codigo += '

'+i+'
<input type="number" class="col-md-4" id="outflow'+i+'"><input type="number" class="col-md-4" id="inflow'+i+'"><input type="number" class="col-md-3" id="comulativecash'+i+'" disabled>

';
  }
  codigo+='

<button type="button" class="btn btn-default" onclick="imprimirresultados()">Show payback period</button>

<input type="number" class="col-md-5" id="netpresentvalue" disabled>

'
  $("#contenedor").html(codigo);
}

function valores(){
    var returnPeriod = -1
    var interest = parseFloat($("#tasainteres").val()) / 100;
    var length = parseInt($("#droplistbox").val());
    var inflow = parseFloat($("#inflow0").val());
    var outflow = parseFloat($("#outflow0").val());

    if (isNaN(inflow)) {
      inflow = 0;
    }

    if (isNaN(outflow)) {
      outflow = 0;
    }

    var net = inflow - outflow;
    var COF = 0;
    var cum = net;

    // Set cumulative de period 0.
    $("#comulativecash0").val(cum);

    if (isNaN(interest)) {
      interest = 0;
    }

    // Recorrer desde 1 hasta length.
    for (var i = 1; i < length + 1; i++) {

        // Calcular net (inflow - outflow)
        inflow = parseFloat($('#inflow' + i).val());
        outflow = parseFloat($('#outflow' + i).val());

        if (isNaN(inflow)) {
          inflow = 0;
        }

        if (isNaN(outflow)) {
          outflow = 0;
        }

        //console.log(inflow);
        //console.log(outflow);

        net = inflow - outflow;

        // Calcular COF
        if (cum < 0) {
            COF = cum * interest;
        } else {
            COF = 0;
        }

        // Calcular Cumulative.
        cum += (net + COF);

        if (cum >= 0 && returnPeriod == -1) {
          returnPeriod = i;
        }

        // Set net and cumulative.
        $('#comulativecash' + i).val(cum);
    }
    return returnPeriod;
}

function imprimirresultados() {
    var returnPeriod = valores();
    $("#netpresentvalue").val(returnPeriod);
}
function netcashflow(inflow, outflow) {
  return inflow - outflow;
}

function printpdf(){
  var x = parseInt($("#droplistbox").val());
  var url ="http://generatepdf-ddnsnet.rhcloud.com/?periods="+(x+1);
  contenedoroutflow = "&outflow[]=a";
  contenedorinflow = "&inflow[]=b";
  contenedorcomu = "&comu[]=c";
  url +=contenedoroutflow+contenedorinflow+contenedorcomu;

  window.open(url);
}
<|endoftext|>


<commit_before>$(document).ready(function(){
  hideNotesSection();
  draggableBoxes();
  resizableBoxes();
  doneStructuringDay();
  showTodoLists();
});

var hideNotesSection = function() {
  $("#focus-todo").hide();
}

var draggableBoxes = function(){
  $(".box").draggable({
    axis: "y",
    containment: "parent",
    grid: [0, 15],
    opacity: 0.5,
  });
};

var resizableBoxes = function(){
  $(".box").resizable({
    grid: [0, 15],
    maxHeight: 400,
    maxWidth: 350,
    minHeight: 25,
    minWidth: 350,
  });
}

var doneStructuringDay = function(){
  $("#one").on('click', function() {
    $(".first-step-flex").addClass("hidden");
    $(".second-step-flex").removeClass("hidden");
    $("#showTodoForm").removeClass("hidden");
  });
}

$(document).on('click','#two',function(){
     $("#showTodoForm").addClass("hidden");
     $(".second-step-flex").addClass("hidden");
     $(".third-step-flex").removeClass("hidden");
})

$(document).on('click','#three',function(){
     $(".third-step-flex").addClass("hidden");
})

var showTodoLists = function(){
 $(".high").on('dblclick', function(){
   $("#linkToShowTodoForm").removeClass("hidden")
   $("#medium").hide();
   $("#low").hide();
   $("#high").toggle();
 });
 $(".medium").on('dblclick', function(){
   $("#linkToShowTodoForm").removeClass("hidden")
   $("#high").hide();
   $("#low").hide();
   $("#medium").toggle();
 })
 $(".low").on('dblclick', function(){
   $("#linkToShowTodoForm").removeClass("hidden")
   $("#low").toggle();
   $("#high").hide();
   $("#medium").hide();
 })
}

$(document).on('click','#completed-the-thing',function(){
   event.preventDefault();
   var url = $(this).attr("action")
   var formData = $(this).serialize();
   $.ajax({
     url: url,
     method: "PUT",
     data: formData
   })
   .done(function(server_response) {
     var todo = JSON.parse(server_response)
     $("#todo-" + todo.id).hide();
     $("#edit-form").hide();
   })
   .fail(function(server_response) {
       alert(server_response.error)
     })
})

$(document).on('click','#linkToShowTodoForm', function(){
    event.preventDefault();
    $("#showTodoForm").removeClass("hidden");
    $(this).addClass("hidden");
})

var addListItem = function(task) {
  if (task.brainjuice_id == 1) {
   $( "ul#high li" ).first().before(
      "
(" + task.time_est + " min) &nbsp <form class=\"inline\" action=\"/todos/" + task.id + "\" method=\"post\" id=\"completed-the-thing\"><input type=\"hidden\" name=\"_method\" value=\"PUT\"></form>  " + task.name + "
" );
  } else if (task.brainjuice_id == 2) {
    $( "ul#medium li" ).first().before(
      "
(" + task.time_est + " min) &nbsp <form class=\"inline\" action=\"/todos/" + task.id + "\" method=\"post\" id=\"completed-the-thing\"><input type=\"hidden\" name=\"_method\" value=\"PUT\"></form>  " + task.name + "
" );
  } else {
    $( "ul#low li" ).first().before(
      "
(" + task.time_est + " min) &nbsp <form class=\"inline\" action=\"/todos/" + task.id + "\" method=\"post\" id=\"completed-the-thing\"><input type=\"hidden\" name=\"_method\" value=\"PUT\"></form>  " + task.name + "
" );
  }
}

$(document).on('click','#new-todo-btn', function(){
    event.preventDefault();
    $("#new-todo-btn").removeClass("success")
    var url = $(this).children().attr("action");
    var formData = $("#new-todo-form").serialize();
    $.ajax({
      url: url,
      method: "POST",
      data: formData
    })
    .done(function(server_response) {
      var task = JSON.parse(server_response)
      $("#new-todo-btn").addClass("success")
      $('#new-todo-form').find('input:text').val('');
      $('#new-todo-form').find('textarea').val('');
      addListItem(task);
    })
  .fail(function(server_response) {
      alert(server_response.error)
    })
})

$(document).on('click','#todo-done-btn', function(){
    $("#showTodoForm").addClass("hidden");
  })

$(document).on('click','#showDetails', function(){
     event.preventDefault();
     var url = $(this).val("href").attr("href")
     $.ajax({
       url:  url,
     })
     .done(function(server_response) {
       var edit_form = JSON.parse(server_response);
       $(".first-step-flex").addClass("hidden")
       $(".second-step-flex").addClass("hidden")
       $(".third-step-flex").addClass("hidden")
      //  $("#edit-form").removeClass("hidden");
       $("#edit-form").show();
       $("#edit-form").empty().append(edit_form);
     })
     .fail(function(server_response) {
       alert(server_response.error)
     })
})

$(document).on('click','#submit-edits-btn', function(){   // This is picking up
     saveChanges();
})

var saveChanges = function() {
    event.preventDefault();
    var url = $("#edit-form form").attr("action");
    var todo_id = $("#edit-form form").attr("id")
    var formData = $("#edit-form form").serialize();
    var whatFunctionIsThis = function() {
      console.log("Mystery function?")
  }
    $.ajax({
      url: url,
      data: formData,
      method: "PUT"
    })
    .done(function(a, b, c) {
      whatFunctionIsThis(a, b, c, todo_id)

      $("#edit-form").hide();
      revised_todo = JSON.parse(a)
      $("#todo-" + revised_todo.id).remove();
      addListItem(revised_todo);
    })
    .fail(function(server_response) {
      console.log(server_response)
    })
}
<commit_msg>Refactor addListItem in planner.js<commit_after>$(document).ready(function(){
  hideNotesSection();
  draggableBoxes();
  resizableBoxes();
  doneStructuringDay();
  showTodoLists();
});

var hideNotesSection = function() {
  $("#focus-todo").hide();
}

var draggableBoxes = function(){
  $(".box").draggable({
    axis: "y",
    containment: "parent",
    grid: [0, 15],
    opacity: 0.5,
  });
};

var resizableBoxes = function(){
  $(".box").resizable({
    grid: [0, 15],
    maxHeight: 400,
    maxWidth: 350,
    minHeight: 25,
    minWidth: 350,
  });
}

var doneStructuringDay = function(){
  $("#one").on('click', function() {
    $(".first-step-flex").addClass("hidden");
    $(".second-step-flex").removeClass("hidden");
    $("#showTodoForm").removeClass("hidden");
  });
}

$(document).on('click','#two',function(){
     $("#showTodoForm").addClass("hidden");
     $(".second-step-flex").addClass("hidden");
     $(".third-step-flex").removeClass("hidden");
})

$(document).on('click','#three',function(){
     $(".third-step-flex").addClass("hidden");
})

var showTodoLists = function(){
 $(".high").on('dblclick', function(){
   $("#linkToShowTodoForm").removeClass("hidden")
   $("#medium").hide();
   $("#low").hide();
   $("#high").toggle();
 });
 $(".medium").on('dblclick', function(){
   $("#linkToShowTodoForm").removeClass("hidden")
   $("#high").hide();
   $("#low").hide();
   $("#medium").toggle();
 })
 $(".low").on('dblclick', function(){
   $("#linkToShowTodoForm").removeClass("hidden")
   $("#low").toggle();
   $("#high").hide();
   $("#medium").hide();
 })
}

$(document).on('click','#completed-the-thing',function(){
   event.preventDefault();
   var url = $(this).attr("action")
   var formData = $(this).serialize();
   $.ajax({
     url: url,
     method: "PUT",
     data: formData
   })
   .done(function(server_response) {
     var todo = JSON.parse(server_response)
     $("#todo-" + todo.id).hide();
     $("#edit-form").hide();
   })
   .fail(function(server_response) {
       alert(server_response.error)
     })
})

$(document).on('click','#linkToShowTodoForm', function(){
    event.preventDefault();
    $("#showTodoForm").removeClass("hidden");
    $(this).addClass("hidden");
})

var addListItem = function(task) {
  if (task.brainjuice_id == 1) {
    var bj = "high"
  } else if (task.brainjuice_id == 2) {
    var bj = "medium"
  } else {
    var bj = "low"
  }
   $( "ul#" + bj +" li" ).first().before(
      "
(" + task.time_est + " min) &nbsp <form class=\"inline\" action=\"/todos/" + task.id + "\" method=\"post\" id=\"completed-the-thing\"><input type=\"hidden\" name=\"_method\" value=\"PUT\"></form>  " + task.name + "
" );
}

$(document).on('click','#new-todo-btn', function(){
    event.preventDefault();
    $("#new-todo-btn").removeClass("success")
    var url = $(this).children().attr("action");
    var formData = $("#new-todo-form").serialize();
    $.ajax({
      url: url,
      method: "POST",
      data: formData
    })
    .done(function(server_response) {
      var task = JSON.parse(server_response)
      $("#new-todo-btn").addClass("success")
      $('#new-todo-form').find('input:text').val('');
      $('#new-todo-form').find('textarea').val('');
      addListItem(task);
    })
  .fail(function(server_response) {
      alert(server_response.error)
    })
})

$(document).on('click','#todo-done-btn', function(){
    $("#showTodoForm").addClass("hidden");
  })

$(document).on('click','#showDetails', function(){
     event.preventDefault();
     var url = $(this).val("href").attr("href")
     $.ajax({
       url:  url,
     })
     .done(function(server_response) {
       var edit_form = JSON.parse(server_response);
       $(".first-step-flex").addClass("hidden")
       $(".second-step-flex").addClass("hidden")
       $(".third-step-flex").addClass("hidden")
       $("#edit-form").show();
       $("#edit-form").empty().append(edit_form);
     })
     .fail(function(server_response) {
       alert(server_response.error)
     })
})

$(document).on('click','#submit-edits-btn', function(){
     saveChanges();
})

var saveChanges = function() {
    event.preventDefault();
    var url = $("#edit-form form").attr("action");
    var todo_id = $("#edit-form form").attr("id")
    var formData = $("#edit-form form").serialize();
    var whatFunctionIsThis = function() {
      console.log("Mystery function?")
  }
    $.ajax({
      url: url,
      data: formData,
      method: "PUT"
    })
    .done(function(a, b, c) {
      whatFunctionIsThis(a, b, c, todo_id)

      $("#edit-form").hide();
      revised_todo = JSON.parse(a)
      $("#todo-" + revised_todo.id).remove();
      addListItem(revised_todo);
    })
    .fail(function(server_response) {
      console.log(server_response)
    })
}
<|endoftext|>


<commit_before>var util = require('../helpers/global')
var EventManager = require('../lib/eventManager')
var traceHelper = require('../helpers/traceHelper')
var yo = require('yo-yo')
var ui = require('../helpers/ui')
var init = require('../helpers/init')
var DropdownPanel = require('./DropdownPanel')
var style = require('./styles/basicStyles')
var csjs = require('csjs-inject')
var styleGuide = require('./styles/style-guide')
var styles = styleGuide()
var styles = styleGuide()
var styles = styleGuide()

var css = csjs`
  .container {
    display: flex;
    flex-direction: column;
  }
  .txContainer {
    display: flex;
    flex-direction: column;
  }
  .txinputs {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .txinput {
    ${styles.inputField}
    min-width: 30px;
    margin: 3px;
  }
  .txbuttons {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .txbutton {
    ${styles.button}
    width: 50%;
    min-width: 30px;
  }
  .txbutton:hover {
    color: ${styles.colors.black};
  }
`
function TxBrowser (_parent) {
  this.event = new EventManager()

  this.blockNumber
  this.txNumber
  this.view
  this.displayConnectionSetting = true
  this.basicPanel = new DropdownPanel('Transaction', {json: true})
  this.basicPanel.data = {}
  var self = this
  _parent.event.register('providerChanged', this, function (provider) {
    self.displayConnectionSetting = provider === 'INTERNAL'
    self.setDefaultValues()
    if (self.view) {
      yo.update(self.view, self.render())
    }
  })
}

// creation 0xa9619e1d0a35b2c1d686f5b661b3abd87f998d2844e8e9cc905edb57fc9ce349
// invokation 0x71a6d583d16d142c5c3e8903060e8a4ee5a5016348a9448df6c3e63b68076ec4 0xcda2b2835add61af54cf83bd076664d98d7908c6cd98d86423b3b48d8b8e51ff
// test:
// creation: 0x72908de76f99fca476f9e3a3b5d352f350a98cd77d09cebfc59ffe32a6ecaa0b
// invokation: 0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51

TxBrowser.prototype.setDefaultValues = function () {
  this.connectInfo = ''
  this.basicPanel.update({})
  this.basicPanel.hide()
  if (this.view) {
    yo.update(this.view, this.render())
  }
}

TxBrowser.prototype.submit = function () {
  if (!this.txNumber) {
    return
  }
  this.event.trigger('newTxLoading', [this.blockNumber, this.txNumber])
  try {
    var self = this
    if (this.txNumber.indexOf('0x') !== -1) {
      util.web3.eth.getTransaction(this.txNumber, function (error, result) {
        self.update(error, result)
      })
    } else {
      util.web3.eth.getTransactionFromBlock(this.blockNumber, this.txNumber, function (error, result) {
        self.update(error, result)
      })
    }
  } catch (e) {
    self.update(e.message)
  }
}

TxBrowser.prototype.update = function (error, tx) {
  var info = {}
  if (error) {
    this.view.querySelector('#error').innerHTML = error
  } else {
    if (tx) {
      this.view.querySelector('#error').innerHTML = ''
      if (!tx.to) {
        tx.to = traceHelper.contractCreationToken('0')
      }
      info.from = tx.from
      info.to = tx.to
      info.hash = tx.hash
      this.event.trigger('newTraceRequested', [this.blockNumber, this.txNumber, tx])
    } else {
      var mes = '<not found>'
      info.from = mes
      info.to = mes
      info.hash = mes
      this.view.querySelector('#error').innerHTML = 'Cannot find transaction with reference. Block number: ' + this.blockNumber + '. Transaction index/hash: ' + this.txNumber
    }
  }
  this.basicPanel.update(info)
}

TxBrowser.prototype.updateWeb3Url = function (newhost) {
  init.setProvider(util.web3, newhost)
  var self = this
  this.checkWeb3(function (error, block) {
    if (!error) {
      self.connectInfo = 'Connected to ' + util.web3.currentProvider.host + '. Current block number: ' + block
    } else {
      self.connectInfo = 'Unable to connect to ' + util.web3.currentProvider.host + '. ' + error.message
    }
    yo.update(self.view, self.render())
  })
}

TxBrowser.prototype.checkWeb3 = function (callback) {
  try {
    util.web3.eth.getBlockNumber(function (error, block) {
      callback(error, block)
    })
  } catch (e) {
    console.log(e)
    callback(e.message, null)
  }
}

TxBrowser.prototype.updateBlockN = function (ev) {
  this.blockNumber = ev.target.value
}

TxBrowser.prototype.updateTxN = function (ev) {
  this.txNumber = ev.target.value
}

TxBrowser.prototype.load = function (txHash) {
  this.txNumber = txHash
  this.submit()
}

TxBrowser.prototype.unload = function (txHash) {
  this.event.trigger('unloadRequested')
  this.init()
}

TxBrowser.prototype.init = function (ev) {
  this.setDefaultValues()
}

TxBrowser.prototype.connectionSetting = function () {
  if (this.displayConnectionSetting) {
    var self = this
    return yo`
Node URL: <input onkeyup=${function () { self.updateWeb3Url(arguments[0].target.value) }} value=${util.web3.currentProvider ? util.web3.currentProvider.host : ' - none - '} type='text' />
              ${this.connectInfo}
`
  } else {
    return ''
  }
}

TxBrowser.prototype.render = function () {
  var self = this
  var view = yo`

        ${this.connectionSetting()}

            <input class="${css.txinput}" onkeyup=${function () { self.updateBlockN(arguments[0]) }} type='text' placeholder=${'Block number'} />
            <input class="${css.txinput}" id='txinput' onkeyup=${function () { self.updateTxN(arguments[0]) }} type='text' placeholder=${'Transaction index or hash'} />

            <button id='load' class='fa fa-play ${css.txbutton}' title='start debugging' onclick=${function () { self.submit() }}></button>
            <button id='unload' class='fa fa-stop ${css.txbutton}' title='stop debugging' onclick=${function () { self.unload() }}></button>

          ${this.basicPanel.render()}

`
  if (!this.view) {
    this.view = view
  }
  return view
}

module.exports = TxBrowser
<commit_msg>remove unneeded<commit_after>var util = require('../helpers/global')
var EventManager = require('../lib/eventManager')
var traceHelper = require('../helpers/traceHelper')
var yo = require('yo-yo')
var ui = require('../helpers/ui')
var init = require('../helpers/init')
var DropdownPanel = require('./DropdownPanel')
var style = require('./styles/basicStyles')
var csjs = require('csjs-inject')
var styleGuide = require('./styles/style-guide')
var styles = styleGuide()

var css = csjs`
  .container {
    display: flex;
    flex-direction: column;
  }
  .txContainer {
    display: flex;
    flex-direction: column;
  }
  .txinputs {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .txinput {
    ${styles.inputField}
    min-width: 30px;
    margin: 3px;
  }
  .txbuttons {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .txbutton {
    ${styles.button}
    width: 50%;
    min-width: 30px;
  }
  .txbutton:hover {
    color: ${styles.colors.black};
  }
`
function TxBrowser (_parent) {
  this.event = new EventManager()

  this.blockNumber
  this.txNumber
  this.view
  this.displayConnectionSetting = true
  this.basicPanel = new DropdownPanel('Transaction', {json: true})
  this.basicPanel.data = {}
  var self = this
  _parent.event.register('providerChanged', this, function (provider) {
    self.displayConnectionSetting = provider === 'INTERNAL'
    self.setDefaultValues()
    if (self.view) {
      yo.update(self.view, self.render())
    }
  })
}

// creation 0xa9619e1d0a35b2c1d686f5b661b3abd87f998d2844e8e9cc905edb57fc9ce349
// invokation 0x71a6d583d16d142c5c3e8903060e8a4ee5a5016348a9448df6c3e63b68076ec4 0xcda2b2835add61af54cf83bd076664d98d7908c6cd98d86423b3b48d8b8e51ff
// test:
// creation: 0x72908de76f99fca476f9e3a3b5d352f350a98cd77d09cebfc59ffe32a6ecaa0b
// invokation: 0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51

TxBrowser.prototype.setDefaultValues = function () {
  this.connectInfo = ''
  this.basicPanel.update({})
  this.basicPanel.hide()
  if (this.view) {
    yo.update(this.view, this.render())
  }
}

TxBrowser.prototype.submit = function () {
  if (!this.txNumber) {
    return
  }
  this.event.trigger('newTxLoading', [this.blockNumber, this.txNumber])
  try {
    var self = this
    if (this.txNumber.indexOf('0x') !== -1) {
      util.web3.eth.getTransaction(this.txNumber, function (error, result) {
        self.update(error, result)
      })
    } else {
      util.web3.eth.getTransactionFromBlock(this.blockNumber, this.txNumber, function (error, result) {
        self.update(error, result)
      })
    }
  } catch (e) {
    self.update(e.message)
  }
}

TxBrowser.prototype.update = function (error, tx) {
  var info = {}
  if (error) {
    this.view.querySelector('#error').innerHTML = error
  } else {
    if (tx) {
      this.view.querySelector('#error').innerHTML = ''
      if (!tx.to) {
        tx.to = traceHelper.contractCreationToken('0')
      }
      info.from = tx.from
      info.to = tx.to
      info.hash = tx.hash
      this.event.trigger('newTraceRequested', [this.blockNumber, this.txNumber, tx])
    } else {
      var mes = '<not found>'
      info.from = mes
      info.to = mes
      info.hash = mes
      this.view.querySelector('#error').innerHTML = 'Cannot find transaction with reference. Block number: ' + this.blockNumber + '. Transaction index/hash: ' + this.txNumber
    }
  }
  this.basicPanel.update(info)
}

TxBrowser.prototype.updateWeb3Url = function (newhost) {
  init.setProvider(util.web3, newhost)
  var self = this
  this.checkWeb3(function (error, block) {
    if (!error) {
      self.connectInfo = 'Connected to ' + util.web3.currentProvider.host + '. Current block number: ' + block
    } else {
      self.connectInfo = 'Unable to connect to ' + util.web3.currentProvider.host + '. ' + error.message
    }
    yo.update(self.view, self.render())
  })
}

TxBrowser.prototype.checkWeb3 = function (callback) {
  try {
    util.web3.eth.getBlockNumber(function (error, block) {
      callback(error, block)
    })
  } catch (e) {
    console.log(e)
    callback(e.message, null)
  }
}

TxBrowser.prototype.updateBlockN = function (ev) {
  this.blockNumber = ev.target.value
}

TxBrowser.prototype.updateTxN = function (ev) {
  this.txNumber = ev.target.value
}

TxBrowser.prototype.load = function (txHash) {
  this.txNumber = txHash
  this.submit()
}

TxBrowser.prototype.unload = function (txHash) {
  this.event.trigger('unloadRequested')
  this.init()
}

TxBrowser.prototype.init = function (ev) {
  this.setDefaultValues()
}

TxBrowser.prototype.connectionSetting = function () {
  if (this.displayConnectionSetting) {
    var self = this
    return yo`
Node URL: <input onkeyup=${function () { self.updateWeb3Url(arguments[0].target.value) }} value=${util.web3.currentProvider ? util.web3.currentProvider.host : ' - none - '} type='text' />
              ${this.connectInfo}
`
  } else {
    return ''
  }
}

TxBrowser.prototype.render = function () {
  var self = this
  var view = yo`

        ${this.connectionSetting()}

            <input class="${css.txinput}" onkeyup=${function () { self.updateBlockN(arguments[0]) }} type='text' placeholder=${'Block number'} />
            <input class="${css.txinput}" id='txinput' onkeyup=${function () { self.updateTxN(arguments[0]) }} type='text' placeholder=${'Transaction index or hash'} />

            <button id='load' class='fa fa-play ${css.txbutton}' title='start debugging' onclick=${function () { self.submit() }}></button>
            <button id='unload' class='fa fa-stop ${css.txbutton}' title='stop debugging' onclick=${function () { self.unload() }}></button>

          ${this.basicPanel.render()}

`
  if (!this.view) {
    this.view = view
  }
  return view
}

module.exports = TxBrowser
<|endoftext|>


<commit_before>/* globals google, picker:true, minDate, expenseRestShow:true, incomeRestShow:true, year, shared, month, hideTheRest, showTheRest, showTheRestExpense, hideTheRestExpense, columnChart, lineChart, stackedColumnChart */

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

    if ($('#inputDateRange').length > 0) {

        picker = $('#inputDateRange').daterangepicker(
            {
                locale: {
                    format: 'YYYY-MM-DD',
                    firstDay: 1,
                },
                minDate: minDate,
                drops: 'up',
            }
        );
    }

    // set values from cookies, if any:
    if (readCookie('report-type') !== null) {
        $('select[name="report_type"]').val(readCookie('report-type'));
    }

    if ((readCookie('report-accounts') !== null)) {
        var arr = readCookie('report-accounts').split(',');
        arr.forEach(function (val) {
            $('input[type="checkbox"][value="' + val + '"]').prop('checked', true);
        });
    }

    // set date:
    var startStr = readCookie('report-start');
    var endStr = readCookie('report-end');
    if (startStr !== null && endStr !== null && startStr.length == 8 && endStr.length == 8) {
        var startDate = moment(startStr, "YYYYMMDD");
        var endDate = moment(endStr, "YYYYMMDD");
        var datePicker = $('#inputDateRange').data('daterangepicker');
        datePicker.setStartDate(startDate);
        datePicker.setEndDate(endDate);
    }

    $('.openModal').on('click', openModal);

    $('.date-select').on('click', preSelectDate);

    $('#report-form').on('submit', catchSubmit);

    // click open the top X income list:
    $('#showIncomes').click(showIncomes);
    // click open the top X expense list:
    $('#showExpenses').click(showExpenses);
});

function catchSubmit() {
    "use strict";
    // default;20141201;20141231;4;5
    // report name:
    var url = '' + $('select[name="report_type"]').val() + ';';

    // date, processed:
    var picker = $('#inputDateRange').data('daterangepicker');
    url += moment(picker.startDate).format("YYYYMMDD") + ';';
    url += moment(picker.endDate).format("YYYYMMDD");

    // all account ids:
    var count = 0;
    var accounts = [];
    $.each($('.account-checkbox'), function (i, v) {
        var c = $(v);
        if (c.prop('checked')) {
            url += ';' + c.val();
            accounts.push(c.val());
            count++;
        }
    });
    if (count > 0) {
        // set cookie to remember choices.
        createCookie('report-type', $('select[name="report_type"]').val(), 365);
        createCookie('report-accounts', accounts, 365);
        createCookie('report-start', moment(picker.startDate).format("YYYYMMDD"), 365);
        createCookie('report-end', moment(picker.endDate).format("YYYYMMDD"), 365);

        window.location.replace(reportURL + "/" + url);
    }
    //console.log(url);

    return false;
}

function preSelectDate(e) {
    "use strict";
    var link = $(e.target);
    var picker = $('#inputDateRange').data('daterangepicker');
    picker.setStartDate(link.data('start'));
    picker.setEndDate(link.data('end'));
    return false;

}

function drawChart() {
    "use strict";
    if (typeof columnChart !== 'undefined' && typeof year !== 'undefined' && typeof month === 'undefined') {
        columnChart('chart/report/in-out/' + year + shared, 'income-expenses-chart');
        columnChart('chart/report/in-out-sum/' + year + shared, 'income-expenses-sum-chart');
    }
    if (typeof stackedColumnChart !== 'undefined' && typeof year !== 'undefined' && typeof month === 'undefined') {
        stackedColumnChart('chart/budget/year/' + year + shared, 'budgets');
        stackedColumnChart('chart/category/spent-in-year/' + year + shared, 'categories-spent-in-year');
        stackedColumnChart('chart/category/earned-in-year/' + year + shared, 'categories-earned-in-year');
    }
    if (typeof lineChart !== 'undefined' && typeof month !== 'undefined') {
        lineChart('/chart/account/month/' + year + '/' + month + shared, 'account-balances-chart');
    }
}

function openModal(e) {
    "use strict";
    var target = $(e.target).parent();
    var URL = target.attr('href');

    $.get(URL).success(function (data) {
        $('#defaultModal').empty().html(data).modal('show');

    }).fail(function () {
        alert('Could not load data.');
    });

    return false;
}

function showIncomes() {
    "use strict";
    if (incomeRestShow) {
        // hide everything, make button say "show"
        $('#showIncomes').text(showTheRest);
        $('.incomesCollapsed').removeClass('in').addClass('out');

        // toggle:
        incomeRestShow = false;
    } else {
        // show everything, make button say "hide".
        $('#showIncomes').text(hideTheRest);
        $('.incomesCollapsed').removeClass('out').addClass('in');

        // toggle:
        incomeRestShow = true;
    }

    return false;
}

function showExpenses() {
    "use strict";
    if (expenseRestShow) {
        // hide everything, make button say "show"
        $('#showExpenses').text(showTheRestExpense);
        $('.expenseCollapsed').removeClass('in').addClass('out');

        // toggle:
        expenseRestShow = false;
    } else {
        // show everything, make button say "hide".
        $('#showExpenses').text(hideTheRestExpense);
        $('.expenseCollapsed').removeClass('out').addClass('in');

        // toggle:
        expenseRestShow = true;
    }

    return false;
}

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

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

function eraseCookie(name) {
    createCookie(name, "", -1);
}<commit_msg>Fix another JS error<commit_after>/* globals google, picker:true, minDate, expenseRestShow:true, incomeRestShow:true, year, shared, month, hideTheRest, showTheRest, showTheRestExpense, hideTheRestExpense, columnChart, lineChart, stackedColumnChart */

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

    if ($('#inputDateRange').length > 0) {

        picker = $('#inputDateRange').daterangepicker(
            {
                locale: {
                    format: 'YYYY-MM-DD',
                    firstDay: 1,
                },
                minDate: minDate,
                drops: 'up',
            }
        );

        // set values from cookies, if any:
        if (readCookie('report-type') !== null) {
            $('select[name="report_type"]').val(readCookie('report-type'));
        }

        if ((readCookie('report-accounts') !== null)) {
            var arr = readCookie('report-accounts').split(',');
            arr.forEach(function (val) {
                $('input[type="checkbox"][value="' + val + '"]').prop('checked', true);
            });
        }

        // set date:
        var startStr = readCookie('report-start');
        var endStr = readCookie('report-end');
        if (startStr !== null && endStr !== null && startStr.length == 8 && endStr.length == 8) {
            var startDate = moment(startStr, "YYYYMMDD");
            var endDate = moment(endStr, "YYYYMMDD");
            var datePicker = $('#inputDateRange').data('daterangepicker');
            datePicker.setStartDate(startDate);
            datePicker.setEndDate(endDate);
        }
    }

    $('.openModal').on('click', openModal);

    $('.date-select').on('click', preSelectDate);

    $('#report-form').on('submit', catchSubmit);

    // click open the top X income list:
    $('#showIncomes').click(showIncomes);
    // click open the top X expense list:
    $('#showExpenses').click(showExpenses);
});

function catchSubmit() {
    "use strict";
    // default;20141201;20141231;4;5
    // report name:
    var url = '' + $('select[name="report_type"]').val() + ';';

    // date, processed:
    var picker = $('#inputDateRange').data('daterangepicker');
    url += moment(picker.startDate).format("YYYYMMDD") + ';';
    url += moment(picker.endDate).format("YYYYMMDD");

    // all account ids:
    var count = 0;
    var accounts = [];
    $.each($('.account-checkbox'), function (i, v) {
        var c = $(v);
        if (c.prop('checked')) {
            url += ';' + c.val();
            accounts.push(c.val());
            count++;
        }
    });
    if (count > 0) {
        // set cookie to remember choices.
        createCookie('report-type', $('select[name="report_type"]').val(), 365);
        createCookie('report-accounts', accounts, 365);
        createCookie('report-start', moment(picker.startDate).format("YYYYMMDD"), 365);
        createCookie('report-end', moment(picker.endDate).format("YYYYMMDD"), 365);

        window.location.replace(reportURL + "/" + url);
    }
    //console.log(url);

    return false;
}

function preSelectDate(e) {
    "use strict";
    var link = $(e.target);
    var picker = $('#inputDateRange').data('daterangepicker');
    picker.setStartDate(link.data('start'));
    picker.setEndDate(link.data('end'));
    return false;

}

function drawChart() {
    "use strict";
    if (typeof columnChart !== 'undefined' && typeof year !== 'undefined' && typeof month === 'undefined') {
        columnChart('chart/report/in-out/' + year + shared, 'income-expenses-chart');
        columnChart('chart/report/in-out-sum/' + year + shared, 'income-expenses-sum-chart');
    }
    if (typeof stackedColumnChart !== 'undefined' && typeof year !== 'undefined' && typeof month === 'undefined') {
        stackedColumnChart('chart/budget/year/' + year + shared, 'budgets');
        stackedColumnChart('chart/category/spent-in-year/' + year + shared, 'categories-spent-in-year');
        stackedColumnChart('chart/category/earned-in-year/' + year + shared, 'categories-earned-in-year');
    }
    if (typeof lineChart !== 'undefined' && typeof month !== 'undefined') {
        lineChart('/chart/account/month/' + year + '/' + month + shared, 'account-balances-chart');
    }
}

function openModal(e) {
    "use strict";
    var target = $(e.target).parent();
    var URL = target.attr('href');

    $.get(URL).success(function (data) {
        $('#defaultModal').empty().html(data).modal('show');

    }).fail(function () {
        alert('Could not load data.');
    });

    return false;
}

function showIncomes() {
    "use strict";
    if (incomeRestShow) {
        // hide everything, make button say "show"
        $('#showIncomes').text(showTheRest);
        $('.incomesCollapsed').removeClass('in').addClass('out');

        // toggle:
        incomeRestShow = false;
    } else {
        // show everything, make button say "hide".
        $('#showIncomes').text(hideTheRest);
        $('.incomesCollapsed').removeClass('out').addClass('in');

        // toggle:
        incomeRestShow = true;
    }

    return false;
}

function showExpenses() {
    "use strict";
    if (expenseRestShow) {
        // hide everything, make button say "show"
        $('#showExpenses').text(showTheRestExpense);
        $('.expenseCollapsed').removeClass('in').addClass('out');

        // toggle:
        expenseRestShow = false;
    } else {
        // show everything, make button say "hide".
        $('#showExpenses').text(hideTheRestExpense);
        $('.expenseCollapsed').removeClass('out').addClass('in');

        // toggle:
        expenseRestShow = true;
    }

    return false;
}

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

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

function eraseCookie(name) {
    createCookie(name, "", -1);
}<|endoftext|>


<commit_before>(function() {

  /**
    * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
    * @memberOf fabric.util
    * @param {Object} [options] Animation options
    * @param {Function} [options.onChange] Callback; invoked on every value change
    * @param {Function} [options.onComplete] Callback; invoked when value change is completed
    * @param {Number} [options.startValue=0] Starting value
    * @param {Number} [options.endValue=100] Ending value
    * @param {Number} [options.byValue=100] Value to modify the property by
    * @param {Function} [options.easing] Easing function
    * @param {Number} [options.duration=500] Duration of change
    */
  function animate(options) {

    requestAnimFrame(function(timestamp) {
      options || (options = { });

      var start = timestamp || +new Date(),
          duration = options.duration || 500,
          finish = start + duration, time,
          onChange = options.onChange || function() { },
          abort = options.abort || function() { return false; },
          easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t/d * (Math.PI/2)) + c + b;},
          startValue = 'startValue' in options ? options.startValue : 0,
          endValue = 'endValue' in options ? options.endValue : 100,
          byValue = options.byValue || endValue - startValue;

      options.onStart && options.onStart();

      (function tick(ticktime) {
        time = ticktime || +new Date();
        var currentTime = time > finish ? duration : (time - start);
        if (abort()) {
          options.onComplete && options.onComplete();
          return;
        }
        onChange(easing(currentTime, startValue, byValue, duration));
        if (time > finish) {
          options.onComplete && options.onComplete();
          return;
        }
        requestAnimFrame(tick);
      })(start);
    });

  }

  var _requestAnimFrame = fabric.window.requestAnimationFrame       ||
                          fabric.window.webkitRequestAnimationFrame ||
                          fabric.window.mozRequestAnimationFrame    ||
                          fabric.window.oRequestAnimationFrame      ||
                          fabric.window.msRequestAnimationFrame     ||
                          function(callback) {
                            fabric.window.setTimeout(callback, 1000 / 60);
                          };
  /**
    * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    * @memberOf fabric.util
    * @param {Function} callback Callback to invoke
    * @param {DOMElement} element optional Element to associate with animation
    */
  var requestAnimFrame = function() {
    return _requestAnimFrame.apply(fabric.window, arguments);
  };

  fabric.util.animate = animate;
  fabric.util.requestAnimFrame = requestAnimFrame;

})();
<commit_msg>fixed weird spacing stuff2<commit_after>(function() {

   /**
    * Changes value from one to another within certain period of time, invoking callbacks as value is being changed.
    * @memberOf fabric.util
    * @param {Object} [options] Animation options
    * @param {Function} [options.onChange] Callback; invoked on every value change
    * @param {Function} [options.onComplete] Callback; invoked when value change is completed
    * @param {Number} [options.startValue=0] Starting value
    * @param {Number} [options.endValue=100] Ending value
    * @param {Number} [options.byValue=100] Value to modify the property by
    * @param {Function} [options.easing] Easing function
    * @param {Number} [options.duration=500] Duration of change
    */
  function animate(options) {

    requestAnimFrame(function(timestamp) {
      options || (options = { });

      var start = timestamp || +new Date(),
          duration = options.duration || 500,
          finish = start + duration, time,
          onChange = options.onChange || function() { },
          abort = options.abort || function() { return false; },
          easing = options.easing || function(t, b, c, d) {return -c * Math.cos(t/d * (Math.PI/2)) + c + b;},
          startValue = 'startValue' in options ? options.startValue : 0,
          endValue = 'endValue' in options ? options.endValue : 100,
          byValue = options.byValue || endValue - startValue;

      options.onStart && options.onStart();

      (function tick(ticktime) {
        time = ticktime || +new Date();
        var currentTime = time > finish ? duration : (time - start);
        if (abort()) {
          options.onComplete && options.onComplete();
          return;
        }
        onChange(easing(currentTime, startValue, byValue, duration));
        if (time > finish) {
          options.onComplete && options.onComplete();
          return;
        }
        requestAnimFrame(tick);
      })(start);
    });

  }

  var _requestAnimFrame = fabric.window.requestAnimationFrame       ||
                          fabric.window.webkitRequestAnimationFrame ||
                          fabric.window.mozRequestAnimationFrame    ||
                          fabric.window.oRequestAnimationFrame      ||
                          fabric.window.msRequestAnimationFrame     ||
                          function(callback) {
                            fabric.window.setTimeout(callback, 1000 / 60);
                          };
  /**
    * requestAnimationFrame polyfill based on http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    * @memberOf fabric.util
    * @param {Function} callback Callback to invoke
    * @param {DOMElement} element optional Element to associate with animation
    */
  var requestAnimFrame = function() {
    return _requestAnimFrame.apply(fabric.window, arguments);
  };

  fabric.util.animate = animate;
  fabric.util.requestAnimFrame = requestAnimFrame;

})();
<|endoftext|>