<commit_before>try {
    if (!Nabu) throw "Nabu Manager not loaded";
} catch (e) {
    throw "Nabu Manager not loaded";
}

if (typeof Nabu.UI === 'undefined') {
    Nabu.UI = function() {};
}

Nabu.UI.Table = function(object, params)
{
    this.events = new Nabu.EventPool();
    this.container = object;
    this.params = params;

    try {
        this.table = $(object).find('table').get(0);
    } catch (e) {
        this.table = null;
    }

    this.init();
};

Nabu.UI.Table.prototype = {

    addEventListener: function(event)
    {
        this.events.addEventListener(event);
    },

    removeEventListener: function(event)
    {
        this.events.removeEventListener(event);
    },

    init: function()
    {
        this.initUI();
        this.initPager();
        this.initEditButtonStyle();
        this.initSelectableCheckbox();
        this.initToolbar();
    },

    initUI: function()
    {
        var Self = this;

        $(window).resize(function() {
            var cells = $(Self.container).find('tbody tr[data-type="row"]:first').children();
            var widths = cells.map(function() {
                return $(this).width();
            }).get();

            $(Self.container).find('thead tr').children().each(function (i, v) {
                $(v).width(widths[i]);
            });
        }).resize();
    },

    initPager: function()
    {
        if (this.params.tablePager && this.params.tableSize > 0) {
            var pager = $(this.container).find('.table-pager');
            var rows = $(this.container).find('tbody > tr');
            if (pager.length === 0) {
                var html =
                    "
" +
                        "" +
                            "
" +
                                "
«
" +
                                "
1
" +
                                "
2
" +
                                "
3
" +
                                "
4
" +
                                "
5
" +
                                "
»
" +
                            "
" +
                        "" +
                    "
"
                ;
                $(this.container).append(html);
                pager = $(this.container).find('.table-pager');
            } else {
                pager.addClass("hide");
            }

            if (this.params.tableSize < rows.length) {
                pager.removeClass("hide");
            }
        }
    },

    initEditButtonStyle: function()
    {
        var Self = this;

        if (this.params.editButton === 'button') {
            $(this.container).find('.btn-editor')
                .unbind('click')
                .on('click', function(e) {
                    return Self.doEditButtonClick(e);
                })
            ;
        } else if (this.params.editButton === 'line') {
            $(this.container).find('tr[data-id]')
                .unbind('click')
                .on('click', function(e) {
                    return Self.doEditButtonClick(e);
                })
            ;
        }
    },

    initSelectableCheckbox: function()
    {
        var Self = this;

        $(this.container).find('thead th[data-toggle="table-selectable"] input[type="checkbox"]')
            .unbind('click')
            .on('click', function(e) {
                return Self.doSelectableHeadCheckbox(e);
            })
        ;

        $(this.container).find('tbody th[data-toggle="table-selectable"] input[type="checkbox"]')
            .unbind('click')
            .on('click', function(e) {
                return Self.doSelectableBodyCheckbox(e);
            })
        ;
    },

    initToolbar: function()
    {
        var Self = this;

        $(this.container).find('.table-toolbar .btn')
            .on('click', function(e) {
                var data = $(this).data();
                if (data.action) {
                    Self.events.fireEvent('onToolbarClick', Self, {
                        action: data.action,
                        selection: Self.getSelectedItems()
                    });
                }
                if (!data.toggle) {
                    e.preventDefault();
                    return false;
                } else {
                    return true;
                }

            })
        ;

        this.enableToolbarButtons();
    },

    enableToolbarButtons: function()
    {
        var toolbar = $(this.container).find('.table-toolbar');
        if (toolbar.length > 0) {
            var selected = this.getSelectedItems();
            toolbar.find('.btn').attr('disabled', 'disabled');
            if (selected !== null) {
                if (selected.length === 1) {
                    toolbar.find('[data-apply="all"], [data-apply="single"], [data-apply="multiple"]')
                           .removeAttr('disabled');
                } else if (selected.length > 1) {
                    toolbar.find('[data-apply="all"], [data-apply="multiple"]')
                           .removeAttr('disabled');
                }
            } else {
                toolbar.find('[data-apply="all"]')
                       .removeAttr('disabled');
            }
        }
    },

    doEditButtonClick: function(e)
    {
        var id = false;

        if (this.params.editButton === 'line') {
            id = $(e.currentTarget).data('id');
        } else if (this.params.editButton === 'button') {
            id = $(e.currentTarget).closest('[data-id]').data('id');
        } else {
            throw Exception('Invalid editButton value [' + id + ']');
        }

        this.editor(id);
    },

    editor: function(id)
    {
        var Self = this;
        var is_new = ((typeof id) === 'undefined');

        var target = is_new
                   ? $.sprintf(this.params.editor, '')
                   : $.sprintf(this.params.editor, id)
        ;

        if (this.params.editorMode === 'ajax' && this.params.editorContainer.length > 0) {

            if (is_new) {
                var row_id =  'new_' + (new Date().getTime()) + '' + Math.floor(Math.random() * 900) + 100;
                this.appendRow(row_id);
                this.initSelectableCheckbox();
                this.initEditButtonStyle();
            } else {
                this.editRow(id);
            }

            var container = $("#" + this.params.editorContainer);
            if (container.length > 0) {
                container.find('[id^=' + this.params.editorContainer + '_]').addClass('hide');
            }

            var myst = container.find('.myst');
            myst.removeClass('hide');

            var current = is_new ? [] : container.find('[id=' + this.params.editorContainer + '_' + id + ']');
            if (current.length > 0) {
                current.removeClass('hide');
                myst.addClass('hide');
                $(this.table).find('tr').removeClass('editing');
                $(this.table).find('tr[data-id="' + id + '"]').addClass('editing');
            } else {
                nabu.loadLibrary('Ajax', function() {
                    var ajax = new Nabu.Ajax.Connector(target, 'GET');
                    ajax.addEventListener(new Nabu.Event({
                        onLoad: function(e) {
                            var cont_id = Self.params.editorContainer + '_'
                                        + (is_new ? row_id : id);
                            container.append('
' + e.params.text + '
');
                            if (is_new) {
                                var multiform=container.find('form[data-multiform-part]');
                                multiform.each(function() {
                                    var part = $(this).data('multiform-part');
                                    $(this).attr('data-multiform-part', $.sprintf(part, row_id));
                                    $(this).data('multiform-part', $.sprintf(part, row_id));
                                });
                            }
                            $(Self.table).find('tr').removeClass('editing');
                            $(Self.table).find('tr[data-id="' + (is_new ? row_id : id) + '"]').addClass('editing');
                            Self.events.fireEvent('onLoadEditor', Self, {
                                id: (is_new ? row_id : id),
                                container_id: cont_id
                            });
                            myst.addClass('hide');
                        },
                        onError: function(e) {
                            myst.addClass('hide');
                        }
                    }));
                    ajax.execute();
                });
            }
        } else if (this.params.editorMode === 'page') {
            document.location = target;
        }

        return false;
    },

    appendRow: function(row_id)
    {
        if (this.table !== null) {
            var row = this.table.insertRow(this.table.rows.length);
            $(row).attr('data-id', row_id);
            if (this.params.editButton==='line') {
                $(row).addClass('btn-edit-line');
            }
            if (this.table.tHead.rows.length > 0) {
                var head_row = this.table.tHead.rows[0];
                for (var i=0; i < head_row.cells.length; i++) {
                    var head_cell = head_row.cells[i];
                    var cell = row.insertCell();
                    if (head_cell.hasAttribute('data-toggle') && head_cell.getAttribute('data-toggle') === 'table-selectable') {
                        cell.setAttribute('data-toggle', 'table-selectable');
                        cell.innerHTML = "<input type=\"checkbox\">";
                    }
                    if (head_cell.hasAttribute('class')) {
                        cell.setAttribute('class', head_cell.getAttribute('class'));
                    }
                    if (head_cell.hasAttribute('data-name')) {
                        cell.setAttribute('data-name', head_cell.getAttribute('data-name'));
                    }
                    if (head_cell.hasAttribute('data-align')) {
                        $(cell).addClass(head_cell.getAttribute('data-align'));
                    }
                    if (head_cell.hasAttribute('data-is-id') && head_cell.getAttribute('data-is-id') === 'true') {
                        $(cell).html('');
                    }
                }
            }
        }
    },

    editRow: function(row_id)
    {
        if (this.table !== null) {
            var body_row = $(this.table).find('tbody tr[data-id="' + row_id + '"]').get(0);
            var head_row = this.table.tHead.rows[0];
            if (body_row.cells.length === head_row.cells.length) {
                for (var i = 0; i < head_row.cells.length; i++) {
                    var head_cell = head_row.cells[i];
                    if ($(head_cell).data('is-id')) {
                        var body_cell = body_row.cells[i];
                        if ($(body_cell).find('.edited').length === 0) {
                            $('')
                                .insertBefore($(body_cell).children().get(0))
                            ;
                        }
                    }
                }
            }
        }
    },

    doSelectableHeadCheckbox: function(e)
    {
        e.stopPropagation();

        var checks = $(this.container).find('tbody th[data-toggle="table-selectable"] input[type="checkbox"]');
        var head = $(e.currentTarget);
        if (e.currentTarget.checked) {
            checks.prop('checked', true);
        } else {
            checks.prop('checked', false);
        }

        this.enableToolbarButtons();

        return true;
    },

    doSelectableBodyCheckbox: function(e)
    {
        e.stopPropagation();

        var head = $(this.container).find('thead th[data-toggle="table-selectable"] input[type="checkbox"]');
        var total = $(this.container).find('tbody th[data-toggle="table-selectable"] input[type="checkbox"]').length;
        var checks = $(this.container).find('tbody th[data-toggle="table-selectable"] input[type="checkbox"]:checked').length;

        head.prop('checked', (total === checks));

        this.enableToolbarButtons();

        return true;
    },

    getSelectedItems: function()
    {
        var selected = [];

        $(this.container)
            .find('tbody th[data-toggle="table-selectable"] input[type="checkbox"]:checked')
            .closest('tr')
            .each(function(e) {
                if ($(this).data('id')) {
                    selected.push($(this).data('id'));
                }
            })
        ;

        return selected.length > 0 ? selected : null;
    },

    connectForm: function(table_row_id, form_id)
    {
        var $form = $(form_id);
        if ($form.length === 1) {
            var form = $form.get(0);
            if (form.nabuForm) {
                var Self = this;
                form.nabuForm.addEventListener(new Nabu.Event({
                    onFieldChange: function(e, params) {
                        var head_cell = $(Self.table).find("thead th[data-name=\"" + e.params.field + "\"]");
                        if (head_cell.length === 1) {
                            var text = e.params.value;
                            var head_lookup = head_cell.data('lookup');
                            if ((typeof head_lookup) !== "undefined") {
                                text = head_lookup[e.params.value];
                            }
                            $(Self.table)
                                .find("tbody tr[data-id=\"" + table_row_id + "\"] td[data-name=\"" + e.params.field + "\"]")
                                .text(text)
                            ;
                        }
                    }
                }));
            } else {
                console.log("Nabu.Form object not found");
            }
        } else {
            console.log("More than one forms found with same identifier");
        }
    }
};

nabu.registerLibrary('Table', ['Event', 'Ajax']);
<commit_msg>Solve issue when check items in a table<commit_after>try {
    if (!Nabu) throw "Nabu Manager not loaded";
} catch (e) {
    throw "Nabu Manager not loaded";
}

if (typeof Nabu.UI === 'undefined') {
    Nabu.UI = function() {};
}

Nabu.UI.Table = function(object, params)
{
    this.events = new Nabu.EventPool();
    this.container = object;
    this.params = params;

    try {
        this.table = $(object).find('table').get(0);
    } catch (e) {
        this.table = null;
    }

    this.init();
};

Nabu.UI.Table.prototype = {

    addEventListener: function(event)
    {
        this.events.addEventListener(event);
    },

    removeEventListener: function(event)
    {
        this.events.removeEventListener(event);
    },

    init: function()
    {
        this.initUI();
        this.initPager();
        this.initEditButtonStyle();
        this.initSelectableCheckbox();
        this.initToolbar();
    },

    initUI: function()
    {
        var Self = this;

        $(window).resize(function() {
            var cells = $(Self.container).find('tbody tr[data-type="row"]:first').children();
            var widths = cells.map(function() {
                return $(this).width();
            }).get();

            $(Self.container).find('thead tr').children().each(function (i, v) {
                $(v).width(widths[i]);
            });
        }).resize();
    },

    initPager: function()
    {
        if (this.params.tablePager && this.params.tableSize > 0) {
            var pager = $(this.container).find('.table-pager');
            var rows = $(this.container).find('tbody > tr');
            if (pager.length === 0) {
                var html =
                    "
" +
                        "" +
                            "
" +
                                "
«
" +
                                "
1
" +
                                "
2
" +
                                "
3
" +
                                "
4
" +
                                "
5
" +
                                "
»
" +
                            "
" +
                        "" +
                    "
"
                ;
                $(this.container).append(html);
                pager = $(this.container).find('.table-pager');
            } else {
                pager.addClass("hide");
            }

            if (this.params.tableSize < rows.length) {
                pager.removeClass("hide");
            }
        }
    },

    initEditButtonStyle: function()
    {
        var Self = this;

        if (this.params.editButton === 'button') {
            $(this.container).find('.btn-editor')
                .unbind('click')
                .on('click', function(e) {
                    return Self.doEditButtonClick(e);
                })
            ;
        } else if (this.params.editButton === 'line') {
            $(this.container).find('tr[data-id]')
                .unbind('click')
                .on('click', function(e) {
                    return Self.doEditButtonClick(e);
                })
            ;
        }
    },

    initSelectableCheckbox: function()
    {
        var Self = this;

        $(this.container).find('thead th[data-toggle="table-selectable"] input[type="checkbox"]')
            .unbind('click')
            .on('click', function(e) {
                return Self.doSelectableHeadCheckbox(e);
            })
        ;

        $(this.container).find('tbody td[data-toggle="table-selectable"] input[type="checkbox"]')
            .unbind('click')
            .on('click', function(e) {
                return Self.doSelectableBodyCheckbox(e);
            })
        ;
    },

    initToolbar: function()
    {
        var Self = this;

        $(this.container).find('.table-toolbar .btn')
            .on('click', function(e) {
                var data = $(this).data();
                if (data.action) {
                    Self.events.fireEvent('onToolbarClick', Self, {
                        action: data.action,
                        selection: Self.getSelectedItems()
                    });
                }
                if (!data.toggle) {
                    e.preventDefault();
                    return false;
                } else {
                    return true;
                }

            })
        ;

        this.enableToolbarButtons();
    },

    enableToolbarButtons: function()
    {
        var toolbar = $(this.container).find('.table-toolbar');
        if (toolbar.length > 0) {
            var selected = this.getSelectedItems();
            toolbar.find('.btn').attr('disabled', 'disabled');
            if (selected !== null) {
                if (selected.length === 1) {
                    toolbar.find('[data-apply="all"], [data-apply="single"], [data-apply="multiple"]')
                           .removeAttr('disabled');
                } else if (selected.length > 1) {
                    toolbar.find('[data-apply="all"], [data-apply="multiple"]')
                           .removeAttr('disabled');
                }
            } else {
                toolbar.find('[data-apply="all"]')
                       .removeAttr('disabled');
            }
        }
    },

    doEditButtonClick: function(e)
    {
        var id = false;

        if (this.params.editButton === 'line') {
            id = $(e.currentTarget).data('id');
        } else if (this.params.editButton === 'button') {
            id = $(e.currentTarget).closest('[data-id]').data('id');
        } else {
            throw Exception('Invalid editButton value [' + id + ']');
        }

        this.editor(id);
    },

    editor: function(id)
    {
        var Self = this;
        var is_new = ((typeof id) === 'undefined');

        var target = is_new
                   ? $.sprintf(this.params.editor, '')
                   : $.sprintf(this.params.editor, id)
        ;

        if (this.params.editorMode === 'ajax' && this.params.editorContainer.length > 0) {

            if (is_new) {
                var row_id =  'new_' + (new Date().getTime()) + '' + Math.floor(Math.random() * 900) + 100;
                this.appendRow(row_id);
                this.initSelectableCheckbox();
                this.initEditButtonStyle();
            } else {
                this.editRow(id);
            }

            var container = $("#" + this.params.editorContainer);
            if (container.length > 0) {
                container.find('[id^=' + this.params.editorContainer + '_]').addClass('hide');
            }

            var myst = container.find('.myst');
            myst.removeClass('hide');

            var current = is_new ? [] : container.find('[id=' + this.params.editorContainer + '_' + id + ']');
            if (current.length > 0) {
                current.removeClass('hide');
                myst.addClass('hide');
                $(this.table).find('tr').removeClass('editing');
                $(this.table).find('tr[data-id="' + id + '"]').addClass('editing');
            } else {
                nabu.loadLibrary('Ajax', function() {
                    var ajax = new Nabu.Ajax.Connector(target, 'GET');
                    ajax.addEventListener(new Nabu.Event({
                        onLoad: function(e) {
                            var cont_id = Self.params.editorContainer + '_'
                                        + (is_new ? row_id : id);
                            container.append('
' + e.params.text + '
');
                            if (is_new) {
                                var multiform=container.find('form[data-multiform-part]');
                                multiform.each(function() {
                                    var part = $(this).data('multiform-part');
                                    $(this).attr('data-multiform-part', $.sprintf(part, row_id));
                                    $(this).data('multiform-part', $.sprintf(part, row_id));
                                });
                            }
                            $(Self.table).find('tr').removeClass('editing');
                            $(Self.table).find('tr[data-id="' + (is_new ? row_id : id) + '"]').addClass('editing');
                            Self.events.fireEvent('onLoadEditor', Self, {
                                id: (is_new ? row_id : id),
                                container_id: cont_id
                            });
                            myst.addClass('hide');
                        },
                        onError: function(e) {
                            myst.addClass('hide');
                        }
                    }));
                    ajax.execute();
                });
            }
        } else if (this.params.editorMode === 'page') {
            document.location = target;
        }

        return false;
    },

    appendRow: function(row_id)
    {
        if (this.table !== null) {
            var row = this.table.insertRow(this.table.rows.length);
            $(row).attr('data-id', row_id);
            if (this.params.editButton==='line') {
                $(row).addClass('btn-edit-line');
            }
            if (this.table.tHead.rows.length > 0) {
                var head_row = this.table.tHead.rows[0];
                for (var i=0; i < head_row.cells.length; i++) {
                    var head_cell = head_row.cells[i];
                    var cell = row.insertCell();
                    if (head_cell.hasAttribute('data-toggle') && head_cell.getAttribute('data-toggle') === 'table-selectable') {
                        cell.setAttribute('data-toggle', 'table-selectable');
                        cell.innerHTML = "<input type=\"checkbox\">";
                    }
                    if (head_cell.hasAttribute('class')) {
                        cell.setAttribute('class', head_cell.getAttribute('class'));
                    }
                    if (head_cell.hasAttribute('data-name')) {
                        cell.setAttribute('data-name', head_cell.getAttribute('data-name'));
                    }
                    if (head_cell.hasAttribute('data-align')) {
                        $(cell).addClass(head_cell.getAttribute('data-align'));
                    }
                    if (head_cell.hasAttribute('data-is-id') && head_cell.getAttribute('data-is-id') === 'true') {
                        $(cell).html('');
                    }
                }
            }
        }
    },

    editRow: function(row_id)
    {
        if (this.table !== null) {
            var body_row = $(this.table).find('tbody tr[data-id="' + row_id + '"]').get(0);
            var head_row = this.table.tHead.rows[0];
            if (body_row.cells.length === head_row.cells.length) {
                for (var i = 0; i < head_row.cells.length; i++) {
                    var head_cell = head_row.cells[i];
                    if ($(head_cell).data('is-id')) {
                        var body_cell = body_row.cells[i];
                        if ($(body_cell).find('.edited').length === 0) {
                            $('')
                                .insertBefore($(body_cell).children().get(0))
                            ;
                        }
                    }
                }
            }
        }
    },

    doSelectableHeadCheckbox: function(e)
    {
        e.stopPropagation();

        var checks = $(this.container).find('tbody td[data-toggle="table-selectable"] input[type="checkbox"]');
        var head = $(e.currentTarget);
        if (e.currentTarget.checked) {
            checks.prop('checked', true);
        } else {
            checks.prop('checked', false);
        }

        this.enableToolbarButtons();

        return true;
    },

    doSelectableBodyCheckbox: function(e)
    {
        e.stopPropagation();

        var head = $(this.container).find('thead th[data-toggle="table-selectable"] input[type="checkbox"]');
        var total = $(this.container).find('tbody td[data-toggle="table-selectable"] input[type="checkbox"]').length;
        var checks = $(this.container).find('tbody td[data-toggle="table-selectable"] input[type="checkbox"]:checked').length;

        head.prop('checked', (total === checks));

        this.enableToolbarButtons();

        return true;
    },

    getSelectedItems: function()
    {
        var selected = [];

        $(this.container)
            .find('tbody td[data-toggle="table-selectable"] input[type="checkbox"]:checked')
            .closest('tr')
            .each(function(e) {
                if ($(this).data('id')) {
                    selected.push($(this).data('id'));
                }
            })
        ;

        return selected.length > 0 ? selected : null;
    },

    connectForm: function(table_row_id, form_id)
    {
        var $form = $(form_id);
        if ($form.length === 1) {
            var form = $form.get(0);
            if (form.nabuForm) {
                var Self = this;
                form.nabuForm.addEventListener(new Nabu.Event({
                    onFieldChange: function(e, params) {
                        var head_cell = $(Self.table).find("thead th[data-name=\"" + e.params.field + "\"]");
                        if (head_cell.length === 1) {
                            var text = e.params.value;
                            var head_lookup = head_cell.data('lookup');
                            if ((typeof head_lookup) !== "undefined") {
                                text = head_lookup[e.params.value];
                            }
                            $(Self.table)
                                .find("tbody tr[data-id=\"" + table_row_id + "\"] td[data-name=\"" + e.params.field + "\"]")
                                .text(text)
                            ;
                        }
                    }
                }));
            } else {
                console.log("Nabu.Form object not found");
            }
        } else {
            console.log("More than one forms found with same identifier");
        }
    }
};

nabu.registerLibrary('Table', ['Event', 'Ajax']);
<|endoftext|>


<commit_before>// Imports
// var Milestone = require('./Milestone.js').Milestone;

// Set things up
var startDate = new Date(1983, 4, 5); // TODO - don't hardcode

var resultsContainer = document.getElementById("results_container");
var results = [];

function updateResults() {
  console.log("Updating Results");

  var hide_cats = !document.getElementById("check_cats").checked;
  var hide_dogs = !document.getElementById("check_dogs").checked;
  var hide_red  = !document.getElementById("check_red").checked;
  var hide_blue = !document.getElementById("check_blue").checked;

  for (result of results) {
    result.style.display = "block";

    if (hide_cats && result.animal == 'cat') {
      result.style.display = "none";
    }

    if (hide_dogs && result.animal == 'dog') {
      result.style.display = "none";
    }

    if (hide_red && result.color == 'red') {
      result.style.display = "none";
    }

    if (hide_blue && result.color == 'blue') {
      result.style.display = "none";
    }
  }
}

function loadDummyData() {
  var sizes = ['small', 'big'];
  var animals = ['cat', 'dog', 'mouse'];
  var colors = ['red', 'green', 'blue'];

  for (size of sizes) {
    for (animal of animals) {
      for (color of colors) {
        // var Milestone = new Milestone(startDate, time_unit, time_number, blank_html_element);
        var res = document.createElement("p");
        var text = document.createTextNode([size, color, animal].join());
        res.appendChild(text);
        res.size = size;
        res.animal = animal;
        res.color = color;
        results.push(res);
        resultsContainer.appendChild(res);
      }
    }
  }
}

function wireUpInputs() {
  document.getElementById("check_odds").onchange = updateResults;
  document.getElementById("check_evens").onchange = updateResults;
  document.getElementById("check_small").onchange = updateResults;
}

wireUpInputs();
loadDummyData();
updateResults();
<commit_msg>animals and colors fixbug<commit_after>// Imports
// var Milestone = require('./Milestone.js').Milestone;

// Set things up
var startDate = new Date(1983, 4, 5); // TODO - don't hardcode

var resultsContainer = document.getElementById("results_container");
var results = [];

function updateResults() {
  console.log("Updating Results");

  var hide_cats = !document.getElementById("check_cats").checked;
  var hide_dogs = !document.getElementById("check_dogs").checked;
  var hide_red  = !document.getElementById("check_red").checked;
  var hide_blue = !document.getElementById("check_blue").checked;

  for (result of results) {
    result.style.display = "block";

    if (hide_cats && result.animal == 'cat') {
      result.style.display = "none";
    }

    if (hide_dogs && result.animal == 'dog') {
      result.style.display = "none";
    }

    if (hide_red && result.color == 'red') {
      result.style.display = "none";
    }

    if (hide_blue && result.color == 'blue') {
      result.style.display = "none";
    }
  }
}

function loadDummyData() {
  var sizes = ['small', 'big'];
  var animals = ['cat', 'dog', 'mouse'];
  var colors = ['red', 'green', 'blue'];

  for (size of sizes) {
    for (animal of animals) {
      for (color of colors) {
        // var Milestone = new Milestone(startDate, time_unit, time_number, blank_html_element);
        var res = document.createElement("p");
        var text = document.createTextNode([size, color, animal].join());
        res.appendChild(text);
        res.size = size;
        res.animal = animal;
        res.color = color;
        results.push(res);
        resultsContainer.appendChild(res);
      }
    }
  }
}

function wireUpInputs() {
  document.getElementById("check_cats").onchange = updateResults;
  document.getElementById("check_dogs").onchange = updateResults;
  document.getElementById("check_red").onchange = updateResults;
  document.getElementById("check_blue").onchange = updateResults;
}

wireUpInputs();
loadDummyData();
updateResults();
<|endoftext|>


<commit_before>/**
 * FCViz
 * Payload script for loan auction pages
 */

window.fcViz = function (e) {
  targetUrl = $(e.target).attr('href');
  switch(targetUrl) {
    case "#bids-summary":
      if ($("#bids_summary_chart").length == 0) {
        renderBidSummaryCharts();
      }
      break;
    default:
      break;
  }
}

$('.tabs').tabs().bind('change', window.fcViz);

//Observe mutations made to #bids-summary, so that we can reapply window.fcViz
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if(mutation.addedNodes.length > 0 && mutation.addedNodes[0].id == "bids_summary") {
      renderBidSummaryCharts();
    }
  })
});

observer.observe(document, { childList: true, subtree: true });

var bidSummaryTab = $("#bids-summary")[0];

if (bidSummaryTab.attributes["class"].value.indexOf("active") != -1) {
  renderBidSummaryCharts();
}

function renderBidSummaryCharts() {
  var tableOrig = $("#bids_summary").find("table");

  var rows = jQuery(tableOrig).find("tbody");

  //TODO: iterate through the bid-groups and note information about the user's bid.
  //Interpolate that on the chart.

  //Remove the column of the table since it containing the status of the bids at that rate
  //Capture the rate found in the first element (because FC may mangle the rate
  //when including user bids), then trim the last element
  var rateRegexp = /\d+\.\d%/;
  var data = [];
  rows.children().filter(":not(.sub-accepted, .sub-group)").each(function(){
    data.push({
      name: +$(this).attr("data-annualised_rate"),
      value: +$(this).attr("data-amount")
    });
  });

  if (data.length > 1) {
    data[0].name = "Rej";
  }

  var rowCount = rows.children().size();

  var chartControlDiv = document.createElement("div");
  chartControlDiv.id = "bids_summary_chart_control";

  tableOrig.before(chartControlDiv);

  var margin = {top: 20, right: 30, bottom: 30, left: 55},
    width = $("#bids_summary").width() * 0.95 - margin.left - margin.right,
    height = 250 - margin.top - margin.bottom;

  var x = d3.scale.ordinal()
      .rangeRoundBands([0, width], .1);

  var y = d3.scale.linear()
      .range([height, 0]);

  var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom");

  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left");

  var chart = d3.select("#bids_summary_chart_control").append("svg")
      .attr("id", "bids_summary_viz")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  x.domain(data.map(function(d) { return d.name; }));
  y.domain([0, d3.max(data, function(d) { return d.value; })]);

  chart.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  chart.append("g").call(yAxis);

  chart.selectAll("rect")
    .data(data)
  .enter().append("rect")
    .attr("x", function(d) { return x(d.name+""); })
    .attr("y", function(d) { return y(d.value); })
    .attr("height", function(d) { return height - y(d.value); })
    .attr("width", x.rangeBand());

}
<commit_msg>Clarify comments<commit_after>/**
 * FCViz
 * Payload script for loan auction pages
 */

window.fcViz = function (e) {
  targetUrl = $(e.target).attr('href');
  switch(targetUrl) {
    case "#bids-summary":
      if ($("#bids_summary_chart").length == 0) {
        renderBidSummaryCharts();
      }
      break;
    default:
      break;
  }
}

$('.tabs').tabs().bind('change', window.fcViz);

//Observe mutations made to #bids-summary, so that we can reapply window.fcViz
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if(mutation.addedNodes.length > 0 && mutation.addedNodes[0].id == "bids_summary") {
      renderBidSummaryCharts();
    }
  })
});

observer.observe(document, { childList: true, subtree: true });

var bidSummaryTab = $("#bids-summary")[0];

if (bidSummaryTab.attributes["class"].value.indexOf("active") != -1) {
  renderBidSummaryCharts();
}

function renderBidSummaryCharts() {
  var tableOrig = $("#bids_summary").find("table");

  var rows = jQuery(tableOrig).find("tbody");

  //TODO: iterate through the bid-groups and note information about the user's bid.
  //Interpolate that on the chart.

  //Capture the rate and amount found in the first element
  //(because FC may mangle the rate when including user bids)
  var rateRegexp = /\d+\.\d%/;
  var data = [];
  rows.children().filter(":not(.sub-accepted, .sub-group)").each(function(){
    data.push({
      name: +$(this).attr("data-annualised_rate"),
      value: +$(this).attr("data-amount")
    });
  });

  if (data.length > 1) {
    data[0].name = "Rej";
  }

  var rowCount = rows.children().size();

  var chartControlDiv = document.createElement("div");
  chartControlDiv.id = "bids_summary_chart_control";

  tableOrig.before(chartControlDiv);

  var margin = {top: 20, right: 30, bottom: 30, left: 55},
    width = $("#bids_summary").width() * 0.95 - margin.left - margin.right,
    height = 250 - margin.top - margin.bottom;

  var x = d3.scale.ordinal()
      .rangeRoundBands([0, width], .1);

  var y = d3.scale.linear()
      .range([height, 0]);

  var xAxis = d3.svg.axis()
      .scale(x)
      .orient("bottom");

  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left");

  var chart = d3.select("#bids_summary_chart_control").append("svg")
      .attr("id", "bids_summary_viz")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  x.domain(data.map(function(d) { return d.name; }));
  y.domain([0, d3.max(data, function(d) { return d.value; })]);

  chart.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  chart.append("g").call(yAxis);

  chart.selectAll("rect")
    .data(data)
  .enter().append("rect")
    .attr("x", function(d) { return x(d.name+""); })
    .attr("y", function(d) { return y(d.value); })
    .attr("height", function(d) { return height - y(d.value); })
    .attr("width", x.rangeBand());

}
<|endoftext|>


<commit_before>//=============================================================================
// marker
//=============================================================================
var MarkerCluster;

function MapOverlay(map,data,manager_ref,select_comp_list) {
    if(!MarkerCluster){
        MarkerCluster=new MarkerClusterer(map);
        MarkerCluster.setGridSize(50);
        MarkerCluster.setMaxZoom(15);
    }
    this.select_comp_list=select_comp_list;
    this.map_ = map;
    this.data_ = data;
    this.id=data.id;
    this.info= new google.maps.InfoWindow();
    this.info.setOptions({"disableAutoPan":false});//吹き出しを地図の中心に持ってくるか
    this.marker_color={1:'FC7790',5:'32ceff',99:'44f186'};//1:未完了 5:完了　99:ブックマーク時のアイコン色
    this.latlng=null;
    var geo=eval("a="+this.data_.geometry);
    if(geo.coordinates){
        if(!isNaN(parseInt(geo.coordinates[1]))&& !isNaN(parseInt(geo.coordinates[0]))){
            this.latlng=new google.maps.LatLng(geo.coordinates[1],geo.coordinates[0]);
        }else{
            this.latlng=new google.maps.LatLng("39.8781539650443","139.84579414129257");//往く当てが無いなら富士山でも登りたい
        }
    }

    //this.marker = new google.maps.Marker({'map': this.map_,'position': this.latlng});
    this.marker = new google.maps.Marker();
    this.marker.setPosition(this.latlng);
    MarkerCluster.addMarker(this.marker); // markerclusterを表示（間引き表示）

    // this.marker.setMap(map);//マーカーでの表示

    /* マーカーがクリックされた時 */
    var self=this;
    google.maps.event.addListener(this.marker, 'click', function() {
        self.show_info(true);
    });
}
/**
 * アイコン生成
 */
MapOverlay.prototype.createIco_img = function(is_select) {
    var status_id=this.data_.status.id;
    var color=is_select?this.marker_color[99]:this.marker_color[status_id];
    var status= this.data_.status.name.substring(0,1);
    return "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+status+"|"+color+"|000000";
}

/**
 * 吹き出し表示
 * @param flg 表示・非表示
 */

MapOverlay.prototype.show_info = function(flg) {
    if(flg){
        if(currentInfoWindow){
            currentInfoWindow.close();
        }
        this.info.open(this.map_,this.marker);
        currentInfoWindow=this.info;
        twttr.widgets.load();
    }else{
        this.info.close();
        currentInfoWindow=undefined;
    }
}

MapOverlay.prototype.refresh=function(){
    var id=this.id;
    var description=this.data_.description;
    var subject=this.data_.subject;
    var is_select=this.select_comp_list[id];
    //完了時と未貼り付け時で吹き出しを変える
    if(this.data_.status.id==1){
        //未貼り付け
        var t_str='完了したらtwitterに報告
<textarea id="tweet_txt_'+id+'" class="tweet_txt" name="tweet_txt" >'+TWEET_FORMAT.replace('<$subject$>',subject)+'</textarea>';
        t_str += '

<a href="https://twitter.com/intent/tweet?text=' + encodeURIComponent(TWEET_FORMAT.replace('<$subject$>',subject)) + '" class="twitter-mention-button" data-lang="ja">Tweet to @posterdone';
        if(navigator.userAgent.search(/iPhone|Android/) != -1){
          t_str += '

<a style="text-decoration: underline;" href="twitter://post?message=' + encodeURIComponent(TWEET_FORMAT.replace('<$subject$>',subject)) + '"twitterアプリでツイート';
        }
        //this.info.setContent('
' +'ID:'+id+'
'+subject + '
' + description+'
●'+this.data_.status.name+'
Mark
');
        this.info.setContent('
' +'ID:'+id+'
'+subject + '
' + description+'
●'+this.data_.status.name+'
'+t_str+'
');
    }else{
        //完了・その他
        this.info.setContent('
' +'ID:'+id+'
'+subject + '
' + description+'
●'+this.data_.status.name+"
");
    }
    this.marker.setIcon(this.createIco_img(is_select));
}

MapOverlay.prototype.get_marker_position=function(){
    return this.latlng;
}
MapOverlay.prototype.get_marker=function(){
    return this.marker;
}
MapOverlay.prototype.delete_marker=function(){
    MarkerCluster.removeMarker(this.marker);
}

<commit_msg>url対策<commit_after>//=============================================================================
// marker
//=============================================================================
var MarkerCluster;

function MapOverlay(map,data,manager_ref,select_comp_list) {
    if(!MarkerCluster){
        MarkerCluster=new MarkerClusterer(map);
        MarkerCluster.setGridSize(50);
        MarkerCluster.setMaxZoom(15);
    }
    this.select_comp_list=select_comp_list;
    this.map_ = map;
    this.data_ = data;
    this.id=data.id;
    this.info= new google.maps.InfoWindow();
    this.info.setOptions({"disableAutoPan":false});//吹き出しを地図の中心に持ってくるか
    this.marker_color={1:'FC7790',5:'32ceff',99:'44f186'};//1:未完了 5:完了　99:ブックマーク時のアイコン色
    this.latlng=null;
    var geo=eval("a="+this.data_.geometry);
    if(geo.coordinates){
        if(!isNaN(parseInt(geo.coordinates[1]))&& !isNaN(parseInt(geo.coordinates[0]))){
            this.latlng=new google.maps.LatLng(geo.coordinates[1],geo.coordinates[0]);
        }else{
            this.latlng=new google.maps.LatLng("39.8781539650443","139.84579414129257");//往く当てが無いなら富士山でも登りたい
        }
    }

    //this.marker = new google.maps.Marker({'map': this.map_,'position': this.latlng});
    this.marker = new google.maps.Marker();
    this.marker.setPosition(this.latlng);
    MarkerCluster.addMarker(this.marker); // markerclusterを表示（間引き表示）

    // this.marker.setMap(map);//マーカーでの表示

    /* マーカーがクリックされた時 */
    var self=this;
    google.maps.event.addListener(this.marker, 'click', function() {
        self.show_info(true);
    });
}
/**
 * アイコン生成
 */
MapOverlay.prototype.createIco_img = function(is_select) {
    var status_id=this.data_.status.id;
    var color=is_select?this.marker_color[99]:this.marker_color[status_id];
    var status= this.data_.status.name.substring(0,1);
    return "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+status+"|"+color+"|000000";
}

/**
 * 吹き出し表示
 * @param flg 表示・非表示
 */

MapOverlay.prototype.show_info = function(flg) {
    if(flg){
        if(currentInfoWindow){
            currentInfoWindow.close();
        }
        this.info.open(this.map_,this.marker);
        currentInfoWindow=this.info;
        twttr.widgets.load();
    }else{
        this.info.close();
        currentInfoWindow=undefined;
    }
}

MapOverlay.prototype.refresh=function(){
    var id=this.id;
    var description=this.data_.description;
    var subject=this.data_.subject;
    var is_select=this.select_comp_list[id];
    //完了時と未貼り付け時で吹き出しを変える
    if(this.data_.status.id==1){
        //未貼り付け
        var t_str='完了したらtwitterに報告
<textarea id="tweet_txt_'+id+'" class="tweet_txt" name="tweet_txt" >'+TWEET_FORMAT.replace('<$subject$>',subject)+'</textarea>';
        t_str += '

<a href="https://twitter.com/intent/tweet?url=null&text=' + encodeURIComponent(TWEET_FORMAT.replace('<$subject$>',subject)) + '" class="twitter-mention-button" data-lang="ja">Tweet to @posterdone';
        if(navigator.userAgent.search(/iPhone|Android/) != -1){
          t_str += '

<a style="text-decoration: underline;" href="twitter://post?message=' + encodeURIComponent(TWEET_FORMAT.replace('<$subject$>',subject)) + '"twitterアプリでツイート';
        }
        //this.info.setContent('
' +'ID:'+id+'
'+subject + '
' + description+'
●'+this.data_.status.name+'
Mark
');
        this.info.setContent('
' +'ID:'+id+'
'+subject + '
' + description+'
●'+this.data_.status.name+'
'+t_str+'
');
    }else{
        //完了・その他
        this.info.setContent('
' +'ID:'+id+'
'+subject + '
' + description+'
●'+this.data_.status.name+"
");
    }
    this.marker.setIcon(this.createIco_img(is_select));
}

MapOverlay.prototype.get_marker_position=function(){
    return this.latlng;
}
MapOverlay.prototype.get_marker=function(){
    return this.marker;
}
MapOverlay.prototype.delete_marker=function(){
    MarkerCluster.removeMarker(this.marker);
}

<|endoftext|>


<commit_before>/*global TRCGame*/

TRCGame.generateNextSegment = function (environment) {
  return function () {
    // Save the current game object
    var game = this.game

    // KEep track of the starting X position
    var startX = this.nextStartX

    // Reset the boundaries of the world
    game.world.setBounds(game.camera.x, 0, startX + 500, game.world.height)

    // With a 25% chance, generate a crashed satellite
    if (game.rnd.frac() < 0.25) {
      // Create the satellite at (startX, game.world.height - 64)
      // with the image called 'crashedSat'
      var crashedSat = this.platforms.create(startX,
        game.world.height - 64, 'crashedSat')

      // Add an animation called 'burn' using frames 0, 1, and 2
      // for 10 frames each that does loop
      crashedSat.animations.add('burn', [0, 1, 2], 10, true)

      // Play that animation
      crashedSat.animations.play('burn')

      // Scale up to 2x as big
      crashedSat.scale.setTo(2, 2)

      // Mark as immovable
      crashedSat.body.immovable = true

      // Otherwise, with a 25% chance, generate an alien
    } else if (game.rnd.frac() < 0.25) {
      // Create the alien at (startX, 200)
      // with the image called 'alien'
      var alien = this.aliens.create(startX, 200, 'alien')

      // Add an animation called 'die' using frames 0, 1, and 2
      // for 30 frames each that does not loop
      // (if this worked properly I would not have changed it to 30,
      // but that didn't fix it, so I should probably change it back)
      var alienDeath = alien.animations.add('die', [0, 1, 2], 30, false)

      // Tell this animation that it should kill the alien when it is done
      alienDeath.killOnComplete = true

      // Scale up to 2x as big
      alien.scale.setTo(2, 2)

      // Don't bounce at all when landing on thr ground
      alien.body.bounce.y = 0

      // Follow gravity
      alien.body.gravity.y = 300
    }

    // Place platforms along thr ground
    for (var i = startX; i < startX + 480; i += 48) {
      // Create a platform at (i, game.world.height - 32)
      // with the image called 'platform_' + environment
      // (this will be 'platform_space', etc.)
      var ground = this.platforms.create(i, game.world.height - 32, 'platform_' + environment)

      // Scale up to 2x as big
      ground.scale.setTo(2, 2)

      // Mark as immovable
      ground.body.immovable = true
    }

    // 1/4 of the time, generate a gas can
    if (game.rnd.frac() < 0.25) {
      var gasCan = this.gasCans.create(startX + 200, game.world.height - 64, 'gasCan')
      gasCan.scale.setTo(2, 2)
      // Otherwise, 1/10 of the time, generate a screwdriver
    } else if (game.rnd.frac() < 0.1) {
      var screwdriver = this.screwdrivers.create(startX + 200, game.world.height - 64, 'screwdriver')
      screwdriver.scale.setTo(2, 2)
    }

    // If we've found at least five gas cans...
    if (TRCGame.score.collectibles['gasCan'] >= 5) {
      // 20% of the time...
      if (game.rnd.frac() < 0.2) {
        // Create a rocket
        var rocket = this.rockets.create(startX + 350, game.world.height - 32, 'rocket')

        // Create an animation called 'idle' that only uses frame 0
        // for 10 frames and does not loop
        rocket.animations.add('idle', [0], 10, false)

        // Create a second animation called 'explode' that uses frames
        // 1, 2, 3 for 10 frames each and does not loop
        rocket.animations.add('explode', [1, 2, 3], 10, false)

        // Start by playing the idle animation
        rocket.animations.play('idle')

        // Scale up
        rocket.scale.setTo(2, 2)

        // The coordinates used to create the rocket should be lined up with
        // the middle of the bottom edge of the image itself
        rocket.anchor.setTo(0.5, 1)
      }
    }

    // Make the next startX be 480 away (since we generated 480 pixels of
    // platforms). This is not magic; it can be a different number if that
    // makes sense.
    this.nextStartX = startX + 480
  }
}
<commit_msg>Added more platforms<commit_after>/*global TRCGame*/

TRCGame.generateNextSegment = function (environment) {
  return function () {
    // Save the current game object
    var game = this.game

    // KEep track of the starting X position
    var startX = this.nextStartX

    // Reset the boundaries of the world
    game.world.setBounds(game.camera.x, 0, startX + 500, game.world.height)

    // With a 25% chance, generate a crashed satellite
    if (game.rnd.frac() < 0.25) {
      // Create the satellite at (startX, game.world.height - 64)
      // with the image called 'crashedSat'
      var crashedSat = this.platforms.create(startX,
        game.world.height - 64, 'crashedSat')

      // Add an animation called 'burn' using frames 0, 1, and 2
      // for 10 frames each that does loop
      crashedSat.animations.add('burn', [0, 1, 2], 10, true)

      // Play that animation
      crashedSat.animations.play('burn')

      // Scale up to 2x as big
      crashedSat.scale.setTo(2, 2)

      // Mark as immovable
      crashedSat.body.immovable = true

    } else if (game.rnd.frac() < 0.6) {
        var random = game.rnd.integerInRange(80,150)
          var normalSat = this.platforms.create(startX ,
            game.world.height - 100 , 'satellite')
            normalSat.scale.setTo(2, 2)
            normalSat.body.immovable = true

      // Otherwise, with a 25% chance, generate an alien
    } else if (game.rnd.frac() < 0.25) {
      // Create the alien at (startX, 200)
      // with the image called 'alien'
      var alien = this.aliens.create(startX, 200, 'alien')

      // Add an animation called 'die' using frames 0, 1, and 2
      // for 30 frames each that does not loop
      // (if this worked properly I would not have changed it to 30,
      // but that didn't fix it, so I should probably change it back)
      var alienDeath = alien.animations.add('die', [0, 1, 2], 30, false)

      // Tell this animation that it should kill the alien when it is done
      alienDeath.killOnComplete = true

      // Scale up to 2x as big
      alien.scale.setTo(2, 2)

      // Don't bounce at all when landing on thr ground
      alien.body.bounce.y = 0

      // Follow gravity
      alien.body.gravity.y = 300
    }

    // Place platforms along thr ground
    for (var i = startX; i < startX + 480; i += 48) {
      // Create a platform at (i, game.world.height - 32)
      // with the image called 'platform_' + environment
      // (this will be 'platform_space', etc.)
      var ground = this.platforms.create(i, game.world.height - 32, 'platform_' + environment)

      // Scale up to 2x as big
      ground.scale.setTo(2, 2)

      // Mark as immovable
      ground.body.immovable = true
    }

    // 1/4 of the time, generate a gas can
    if (game.rnd.frac() < 0.25) {
      var gasCan = this.gasCans.create(startX + 200, game.world.height - 90, 'gasCan')
      gasCan.scale.setTo(2, 2)
      // Otherwise, 1/10 of the time, generate a screwdriver
    } else if (game.rnd.frac() < 0.1) {
      var screwdriver = this.screwdrivers.create(startX + 200, game.world.height - 64, 'screwdriver')
      screwdriver.scale.setTo(2, 2)
    }

    // If we've found at least five gas cans...
    if (TRCGame.score.collectibles['gasCan'] >= 10) {
      // 20% of the time...
      if (game.rnd.frac() < 0.1) {
        // Create a rocket
        var rocket = this.rockets.create(startX + 350, game.world.height - 32, 'rocket')

        // Create an animation called 'idle' that only uses frame 0
        // for 10 frames and does not loop
        rocket.animations.add('idle', [0], 10, false)

        // Create a second animation called 'explode' that uses frames
        // 1, 2, 3 for 10 frames each and does not loop
        rocket.animations.add('explode', [1, 2, 3], 10, false)

        // Start by playing the idle animation
        rocket.animations.play('idle')

        // Scale up
        rocket.scale.setTo(2, 2)

        // The coordinates used to create the rocket should be lined up with
        // the middle of the bottom edge of the image itself
        rocket.anchor.setTo(0.5, 1)
      }
    }

    // Make the next startX be 480 away (since we generated 480 pixels of
    // platforms). This is not magic; it can be a different number if that
    // makes sense.
    this.nextStartX = startX + 50
  }
}
<|endoftext|>


<commit_before>// Copyright 2002-2012, University of Colorado

/**
 * Images
 *
 * TODO: setImage / getImage and the whole toolchain that uses that
 *
 * TODO: SVG support
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'scenery' );

  var inherit = require( 'PHET_CORE/inherit' );
  var Bounds2 = require( 'DOT/Bounds2' );

  var scenery = require( 'SCENERY/scenery' );

  var Node = require( 'SCENERY/nodes/Node' ); // Image inherits from Node
  var Renderer = require( 'SCENERY/layers/Renderer' ); // we need to specify the Renderer in the prototype
  var objectCreate = require( 'SCENERY/util/Util' ).objectCreate;

  /*
   * Canvas renderer supports the following as 'image':
   *     URL (string)             // works, but does NOT support bounds-based parameter object keys like 'left', 'centerX', etc.
   *                              // also necessary to force updateScene() after it has loaded
   *     HTMLImageElement         // works
   *     HTMLVideoElement         // not tested
   *     HTMLCanvasElement        // works, and forces the canvas renderer
   *     CanvasRenderingContext2D // not tested, but bad luck in past
   *     ImageBitmap              // good luck creating this. currently API for window.createImageBitmap not implemented
   * SVG renderer supports the following as 'image':
   *     URL (string)
   *     HTMLImageElement
   */
  scenery.Image = function Image( image, options ) {
    assert && assert( image, "image should be available" );

    // allow not passing an options object
    options = options || {};

    // rely on the setImage call from the super constructor to do the setup
    if ( image ) {
      options.image = image;
    }

    var self = this;
    // allows us to invalidate our bounds whenever an image is loaded
    this.loadListener = function( event ) {
      self.invalidateImage();

      // don't leak memory!
      self._image.removeEventListener( 'load', self.loadListener );
    };

    Node.call( this, options );
  };
  var Image = scenery.Image;

  inherit( Image, Node, {
    invalidateImage: function() {
      this.invalidateSelf( new Bounds2( 0, 0, this.getImageWidth(), this.getImageHeight() ) );
    },

    getImage: function() {
      return this._image;
    },

    setImage: function( image ) {
      var self = this;

      if ( this._image !== image && ( typeof image !== 'string' || !this._image || image !== this._image.src ) ) {
        // don't leak memory by referencing old images
        if ( this._image ) {
          this._image.removeEventListener( 'load', this.loadListener );
        }

        if ( typeof image === 'string' ) {
          // create an image with the assumed URL
          var src = image;
          image = document.createElement( 'img' );
          image.addEventListener( 'load', this.loadListener );
          image.src = src;
        } else if ( image instanceof HTMLImageElement ) {
          // only add a listener if we probably haven't loaded yet
          if ( !image.width || !image.height ) {
            image.addEventListener( 'load', this.loadListener );
          }
        }

        // swap supported renderers if necessary
        if ( image instanceof HTMLCanvasElement ) {
          if ( !this.hasOwnProperty( '_supportedRenderers' ) ) {
            this._supportedRenderers = [ Renderer.Canvas ];
            this.markLayerRefreshNeeded();
          }
        } else {
          if ( this.hasOwnProperty( '_supportedRenderers' ) ) {
            delete this._supportedRenderers; // will leave prototype intact
            this.markLayerRefreshNeeded();
          }
        }

        this._image = image;
        this.invalidateImage(); // yes, if we aren't loaded yet this will give us 0x0 bounds
      }
      return this;
    },

    invalidateOnImageLoad: function( image ) {
      var self = this;
      var listener = function( event ) {
        self.invalidateImage();

        // don't leak memory!
        image.removeEventListener( listener );
      };
      image.addEventListener( listener );
    },

    getImageWidth: function() {
      return this._image.width;
    },

    getImageHeight: function() {
      return this._image.height;
    },

    getImageURL: function() {
      return this._image.src;
    },

    // signal that we are actually rendering something
    isPainted: function() {
      return true;
    },

    /*---------------------------------------------------------------------------*
    * Canvas support
    *----------------------------------------------------------------------------*/

    // TODO: add SVG / DOM support
    paintCanvas: function( wrapper ) {
      wrapper.context.drawImage( this._image, 0, 0 );
    },

    /*---------------------------------------------------------------------------*
    * WebGL support
    *----------------------------------------------------------------------------*/

    paintWebGL: function( state ) {
      throw new Error( 'paintWebGL:nimplemented' );
    },

    /*---------------------------------------------------------------------------*
    * SVG support
    *----------------------------------------------------------------------------*/

    createSVGFragment: function( svg, defs, group ) {
      var element = document.createElementNS( 'http://www.w3.org/2000/svg', 'image' );
      element.setAttribute( 'x', 0 );
      element.setAttribute( 'y', 0 );
      return element;
    },

    updateSVGFragment: function( element ) {
      // like <image xlink:href='http://phet.colorado.edu/images/phet-logo-yellow.png' x='0' y='0' height='127px' width='242px'/>
      var xlinkns = 'http://www.w3.org/1999/xlink';

      element.setAttribute( 'width', this.getImageWidth() + 'px' );
      element.setAttribute( 'height', this.getImageHeight() + 'px' );
      element.setAttributeNS( xlinkns, 'xlink:href', this.getImageURL() );
    },

    /*---------------------------------------------------------------------------*
    * DOM support
    *----------------------------------------------------------------------------*/

    getDOMElement: function() {
      this._image.style.display = 'block';
      this._image.style.position = 'absolute';
      return this._image;
    },

    updateCSSTransform: function( transform ) {
      $( this._image ).css( transform.getMatrix().getCSSTransformStyles() );
    },

    set image( value ) { this.setImage( value ); },
    get image() { return this.getImage(); },

    getBasicConstructor: function( propLines ) {
      return 'new scenery.Image( \'' + this._image.src.replace( /'/g, '\\\'' ) + '\', {' + propLines + '} )';
    }
  } );

  Image.prototype._mutatorKeys = [ 'image' ].concat( Node.prototype._mutatorKeys );

  Image.prototype._supportedRenderers = [ Renderer.Canvas, Renderer.SVG, Renderer.DOM ];

  // utility for others
  Image.createSVGImage = function( url, width, height ) {
    var xlinkns = 'http://www.w3.org/1999/xlink';
    var svgns = 'http://www.w3.org/2000/svg';

    var element = document.createElementNS( svgns, 'image' );
    element.setAttribute( 'x', 0 );
    element.setAttribute( 'y', 0 );
    element.setAttribute( 'width', width + 'px' );
    element.setAttribute( 'height', height + 'px' );
    element.setAttributeNS( xlinkns, 'xlink:href', url );

    return element;
  };

  return Image;
} );

<commit_msg>assert that image is available in scenery.Image constructor<commit_after>// Copyright 2002-2012, University of Colorado

/**
 * Images
 *
 * TODO: setImage / getImage and the whole toolchain that uses that
 *
 * TODO: SVG support
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  "use strict";

  var assert = require( 'ASSERT/assert' )( 'scenery' );

  var inherit = require( 'PHET_CORE/inherit' );
  var Bounds2 = require( 'DOT/Bounds2' );

  var scenery = require( 'SCENERY/scenery' );

  var Node = require( 'SCENERY/nodes/Node' ); // Image inherits from Node
  var Renderer = require( 'SCENERY/layers/Renderer' ); // we need to specify the Renderer in the prototype
  var objectCreate = require( 'SCENERY/util/Util' ).objectCreate;

  /*
   * Canvas renderer supports the following as 'image':
   *     URL (string)             // works, but does NOT support bounds-based parameter object keys like 'left', 'centerX', etc.
   *                              // also necessary to force updateScene() after it has loaded
   *     HTMLImageElement         // works
   *     HTMLVideoElement         // not tested
   *     HTMLCanvasElement        // works, and forces the canvas renderer
   *     CanvasRenderingContext2D // not tested, but bad luck in past
   *     ImageBitmap              // good luck creating this. currently API for window.createImageBitmap not implemented
   * SVG renderer supports the following as 'image':
   *     URL (string)
   *     HTMLImageElement
   */
  scenery.Image = function Image( image, options ) {
    assert && assert( image, "image should be available" );

    // allow not passing an options object
    options = options || {};

    // rely on the setImage call from the super constructor to do the setup
    if ( image ) {
      options.image = image;
    }

    var self = this;
    // allows us to invalidate our bounds whenever an image is loaded
    this.loadListener = function( event ) {
      self.invalidateImage();

      // don't leak memory!
      self._image.removeEventListener( 'load', self.loadListener );
    };

    Node.call( this, options );
  };
  var Image = scenery.Image;

  inherit( Image, Node, {
    invalidateImage: function() {
      this.invalidateSelf( new Bounds2( 0, 0, this.getImageWidth(), this.getImageHeight() ) );
    },

    getImage: function() {
      return this._image;
    },

    setImage: function( image ) {
      var self = this;

      if ( this._image !== image && ( typeof image !== 'string' || !this._image || image !== this._image.src ) ) {
        // don't leak memory by referencing old images
        if ( this._image ) {
          this._image.removeEventListener( 'load', this.loadListener );
        }

        if ( typeof image === 'string' ) {
          // create an image with the assumed URL
          var src = image;
          image = document.createElement( 'img' );
          image.addEventListener( 'load', this.loadListener );
          image.src = src;
        } else if ( image instanceof HTMLImageElement ) {
          // only add a listener if we probably haven't loaded yet
          if ( !image.width || !image.height ) {
            image.addEventListener( 'load', this.loadListener );
          }
        }

        // swap supported renderers if necessary
        if ( image instanceof HTMLCanvasElement ) {
          if ( !this.hasOwnProperty( '_supportedRenderers' ) ) {
            this._supportedRenderers = [ Renderer.Canvas ];
            this.markLayerRefreshNeeded();
          }
        } else {
          if ( this.hasOwnProperty( '_supportedRenderers' ) ) {
            delete this._supportedRenderers; // will leave prototype intact
            this.markLayerRefreshNeeded();
          }
        }

        this._image = image;
        this.invalidateImage(); // yes, if we aren't loaded yet this will give us 0x0 bounds
      }
      return this;
    },

    invalidateOnImageLoad: function( image ) {
      var self = this;
      var listener = function( event ) {
        self.invalidateImage();

        // don't leak memory!
        image.removeEventListener( listener );
      };
      image.addEventListener( listener );
    },

    getImageWidth: function() {
      return this._image.width;
    },

    getImageHeight: function() {
      return this._image.height;
    },

    getImageURL: function() {
      return this._image.src;
    },

    // signal that we are actually rendering something
    isPainted: function() {
      return true;
    },

    /*---------------------------------------------------------------------------*
    * Canvas support
    *----------------------------------------------------------------------------*/

    // TODO: add SVG / DOM support
    paintCanvas: function( wrapper ) {
      wrapper.context.drawImage( this._image, 0, 0 );
    },

    /*---------------------------------------------------------------------------*
    * WebGL support
    *----------------------------------------------------------------------------*/

    paintWebGL: function( state ) {
      throw new Error( 'paintWebGL:nimplemented' );
    },

    /*---------------------------------------------------------------------------*
    * SVG support
    *----------------------------------------------------------------------------*/

    createSVGFragment: function( svg, defs, group ) {
      var element = document.createElementNS( 'http://www.w3.org/2000/svg', 'image' );
      element.setAttribute( 'x', 0 );
      element.setAttribute( 'y', 0 );
      return element;
    },

    updateSVGFragment: function( element ) {
      // like <image xlink:href='http://phet.colorado.edu/images/phet-logo-yellow.png' x='0' y='0' height='127px' width='242px'/>
      var xlinkns = 'http://www.w3.org/1999/xlink';

      element.setAttribute( 'width', this.getImageWidth() + 'px' );
      element.setAttribute( 'height', this.getImageHeight() + 'px' );
      element.setAttributeNS( xlinkns, 'xlink:href', this.getImageURL() );
    },

    /*---------------------------------------------------------------------------*
    * DOM support
    *----------------------------------------------------------------------------*/

    getDOMElement: function() {
      this._image.style.display = 'block';
      this._image.style.position = 'absolute';
      return this._image;
    },

    updateCSSTransform: function( transform ) {
      $( this._image ).css( transform.getMatrix().getCSSTransformStyles() );
    },

    set image( value ) { this.setImage( value ); },
    get image() { return this.getImage(); },

    getBasicConstructor: function( propLines ) {
      return "hello";
//      return 'new scenery.Image( \'' + this._image.src.replace( /'/g, '\\\'' ) + '\', {' + propLines + '} )';
    }
  } );

  Image.prototype._mutatorKeys = [ 'image' ].concat( Node.prototype._mutatorKeys );

  Image.prototype._supportedRenderers = [ Renderer.Canvas, Renderer.SVG, Renderer.DOM ];

  // utility for others
  Image.createSVGImage = function( url, width, height ) {
    var xlinkns = 'http://www.w3.org/1999/xlink';
    var svgns = 'http://www.w3.org/2000/svg';

    var element = document.createElementNS( svgns, 'image' );
    element.setAttribute( 'x', 0 );
    element.setAttribute( 'y', 0 );
    element.setAttribute( 'width', width + 'px' );
    element.setAttribute( 'height', height + 'px' );
    element.setAttributeNS( xlinkns, 'xlink:href', url );

    return element;
  };

  return Image;
} );

<|endoftext|>


<commit_before>// GET AO OTHERMUSICS
var final_url = "http://localhost:8000/othermusics";
var aTracks;
var i=0;
var jsonArray = [];

            $.get(final_url).done( function(data) {
                var jsondata = JSON.parse(data);
                var jsonaTracks = jsondata.aTracks; //GUARDAR RESULTADO NO ARRAY DOS aTracks
                aTracks = jsonaTracks; //PASSAR PARA A VARIÁVEL GLOBAL
                getData(i);
                //console.log(aTracks);
});

var getData = function (i) {

    if (i < aTracks.length) {
        show_html(aTracks, i);
        //var jsonVar = "{track_id: '" + aTracks[i].track_id + "', artist_name: '" + aTracks[i].artist_name + "', track_title: '" + aTracks[i].track_title + "', album_title: '"  + aTracks[i].album_title + "'}";
        jsonArray.push(aTracks[i]);
        // console.log(jsonVar);
        console.log(aTracks[i]);
        console.log(jsonArray);
        i++
        getData(i);

    }
   }

var show_html = function (aTracks, i) {
    var element1 = "
" + aTracks[i].artist_name + "	" + aTracks[i].track_title + "	" + aTracks[i].album_title + "
";

    $(".othermusics").append(element1);
    i++;
}

$(document).on("click", ".musictable", function(e){
    var currentId = $(this).attr('id');
    $(this).remove();
    console.log(jsonArray);
    findAndRemove(jsonArray, 'id', currentId);
    e.preventDefault();
});

function findAndRemove(jsonArray, property, value) {
   $.each(jsonArray, function(index, result) {
    if(result[property] == value) {
          //Remove from array
          jsonArray.splice(index, 1);

      }
   });
}<commit_msg>othermusics.js one more version<commit_after>// GET AO OTHERMUSICS
var final_url = "http://localhost:8000/othermusics";
var aTracks;
var i=0;
var jsonArray = [];

            $.get(final_url).done( function(data) {
                var jsondata = JSON.parse(data);
                var jsonaTracks = jsondata.aTracks; //GUARDAR RESULTADO NO ARRAY DOS aTracks
                aTracks = jsonaTracks; //PASSAR PARA A VARIÁVEL GLOBAL
                getData(i);
                //console.log(aTracks);
});

var getData = function (i) {

    if (i < aTracks.length) {
        show_html(aTracks, i);
        //var jsonVar = "{track_id: '" + aTracks[i].track_id + "', artist_name: '" + aTracks[i].artist_name + "', track_title: '" + aTracks[i].track_title + "', album_title: '"  + aTracks[i].album_title + "'}";
        jsonArray.push(aTracks[i]);
        // console.log(jsonVar);
        console.log(aTracks[i]);
        console.log(jsonArray);
        i++
        getData(i);

    }
   }

var show_html = function (aTracks, i) {
    var element1 = "
" + aTracks[i].artist_name + "	" + aTracks[i].track_title + "	" + aTracks[i].album_title + "
";

    $(".othermusics").append(element1);
    i++;
}

$(document).on("click", ".musictable", function(e){
    var currentId = $(this).attr('id');
    $(this).remove();
    console.log(jsonArray);
    //findAndRemove(jsonArray, 'track_id', currentId);
    findAndRemove(jsonArray, currentId);
    e.preventDefault();
});

//function findAndRemove(jsonArray, property, value) {
function findAndRemove(jsonArray, value) {
   $.each(jsonArray, function(index) {
   //$.each(jsonArray, function(index, result) {
    //if(result[property] == value) {
    if($(this).attr('track_id') == value) {
          //Remove from array
          jsonArray.splice(index, 1);

      }
   });
}<|endoftext|>


<commit_before>var prettyDate = {
  format: function(now, time){
    var date = new Date(time || ""),
      diff = (((new Date(now)).getTime() - date.getTime()) / 1000),
      day_diff = Math.floor(diff / 86400);

    if( isNan(day_diff) || day_diff < 0 || day_diff >= 31 )
      return;

    return day_diff === 0 && (
      diff < 60 && "just now" ||
      diff < 120 && "1 minute ago" ||
      diff < 3600 && Math.floor( diff / 60) +
        " minutes ago" ||
      diff < 7200 && "1 hour ago" ||
      diff < 86400 && Math.floor( diff / 3600 ) +
        " hours ago") ||
    day_diff === 1 && "Yesterday" ||
    day_diff < 7 && day_diff + " days ago" ||
    day_diff < 31 && Math.ceil( day_diff / 7 ) +
      " weeks ago";
  },

  update: function(now) {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++ ) {
      if( links[i].title ) {
        var date = prettyDate.format(now, links[i].title);
	if( date) {
	  links[i].innerHTML = date;
	}
      }
    }
  }
};
<commit_msg>fixed syntax error<commit_after>var prettyDate = {
  format: function(now, time){
    var date = new Date(time || ""),
      diff = (((new Date(now)).getTime() - date.getTime()) / 1000),
      day_diff = Math.floor(diff / 86400);

    if( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
      return;

    return day_diff === 0 && (
      diff < 60 && "just now" ||
      diff < 120 && "1 minute ago" ||
      diff < 3600 && Math.floor( diff / 60) +
        " minutes ago" ||
      diff < 7200 && "1 hour ago" ||
      diff < 86400 && Math.floor( diff / 3600 ) +
        " hours ago") ||
    day_diff === 1 && "Yesterday" ||
    day_diff < 7 && day_diff + " days ago" ||
    day_diff < 31 && Math.ceil( day_diff / 7 ) +
      " weeks ago";
  },

  update: function(now) {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++ ) {
      if( links[i].title ) {
        var date = prettyDate.format(now, links[i].title);
	if( date) {
	  links[i].innerHTML = date;
	}
      }
    }
  }
};
<|endoftext|>


<commit_before>/**
 * Created by Tanner Stevens on 11/8/2016.
 */

import { ADD_EVENT, ADD_CAMERA, REMOVE_CAMERA, MODIFY_CAMERA_SETTINGS, ADD_ALERT, REMOVE_ALERT } from './re_actions'
import Camera from './Camera'
import Email from './Email'

const initialState = {
    cameras: [],
    events: [],
    alerts: [],
};

function reducers(state = initialState, action) {
    var newState;
    switch(action.type){
        case ADD_CAMERA:
            return Object.assign(
                {}, state, {
                    cameras: [
                        ...state.cameras,
                        new Camera({name:action.name, source:action.source, port:action.port})
                    ]
                }
            );
        case REMOVE_CAMERA:
            newState = Object.assign({}, state);
            newState.cameras.splice(action.camIndex, 1);
            return newState;
        case MODIFY_CAMERA_SETTINGS:
            console.log(action);
            return Object.assign(
                {}, state, {
                    cameras: state.cameras.map((camera, index) => {
                            if (index===action.camIndex){
                                camera.state.name = action.name;
                                camera.state.source = action.source;
                                camera.state.port = action.port;
                            }
                            return camera;
                        })
                }
            );
        case ADD_EVENT:
            return Object.assign(
                {}, state, {
                    events: [
                        ...state.events,
                        {
                            camIndex: action.camIndex,
                            eventType: action.eventType
                        }
                    ]
                }
            );
        case ADD_ALERT:
            return Object.assign(
                {}, state, {
                    alerts: [
                        ...state.alerts,
                        {
                            camIndex: action.camIndex,
                            eventType: action.eventType,
                            email: action.email
                        }
                    ]
                }
            );
        case REMOVE_ALERT:
            newState = Object.assign({}, state);
            newState.alerts.splice(action.camIndex, 1);
            return newState;
        default:
            return state;
    }
}

export default reducers<commit_msg>Removed email functionality - doesn't work :(<commit_after>/**
 * Created by Tanner Stevens on 11/8/2016.
 */

import { ADD_EVENT, ADD_CAMERA, REMOVE_CAMERA, MODIFY_CAMERA_SETTINGS, ADD_ALERT, REMOVE_ALERT } from './re_actions'
import Camera from './Camera'
import Email from './Email'

const initialState = {
    cameras: [],
    events: [],
    alerts: [],
};

function reducers(state = initialState, action) {
    var newState;
    switch(action.type){
        case ADD_CAMERA:
            return Object.assign(
                {}, state, {
                    cameras: [
                        ...state.cameras,
                        new Camera({name:action.name, source:action.source, port:action.port})
                    ]
                }
            );
        case REMOVE_CAMERA:
            newState = Object.assign({}, state);
            newState.cameras.splice(action.camIndex, 1);
            return newState;
        case MODIFY_CAMERA_SETTINGS:
            console.log(action);
            return Object.assign(
                {}, state, {
                    cameras: state.cameras.map((camera, index) => {
                            if (index===action.camIndex){
                                camera.state.name = action.name;
                                camera.state.source = action.source;
                                camera.state.port = action.port;
                            }
                            return camera;
                        })
                }
            );
        case ADD_EVENT:
            //var email = new Email({email: '', camId: '', event: ''});
            return Object.assign(
                {}, state, {
                    events: [
                        ...state.events,
                        {
                            camIndex: action.camIndex,
                            eventType: action.eventType
                        }
                    ]
                }
            );
        case ADD_ALERT:
            return Object.assign(
                {}, state, {
                    alerts: [
                        ...state.alerts,
                        {
                            camIndex: action.camIndex,
                            eventType: action.eventType,
                            email: action.email
                        }
                    ]
                }
            );
        case REMOVE_ALERT:
            newState = Object.assign({}, state);
            newState.alerts.splice(action.camIndex, 1);
            return newState;
        default:
            return state;
    }
}

export default reducers<|endoftext|>