<commit_before>function Game(Interface) {
    var self = this;

    self.Interface = new Interface;

    self.Interface.on("restart", self.restart.bind(this));
    self.Interface.on("takePoints", self.takePoints.bind(this));
    self.Interface.on("addPoints", self.addPoints.bind(this));
    self.Interface.on("rollDices", self.rollDices.bind(this));
    self.Interface.on("toggleDice", self.toggleDice.bind(this));

    self.setup();
}

Game.prototype.restart = function() {
    this.Interface.setup();
    this.setup();
};

Game.prototype.setup = function() {
    var self = this;
    self.player = {
        score: 0,
        zilch: 0
    };
    self.cpu = {
        score: 0,
        zilch: 0
    };
    self.dices = []

    for (var i = 0; i < 6; i++) {
        var dice = {};
        dice.value = this.random(6);
        dice.disabled = true;
        self.dices[i] = dice;
    }

    self.history = [];

    self.cpuStarts = self.random(2);
    self.cpuSpeed = 1000;

    self.playing = !self.cpuStarts;

    self.points = 0;

    self.Interface.setPlaying(self.playing);
    self.Interface.setPoints(self.points);
    self.Interface.setPlayer(self.player);
    self.Interface.setCpu(self.cpu);
    self.Interface.setDices(self.dices);

    if (self.cpuStarts) {
        self.Interface.showMessage("CPU starts!", 1000, function() {
            setTimeout(function() {
                self.rollDices();
            }, self.cpuSpeed);
        });
    } else {
        self.Interface.showMessage("Player starts!", 0, function() {
            self.Interface.disableRollDices(false);
        });
    }

};

Game.prototype.random = function(int) {
    return Math.floor((Math.random() * int));
};

Game.prototype.rollDices = function(all) {
    var self = this;
    self.Interface.clearMessage();

    var rollCount = 0;
    for (var i = 0; i < 6; i++) {
        self.dices[i] = self.dices[i] || {};
        var dice = self.dices[i];
        if (all || !dice.disabled) {
            dice.value = this.random(6);
            if (all) {
                dice.disabled = false;
            }
            rollCount++;
        }
    }

    if (self.playing && self.player.zilch == 3) {
        self.player.zilch = 0;
    } else if (self.cpu.zilch == 3) {
        self.cpu.zilch = 0;
    }

    if (rollCount == 0) {
        self.rollDices(true);
    } else if (self.checkZilch(rollCount == 6)) {
        self.Interface.animateDices(self.dices, function() {

            if (self.playing) {
                self.player.zilch++;

                var history = {};
                history['player'] = 'Zilch';
                self.history.push(history);

                if (self.player.zilch > 2) {
                    if (self.player.score < 500) {
                        self.player.score = 0;
                    } else {
                        self.player.score -= 500;
                    }

                    var history = {};
                    history['player'] = '-500';
                    self.history.push(history);
                }
            } else {
                self.cpu.zilch++;

                var history = {};
                history['cpu'] = 'Zilch';
                self.history.push(history);

                if (self.cpu.zilch > 2) {
                    if (self.cpu.score < 500) {
                        self.cpu.score = 0;
                    } else {
                        self.cpu.score -= 500;
                    }

                    var history = {};
                    history['cpu'] = '-500';
                    self.history.push(history);
                }

            }

            self.Interface.showMessage("Zilch!", 1000, function() {
                self.endRound();
            });
        });

    } else {
        self.Interface.animateDices(self.dices);
        self.Interface.disableTakePoints(true);
        self.Interface.disableRollDices(true);
        self.Interface.setDices(self.dices);

        if (!self.playing) {
            self.cpuPlay();
        }
    }
};

Game.prototype.checkZilch = function(all) {
    var self = this;

    var rawPoints = [0, 0, 0, 0, 0, 0];
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (all || !dice.disabled) {
            rawPoints[dice.value]++;
        }
    }

    // Zilch?
    return rawPoints[0] < 1 && rawPoints[1] < 3 && rawPoints[2] < 3 && rawPoints[3] < 3 && rawPoints[4] < 1 && rawPoints[5] < 3;
}

Game.prototype.toggleDice = function(diceIndex) {
    var self = this;
    var dice = self.dices[diceIndex];

    if (!dice || dice.disabled) {
        console.error("This should not happen!")
        return;
    }

    dice.selected = !dice.selected;
    var points = self.calculatePoints();
    var valid = true;

    for (var i = 0; i < 6; i++) {
        var toggleDice = self.dices[i];

        if (toggleDice.selected) {
            toggleDice.selected = false;
            var togglePoints = self.calculatePoints();
            if (points > togglePoints) {
                toggleDice.invalid = false;
            } else if (togglePoints == points) {
                toggleDice.invalid = true;
            }

            toggleDice.selected = true;
        } else {
            toggleDice.invalid = false;
        }

        valid &= !toggleDice.invalid;
    }

    if (valid && points > 0 && self.playing) {
        self.Interface.disableRollDices(false);
    } else {
        self.Interface.disableRollDices(true);
    }

    if (valid && self.points + points >= 300 && self.playing) {
        self.Interface.disableTakePoints(false);
    } else {
        self.Interface.disableTakePoints(true);
    }

    self.Interface.setDices(self.dices);
    self.Interface.setPoints(self.points + points);
};

Game.prototype.calculatePoints = function(diceIndex) {
    var self = this;
    var result = [0, 0, 0, 0, 0, 0];
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (dice.selected) {
            result[dice.value]++;
        }
    }

    var straight = true;
    var pairs = 0;
    var triple1 = 0;
    var triple2 = 0;
    for (var i = 0; i < 6; i++) {
        straight &= (result[i] == 1);
        if (result[i] == 2) {
            pairs++;
        }
        if (triple1 == 0 && result[i] > 2) {
            triple1 = i + 1;
        } else if (result[i] > 2) {
            triple2 = i + 1;
        }
    }
    var points = 0;

    if (straight) {
        points += 1500;
    } else if (pairs == 3) {
        points += 1500;
    } else if (triple1) {
        var triple1Points = triple1 * (triple1 == 1 ? 1000 : 100);
        for (var i = 0; i < result[triple1 - 1] - 3; i++) {
            triple1Points *= 2;
        }
        points += triple1Points;

        if (triple2) {
            points += triple2 * (triple2 == 1 ? 1000 : 100);
        }
    }

    // left Ones
    if (pairs < 3 && triple1 != 1 && triple2 != 1) {
        points += result[0] * 100;
    }

    // left Fives
    if (pairs < 3 && triple1 != 5 && triple2 != 5) {
        points += result[4] * 50;
    }

    return points;
}

Game.prototype.addPoints = function() {
    var self = this;

    self.points += self.calculatePoints();

    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (dice.selected) {
            dice.selected = false;
            dice.disabled = true;
        }
    }

    self.Interface.setDices(self.dices);
    self.Interface.setPoints(self.points);
};

Game.prototype.takePoints = function() {
    var self = this;

    self.addPoints();

    if (self.playing) {
        self.player.score += self.points;
        self.player.zilch = 0;
        var history = {};
        history['player'] = self.points;
        self.history.push(history);

    } else {
        self.cpu.score += self.points;
        self.cpu.zilch = 0;
        var history = {};
        history['cpu'] = self.points;
        self.history.push(history);
    }

    self.endRound();
};

Game.prototype.endRound = function() {
    var self = this;

    // Reset
    self.points = 0;

    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        dice.disabled = true;
    }

    self.Interface.disableTakePoints(true);
    self.Interface.disableRollDices(true);
    self.Interface.setDices(self.dices);
    self.Interface.setPoints(self.points);
    self.Interface.setPlayer(self.player);
    self.Interface.setCpu(self.cpu);

    self.Interface.disableTakePoints(true);

    // check score
    var checkScore = self.playing && self.cpuStarts || !self.playing && !self.cpuStarts;

    if (checkScore && self.player.score >= 10000 && self.player.score > self.cpu.score) {
        self.Interface.showMessage("Player wins!")
    } else if (checkScore && self.cpu.score >= 10000 && self.cpu.score > self.player.score) {
        self.Interface.showMessage("CPU wins!")
    } else if (self.player.score >= 10000 && self.player.score == self.cpu.score) {
        self.Interface.showMessage("Remi!")
    } else {
        self.playing = !self.playing;
        self.Interface.setPlaying(self.playing);
        // continue
        if (self.playing) {
            self.Interface.disableRollDices(false);
        }

        if (!self.playing) {
            setTimeout(function() {
                self.rollDices();
            }, self.cpuspeed);
        }
    }

}

Game.prototype.cpuPlay = function() {
    var self = this;

    // first select all available dices
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (!dice.disabled) {
            self.toggleDice(i);
        }
    }

    // check if dice gains points
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        var tmpPoints = self.calculatePoints();
        if (!dice.disabled) {
            self.toggleDice(i);
            if (self.calculatePoints() < tmpPoints) {
                self.toggleDice(i);
            }
        }
    }

    // count free dices
    var freeDices = 0;
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (!dice.disabled && !dice.selected) {
            freeDices++;
        }
    }

    setTimeout(function() {
        // strategy: end round if points >= 300 and less than 4 dices left
        if (self.points + self.calculatePoints() >= 300 && freeDices < 4 && freeDices > 0) {
            self.takePoints();
        } else {
            self.addPoints();
            self.rollDices();
        }
    }, self.cpuSpeed * 2);

}

var game = new Game(Interface);
<commit_msg>fixed cpu speed issues<commit_after>function Game(Interface) {
    var self = this;

    self.Interface = new Interface;

    self.Interface.on("restart", self.restart.bind(this));
    self.Interface.on("takePoints", self.takePoints.bind(this));
    self.Interface.on("addPoints", self.addPoints.bind(this));
    self.Interface.on("rollDices", self.rollDices.bind(this));
    self.Interface.on("toggleDice", self.toggleDice.bind(this));

    self.cpuSpeed = 1500;
    self.setup();
}

Game.prototype.restart = function() {
    this.Interface.setup();
    this.setup();
};

Game.prototype.setup = function() {
    var self = this;
    self.player = {
        score: 0,
        zilch: 0
    };
    self.cpu = {
        score: 0,
        zilch: 0
    };
    self.dices = []

    for (var i = 0; i < 6; i++) {
        var dice = {};
        dice.value = this.random(6);
        dice.disabled = true;
        self.dices[i] = dice;
    }

    self.history = [];

    self.cpuStarts = self.random(2);

    self.playing = !self.cpuStarts;

    self.points = 0;

    self.Interface.setPlaying(self.playing);
    self.Interface.setPoints(self.points);
    self.Interface.setPlayer(self.player);
    self.Interface.setCpu(self.cpu);
    self.Interface.setDices(self.dices);

    if (self.cpuStarts) {
        self.Interface.showMessage("CPU starts!", 1000, function() {
            setTimeout(function() {
                self.rollDices();
            }, self.cpuSpeed);
        });
    } else {
        self.Interface.showMessage("Player starts!", 0, function() {
            self.Interface.disableRollDices(false);
        });
    }

};

Game.prototype.random = function(int) {
    return Math.floor((Math.random() * int));
};

Game.prototype.rollDices = function(all) {
    var self = this;
    self.Interface.clearMessage();

    var rollCount = 0;
    for (var i = 0; i < 6; i++) {
        self.dices[i] = self.dices[i] || {};
        var dice = self.dices[i];
        if (all || !dice.disabled) {
            dice.value = this.random(6);
            if (all) {
                dice.disabled = false;
            }
            dice.selected = false;
            rollCount++;
        }
    }

    if (self.playing && self.player.zilch == 3) {
        self.player.zilch = 0;
    } else if (self.cpu.zilch == 3) {
        self.cpu.zilch = 0;
    }

    if (rollCount == 0) {
        self.rollDices(true);
    } else if (self.checkZilch(rollCount == 6)) {
        self.Interface.animateDices(self.dices, function() {

            if (self.playing) {
                self.player.zilch++;

                var history = {};
                history['player'] = 'Zilch';
                self.history.push(history);

                if (self.player.zilch > 2) {
                    if (self.player.score < 500) {
                        self.player.score = 0;
                    } else {
                        self.player.score -= 500;
                    }

                    var history = {};
                    history['player'] = '-500';
                    self.history.push(history);
                }
            } else {
                self.cpu.zilch++;

                var history = {};
                history['cpu'] = 'Zilch';
                self.history.push(history);

                if (self.cpu.zilch > 2) {
                    if (self.cpu.score < 500) {
                        self.cpu.score = 0;
                    } else {
                        self.cpu.score -= 500;
                    }

                    var history = {};
                    history['cpu'] = '-500';
                    self.history.push(history);
                }

            }

            self.Interface.showMessage("Zilch!", 1000, function() {
                self.endRound();
            });
        });

    } else {
        self.Interface.animateDices(self.dices);
        self.Interface.disableTakePoints(true);
        self.Interface.disableRollDices(true);
        self.Interface.setDices(self.dices);

        if (!self.playing) {
            self.cpuPlay();
        }
    }
};

Game.prototype.checkZilch = function(all) {
    var self = this;

    var rawPoints = [0, 0, 0, 0, 0, 0];
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (all || !dice.disabled) {
            rawPoints[dice.value]++;
        }
    }

    // Zilch?
    return rawPoints[0] < 1 && rawPoints[1] < 3 && rawPoints[2] < 3 && rawPoints[3] < 3 && rawPoints[4] < 1 && rawPoints[5] < 3;
}

Game.prototype.toggleDice = function(diceIndex) {
    var self = this;
    var dice = self.dices[diceIndex];

    if (!dice || dice.disabled) {
        console.error("This should not happen!")
        return;
    }

    dice.selected = !dice.selected;
    var points = self.calculatePoints();
    var valid = true;

    for (var i = 0; i < 6; i++) {
        var toggleDice = self.dices[i];

        if (toggleDice.selected && !toggleDice.disabled) {
            toggleDice.selected = false;
            var togglePoints = self.calculatePoints();
            if (points > togglePoints) {
                toggleDice.invalid = false;
            } else if (togglePoints == points) {
                toggleDice.invalid = true;
            }

            toggleDice.selected = true;
        } else {
            toggleDice.invalid = false;
        }

        valid &= !toggleDice.invalid;
    }

    if (valid && points > 0 && self.playing) {
        self.Interface.disableRollDices(false);
    } else {
        self.Interface.disableRollDices(true);
    }

    if (valid && self.points + points >= 300 && self.playing) {
        self.Interface.disableTakePoints(false);
    } else {
        self.Interface.disableTakePoints(true);
    }

    self.Interface.setDices(self.dices);
    self.Interface.setPoints(self.points + points);
};

Game.prototype.calculatePoints = function(diceIndex) {
    var self = this;
    var result = [0, 0, 0, 0, 0, 0];
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (dice.selected && !dice.disabled) {
            result[dice.value]++;
        }
    }

    var straight = true;
    var pairs = 0;
    var triple1 = 0;
    var triple2 = 0;
    for (var i = 0; i < 6; i++) {
        straight &= (result[i] == 1);
        if (result[i] == 2) {
            pairs++;
        }
        if (triple1 == 0 && result[i] > 2) {
            triple1 = i + 1;
        } else if (result[i] > 2) {
            triple2 = i + 1;
        }
    }
    var points = 0;

    if (straight) {
        points += 1500;
    } else if (pairs == 3) {
        points += 1500;
    } else if (triple1) {
        var triple1Points = triple1 * (triple1 == 1 ? 1000 : 100);
        for (var i = 0; i < result[triple1 - 1] - 3; i++) {
            triple1Points *= 2;
        }
        points += triple1Points;

        if (triple2) {
            points += triple2 * (triple2 == 1 ? 1000 : 100);
        }
    }

    // left Ones
    if (pairs < 3 && triple1 != 1 && triple2 != 1) {
        points += result[0] * 100;
    }

    // left Fives
    if (pairs < 3 && triple1 != 5 && triple2 != 5) {
        points += result[4] * 50;
    }

    return points;
}

Game.prototype.addPoints = function() {
    var self = this;

    self.points += self.calculatePoints();

    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (dice.selected) {
            dice.selected = false;
            dice.disabled = true;
        }
    }

    self.Interface.setDices(self.dices);
    self.Interface.setPoints(self.points);
};

Game.prototype.takePoints = function() {
    var self = this;

    self.addPoints();

    if (self.playing) {
        self.player.score += self.points;
        self.player.zilch = 0;
        var history = {};
        history['player'] = self.points;
        self.history.push(history);

    } else {
        self.cpu.score += self.points;
        self.cpu.zilch = 0;
        var history = {};
        history['cpu'] = self.points;
        self.history.push(history);
    }

    self.endRound();
};

Game.prototype.endRound = function() {
    var self = this;

    // Reset
    self.points = 0;

    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (dice.disabled) {
            dice.selected = true;
        } else {
            dice.disabled = true;
        }
    }

    self.Interface.disableTakePoints(true);
    self.Interface.disableRollDices(true);
    self.Interface.setDices(self.dices);
    self.Interface.setPoints(self.points);
    self.Interface.setPlayer(self.player);
    self.Interface.setCpu(self.cpu);

    self.Interface.disableTakePoints(true);

    // check score
    var checkScore = self.playing && self.cpuStarts || !self.playing && !self.cpuStarts;

    if (checkScore && self.player.score >= 10000 && self.player.score > self.cpu.score) {
        self.Interface.showMessage("Player wins!")
    } else if (checkScore && self.cpu.score >= 10000 && self.cpu.score > self.player.score) {
        self.Interface.showMessage("CPU wins!")
    } else if (self.player.score >= 10000 && self.player.score == self.cpu.score) {
        self.Interface.showMessage("Remi!")
    } else {
        self.playing = !self.playing;
        self.Interface.setPlaying(self.playing);
        // continue
        if (self.playing) {
            self.Interface.disableRollDices(false);
        }

        if (!self.playing) {
            setTimeout(function() {
                self.rollDices();
            }, self.cpuspeed);
        }
    }

}

Game.prototype.cpuPlay = function() {
    var self = this;

    // first select all available dices
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (!dice.disabled) {
            self.toggleDice(i);
        }
    }

    // check if dice gains points
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        var tmpPoints = self.calculatePoints();
        if (!dice.disabled) {
            self.toggleDice(i);
            if (self.calculatePoints() < tmpPoints) {
                self.toggleDice(i);
            }
        }
    }

    // count free dices
    var freeDices = 0;
    for (var i = 0; i < 6; i++) {
        var dice = self.dices[i];
        if (!dice.disabled && !dice.selected) {
            freeDices++;
        }
    }

    setTimeout(function() {
        // strategy: end round if points >= 300 and less than 4 dices left
        if (self.points + self.calculatePoints() >= 300 && freeDices < 4 && freeDices > 0) {
            self.takePoints();
        } else {
            self.addPoints();
            self.rollDices();
        }
    }, self.cpuSpeed);

}

var game = new Game(Interface);
<|endoftext|>


<commit_before>(function($){
   $.fn.dateRange = function(options)
   {
      var defaults = {selected: null};
      var opts = $.extend({}, defaults, options);
      var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
      var abbreviations = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
      var daySelector = 'td:not(.m):not(:empty)'
      return this.each(function()
      {
         if (this.dateRange) { return false; }

         var $input = $(this);
         var $container, selecting, selected;
         var self =
         {
            initialize: function()
            {
               $container = self.initializeContainer().hide();
               $container.find('div.prev').click(self.loadPrevious);
               $container.find('div.next').click(self.loadNext);
               var now = new Date();
               now.setDate(1);
               var prev = new Date(now.getFullYear(), now.getMonth()-1, 1)
               $container.append(self.buildMonth(prev));
               $container.append(self.buildMonth(now));

               $input.click(function()
               {
                  self.show();
                  return false;
               });
               $(document).keydown(function(e)
               {
                  if (e.keyCode == 27) { self.hide(); }
               }).click(self.hide);

               $container.delegate(daySelector, 'click', self.clicked);
               $container.click(function(){return false;});
            },
            show: function()
            {
               selecting = new Array();
               $container.show();
            },
            hide: function()
            {
               $container.hide();
            },
            clicked: function()
            {
               var $td = $(this).addClass('selected');
               var date = $td.closest('table').data('date');
               selecting.push(new Date(date.getFullYear(), date.getMonth(), $td.text()));
               if (selecting.length == 2)
               {
                  selected = selecting;
                  if (selected[0] > selected[1])
                  {
                     var x = selected[0];
                     selected[0] = selected[1];
                     selected[1] = x;
                  }
                  $input.val(self.format(selected[0]) + ' - ' + self.format(selected[1]));
                  self.highlight($container.find('table:first'));
                  self.highlight($container.find('table:last'));
                  self.hide();
                  if (opts.selected != null) { opts.selected(selected); }
               }
            },
            highlight: function($table)
            {
               if (selected == null || selected.length != 2) { return; }

               $table.find('td.highlight').removeClass('highlight');
               var startDate = $table.data('date');
               var endDate = new Date(startDate.getFullYear(), startDate.getMonth()+1, 0);
               if (startDate > selected[1] || endDate < selected[0]) { return; }

               var $tds = $table.find(daySelector);
               var start = selected[0].getMonth() < startDate.getMonth() || selected[0].getFullYear() < startDate.getFullYear() ? 0 : selected[0].getDate()-1;
               var end = selected[1].getMonth() > endDate.getMonth() || selected[1].getFullYear() > endDate.getFullYear() ? $tds.length : selected[1].getDate();
               for(var i = start; i < end; ++i)
               {
                  $tds.get(i).className = 'highlight';
               }
            },
            loadPrevious: function()
            {
               $container.children('table:eq(1)').remove();
               var date = $container.children('table:eq(0)').data('date');
               $container.find('div.nav').after(self.buildMonth(new Date(date.getFullYear(), date.getMonth()-1, 1)));
            },
            loadNext: function()
            {
               $container.children('table:eq(0)').remove();
               var date = $container.children('table:eq(0)').data('date');
               $container.find('table').after(self.buildMonth(new Date(date.getFullYear(), date.getMonth()+1, 1)));
            },
            initializeContainer: function()
            {
               $input.wrap($('
').addClass('calendarWrap'));
               var $container = $('
').addClass('calendar').insertAfter($input);
               var $nav = $('
').addClass('nav').appendTo($container);
               $nav.html('
‹

›
');
               return $container;
            },
            buildMonth: function(date)
            {
               var first = new Date(date.getFullYear(), date.getMonth(), 1);
               var last = new Date(date.getFullYear(), date.getMonth()+1, 0);
               var firstDay = first.getDay();
               var totalDays = last.getDate();
               var weeks = Math.ceil((totalDays + firstDay) / 7);

               var table = document.createElement('table');

               for (var i = 0, count = 1; i < weeks; ++i)
               {
                  var row = table.insertRow(-1)
                  for(var j = 0; j < 7; ++j, ++count)
                  {
                     var cell = row.insertCell(-1);
                     if (count > firstDay && count <= totalDays+firstDay)
                     {
                        cell.innerHTML = count - firstDay;
                     }
                  }
               }

               var header = table.insertRow(0);
               var cell = header.insertCell(-1);
               cell.innerHTML = months[date.getMonth()] + ' ' + date.getFullYear();
               cell.className = 'm'; //very stupid IE (all versions) fix
               cell.colSpan = 7;

               var $table = $(table).data('date', date);
               self.highlight($table);
               return $table;
            },
            format: function(date)
            {
               return abbreviations[date.getMonth()] + ' ' + date.getDate() + ' ' + date.getFullYear();
            }
         };
         this.dateRange = self;
         self.initialize();
      });
   }
})(jQuery);<commit_msg>added missing ;<commit_after>(function($){
   $.fn.dateRange = function(options)
   {
      var defaults = {selected: null};
      var opts = $.extend({}, defaults, options);
      var months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
      var abbreviations = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
      var daySelector = 'td:not(.m):not(:empty)';
      return this.each(function()
      {
         if (this.dateRange) { return false; }

         var $input = $(this);
         var $container, selecting, selected;
         var self =
         {
            initialize: function()
            {
               $container = self.initializeContainer().hide();
               $container.find('div.prev').click(self.loadPrevious);
               $container.find('div.next').click(self.loadNext);
               var now = new Date();
               now.setDate(1);
               var prev = new Date(now.getFullYear(), now.getMonth()-1, 1);
               $container.append(self.buildMonth(prev));
               $container.append(self.buildMonth(now));

               $input.click(function()
               {
                  self.show();
                  return false;
               });
               $(document).keydown(function(e)
               {
                  if (e.keyCode == 27) { self.hide(); }
               }).click(self.hide);

               $container.delegate(daySelector, 'click', self.clicked);
               $container.click(function(){return false;});
            },
            show: function()
            {
               selecting = new Array();
               $container.show();
            },
            hide: function()
            {
               $container.hide();
            },
            clicked: function()
            {
               var $td = $(this).addClass('selected');
               var date = $td.closest('table').data('date');
               selecting.push(new Date(date.getFullYear(), date.getMonth(), $td.text()));
               if (selecting.length == 2)
               {
                  selected = selecting;
                  if (selected[0] > selected[1])
                  {
                     var x = selected[0];
                     selected[0] = selected[1];
                     selected[1] = x;
                  }
                  $input.val(self.format(selected[0]) + ' - ' + self.format(selected[1]));
                  self.highlight($container.find('table:first'));
                  self.highlight($container.find('table:last'));
                  self.hide();
                  if (opts.selected != null) { opts.selected(selected); }
               }
            },
            highlight: function($table)
            {
               if (selected == null || selected.length != 2) { return; }

               $table.find('td.highlight').removeClass('highlight');
               var startDate = $table.data('date');
               var endDate = new Date(startDate.getFullYear(), startDate.getMonth()+1, 0);
               if (startDate > selected[1] || endDate < selected[0]) { return; }

               var $tds = $table.find(daySelector);
               var start = selected[0].getMonth() < startDate.getMonth() || selected[0].getFullYear() < startDate.getFullYear() ? 0 : selected[0].getDate()-1;
               var end = selected[1].getMonth() > endDate.getMonth() || selected[1].getFullYear() > endDate.getFullYear() ? $tds.length : selected[1].getDate();
               for(var i = start; i < end; ++i)
               {
                  $tds.get(i).className = 'highlight';
               }
            },
            loadPrevious: function()
            {
               $container.children('table:eq(1)').remove();
               var date = $container.children('table:eq(0)').data('date');
               $container.find('div.nav').after(self.buildMonth(new Date(date.getFullYear(), date.getMonth()-1, 1)));
            },
            loadNext: function()
            {
               $container.children('table:eq(0)').remove();
               var date = $container.children('table:eq(0)').data('date');
               $container.find('table').after(self.buildMonth(new Date(date.getFullYear(), date.getMonth()+1, 1)));
            },
            initializeContainer: function()
            {
               $input.wrap($('
').addClass('calendarWrap'));
               var $container = $('
').addClass('calendar').insertAfter($input);
               var $nav = $('
').addClass('nav').appendTo($container);
               $nav.html('
‹

›
');
               return $container;
            },
            buildMonth: function(date)
            {
               var first = new Date(date.getFullYear(), date.getMonth(), 1);
               var last = new Date(date.getFullYear(), date.getMonth()+1, 0);
               var firstDay = first.getDay();
               var totalDays = last.getDate();
               var weeks = Math.ceil((totalDays + firstDay) / 7);

               var table = document.createElement('table');

               for (var i = 0, count = 1; i < weeks; ++i)
               {
                  var row = table.insertRow(-1);
                  for(var j = 0; j < 7; ++j, ++count)
                  {
                     var cell = row.insertCell(-1);
                     if (count > firstDay && count <= totalDays+firstDay)
                     {
                        cell.innerHTML = count - firstDay;
                     }
                  }
               }

               var header = table.insertRow(0);
               var cell = header.insertCell(-1);
               cell.innerHTML = months[date.getMonth()] + ' ' + date.getFullYear();
               cell.className = 'm'; //very stupid IE (all versions) fix
               cell.colSpan = 7;

               var $table = $(table).data('date', date);
               self.highlight($table);
               return $table;
            },
            format: function(date)
            {
               return abbreviations[date.getMonth()] + ' ' + date.getDate() + ' ' + date.getFullYear();
            }
         };
         this.dateRange = self;
         self.initialize();
      });
   }
})(jQuery);<|endoftext|>


<commit_before>var container;
var camera, controls, scene, renderer;
var pickingData = [], pickingTexture, pickingScene;
var objects = [];
var highlightBox;

var mouse = new THREE.Vector2();
var offset = new THREE.Vector3( 10, 10, 10 );

var skyBox;
var drawnSphere;
var raycaster;

function RunGame(){
	init();
	animate();
}

function init() {

	container = document.getElementById( "container" );

	// Camera
	camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000);
	camera.position.z = 1000;

	// Renderer
	renderer = new THREE.WebGLRenderer( { antialias: true, alpha: false } );
	renderer.setClearColor( 0xffffff, 1 );
	renderer.setSize( window.innerWidth, window.innerHeight );
	renderer.sortObjects = false;
	container.appendChild( renderer.domElement );

	// Trackball controls
	renderer.domElement.addEventListener( 'mousemove', onMouseMove );
	controls = new THREE.TrackballControls( camera , renderer.domElement );
	controls.rotateSpeed = 1.0;
	controls.zoomSpeed = 1.2;
	controls.panSpeed = 0.8;
	controls.noZoom = false;
	controls.noPan = false;
	controls.staticMoving = true;
	controls.dynamicDampingFactor = 0.3;

	// Scene
	scene = new THREE.Scene();

	// Lights
	scene.add( new THREE.AmbientLight( 0x555555 ) );
	var light = new THREE.SpotLight( 0xffffff, 1.5 );
	light.position.set( 0, 500, 2000 );
	scene.add( light );

	// Skybox
	var imagePrefix = "img/";
	var imageSuffix = '.jpg';
	var directions = ['px', 'nx', 'py', 'ny', 'pz', 'nz'];
	var skyGeometry = new THREE.CubeGeometry( 10000, 10000, 10000 );
	var materialArray = [];
	for (var i = 0; i < 6; i++)
		materialArray.push( new THREE.MeshBasicMaterial({
			map: THREE.ImageUtils.loadTexture( imagePrefix + directions[i] + imageSuffix ),
			side: THREE.BackSide
		}));
	var skyMaterial = new THREE.MeshFaceMaterial( materialArray );
	skyBox = new THREE.Mesh( skyGeometry, skyMaterial );
	scene.add( skyBox );

	// Icosahedron sphere
	var icosGeo = new THREE.IcosahedronGeometry( 200, 2 );
	var waterTexture = THREE.ImageUtils.loadTexture('img/water.jpg');
	waterTexture.wrapS = waterTexture.wrapT = THREE.RepeatWrapping;
	waterTexture.repeat.set(1,1);
	var icosMat = new THREE.MeshPhongMaterial({map: waterTexture /*,color: 0xffffff*/, vertexColors: THREE.FaceColors}); //Unique colors for each face... i guess?
	for ( var i = 0; i < icosGeo.faces.length; i++ ){
		face  = icosGeo.faces[ i ];
		face.color.setRGB( 0.0, 0.66, 0.91);
	}
	drawnSphere = new THREE.Mesh( icosGeo, icosMat);
	scene.add( drawnSphere);

	projector = new THREE.Projector();
	raycaster = new THREE.Raycaster();
}

function onMouseMove( e ) {
	e.preventDefault();
	mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
	mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
}

function animate() {
	requestAnimationFrame( animate );
	render();
}

// Really dirty to use 3 global vars for the mouseover highlight but cba to think better way atm
var faceUnderMouse = undefined;
var previousColor = undefined;
var previousIntersect = undefined;

function render() {

	// Trackball controls
	controls.update();

	// Raycast from camera to under mouse
	var vector = new THREE.Vector3(mouse.x, mouse.y, 1 );
	projector.unprojectVector(vector, camera);
	raycaster.set(camera.position, vector.sub(camera.position).normalize());
	var intersects = raycaster.intersectObjects([drawnSphere], true);

	// Set face color under cursor
	if(intersects.length > 0){
		if(intersects[0].face !== faceUnderMouse){
			if(faceUnderMouse !== undefined){
				faceUnderMouse.color = previousColor;
			}

			previousIntersect = intersects[0];
			faceUnderMouse = intersects[0].face;
			previousColor = new THREE.Color(faceUnderMouse.color);
			faceUnderMouse.color.setRGB(1,0,0);
			intersects[0].object.geometry.colorsNeedUpdate = true;
		}
	}
	else{
		if(faceUnderMouse !== undefined){
			// Remove face color if cursor moved out of the sphere
			faceUnderMouse.color = previousColor;
			previousIntersect.object.geometry.colorsNeedUpdate = true;
		}
		previousIntersect = undefined;
		previousColor = undefined;
		faceUnderMouse = undefined;
	}

	// Hacky way of preventing camera moving relative to skybox
	skyBox.position.copy( camera.position );

	renderer.render( scene, camera );

}<commit_msg>Revert "Tested texture wrapping"<commit_after>var container;
var camera, controls, scene, renderer;
var pickingData = [], pickingTexture, pickingScene;
var objects = [];
var highlightBox;

var mouse = new THREE.Vector2();
var offset = new THREE.Vector3( 10, 10, 10 );

var skyBox;
var drawnSphere;
var raycaster;

function RunGame(){
	init();
	animate();
}

function init() {

	container = document.getElementById( "container" );

	// Camera
	camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000);
	camera.position.z = 1000;

	// Renderer
	renderer = new THREE.WebGLRenderer( { antialias: true, alpha: false } );
	renderer.setClearColor( 0xffffff, 1 );
	renderer.setSize( window.innerWidth, window.innerHeight );
	renderer.sortObjects = false;
	container.appendChild( renderer.domElement );

	// Trackball controls
	renderer.domElement.addEventListener( 'mousemove', onMouseMove );
	controls = new THREE.TrackballControls( camera , renderer.domElement );
	controls.rotateSpeed = 1.0;
	controls.zoomSpeed = 1.2;
	controls.panSpeed = 0.8;
	controls.noZoom = false;
	controls.noPan = false;
	controls.staticMoving = true;
	controls.dynamicDampingFactor = 0.3;

	// Scene
	scene = new THREE.Scene();

	// Lights
	scene.add( new THREE.AmbientLight( 0x555555 ) );
	var light = new THREE.SpotLight( 0xffffff, 1.5 );
	light.position.set( 0, 500, 2000 );
	scene.add( light );

	// Skybox
	var imagePrefix = "img/";
	var imageSuffix = '.jpg';
	var directions = ['px', 'nx', 'py', 'ny', 'pz', 'nz'];
	var skyGeometry = new THREE.CubeGeometry( 10000, 10000, 10000 );
	var materialArray = [];
	for (var i = 0; i < 6; i++)
		materialArray.push( new THREE.MeshBasicMaterial({
			map: THREE.ImageUtils.loadTexture( imagePrefix + directions[i] + imageSuffix ),
			side: THREE.BackSide
		}));
	var skyMaterial = new THREE.MeshFaceMaterial( materialArray );
	skyBox = new THREE.Mesh( skyGeometry, skyMaterial );
	scene.add( skyBox );

	// Icosahedron sphere
	var icosGeo = new THREE.IcosahedronGeometry( 200, 2 );
	var icosMat = new THREE.MeshPhongMaterial({map: THREE.ImageUtils.loadTexture('img/water.jpg') /*,color: 0xffffff*/, vertexColors: THREE.FaceColors}); //Unique colors for each face... i guess?
	for ( var i = 0; i < icosGeo.faces.length; i++ ){
		face  = icosGeo.faces[ i ];
		face.color.setRGB( 0.0, 0.66, 0.91);
	}
	drawnSphere = new THREE.Mesh( icosGeo, icosMat);
	scene.add( drawnSphere);

	projector = new THREE.Projector();
	raycaster = new THREE.Raycaster();
}

function onMouseMove( e ) {
	e.preventDefault();
	mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
	mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
}

function animate() {
	requestAnimationFrame( animate );
	render();
}

// Really dirty to use 3 global vars for the mouseover highlight but cba to think better way atm
var faceUnderMouse = undefined;
var previousColor = undefined;
var previousIntersect = undefined;

function render() {

	// Trackball controls
	controls.update();

	// Raycast from camera to under mouse
	var vector = new THREE.Vector3(mouse.x, mouse.y, 1 );
	projector.unprojectVector(vector, camera);
	raycaster.set(camera.position, vector.sub(camera.position).normalize());
	var intersects = raycaster.intersectObjects([drawnSphere], true);

	// Set face color under cursor
	if(intersects.length > 0){
		if(intersects[0].face !== faceUnderMouse){
			if(faceUnderMouse !== undefined){
				faceUnderMouse.color = previousColor;
			}

			previousIntersect = intersects[0];
			faceUnderMouse = intersects[0].face;
			previousColor = new THREE.Color(faceUnderMouse.color);
			faceUnderMouse.color.setRGB(1,0,0);
			intersects[0].object.geometry.colorsNeedUpdate = true;
		}
	}
	else{
		if(faceUnderMouse !== undefined){
			// Remove face color if cursor moved out of the sphere
			faceUnderMouse.color = previousColor;
			previousIntersect.object.geometry.colorsNeedUpdate = true;
		}
		previousIntersect = undefined;
		previousColor = undefined;
		faceUnderMouse = undefined;
	}

	// Hacky way of preventing camera moving relative to skybox
	skyBox.position.copy( camera.position );

	renderer.render( scene, camera );

}<|endoftext|>


<commit_before>//
var canvas = document.createElement("canvas");
var container = document.getElementById("container");
var ctx = canvas.getContext("2d");
var direct = Math.random()*(2*Math.PI);
var time = 60;
canvas.width = 512;
canvas.height = 480;
container.appendChild(canvas);

// ͼʵ
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
	bgReady = true;
};
bgImage.src = "images/background.png";

// Ӣ
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
	heroReady = true;
};
heroImage.src = "images/hero.png";

// 粼
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
	monsterReady = true;
};
monsterImage.src = "images/monster.png";

// Ϸʵ
var hero = {
	speed: 256 // movement in pixels per second
};
var monster = {
	speed:128
};
var monstersCaught = 0;

// ¼
var keysDown = {};

addEventListener("keydown", function (e) {
	keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
	delete keysDown[e.keyCode];
}, false);

// 粼ֱץø粼
var reset = function () {
	hero.x = canvas.width / 2;
	hero.y = canvas.height / 2;

	direct = Math.random()*(2*Math.PI);
	// ʾ粼
	monster.x = 32 + (Math.random() * (canvas.width - 64));
	monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// ʵʱ
var update = function (modifier) {
	if (38 in keysDown) { // Player holding up
		hero.y -= hero.speed * modifier;
	}
	if (40 in keysDown) { // Player holding down
		hero.y += hero.speed * modifier;
	}
	if (37 in keysDown) { // Player holding left
		hero.x -= hero.speed * modifier;
	}
	if (39 in keysDown) { // Player holding right
		hero.x += hero.speed * modifier;
	}
	//Ӣ۱߽紦
	if(hero.y<0){
		hero.y=canvas.height;
	}
	if(hero.y>canvas.height){
		hero.y=0;
	}
	if(hero.x<0){
		hero.x=canvas.width;
	}
	if(hero.x>canvas.width){
		hero.x=0;
	}
	//粼ײ߽紦
	if(monster.y<=0){
		direct=(Math.PI)*Math.random();
	}
	if(monster.y>=canvas.height){
		direct=Math.PI+(Math.PI)*Math.random();
	}
	if(monster.x<=0){
		direct=3*Math.PI/2+(Math.PI)*Math.random();
	}
	if(monster.x>=canvas.width){
		direct=Math.PI/2+(Math.PI)*Math.random();
	}
	//粼ƶ
	monster.x += Math.cos(direct)*monster.speed*modifier;
	monster.y += Math.sin(direct)*monster.speed*modifier;
	// жǷץס粼
	if (
		hero.x <= (monster.x + 32)
		&& monster.x <= (hero.x + 32)
		&& hero.y <= (monster.y + 32)
		&& monster.y <= (hero.y + 32)
	) {
		++monstersCaught;
		monster.speed+=2;
		++time;
		reset();
	}
};

//
var render = function () {
	if (bgReady) {
		ctx.drawImage(bgImage, 0, 0);
	}

	if (heroReady) {
		ctx.drawImage(heroImage, hero.x, hero.y);
	}

	if (monsterReady) {
		ctx.drawImage(monsterImage, monster.x, monster.y);
	}

	// ÷뵹ʱ
	ctx.fillStyle = "rgb(250, 250, 250)";
	ctx.font = "24px Helvetica";
	ctx.textAlign = "left";
	ctx.textBaseline = "top";
	ctx.fillText("Goblins caught: " + monstersCaught, 32, 32);
	ctx.fillText("Time: " + parseInt(time), 32, 64);
};

// ѭ
var main = function () {
	var now = Date.now();
	var delta = now - then;

	update(delta / 1000);
	render();

	then = now;
	time -= delta/1000;
	if(time>=0){
		// ֡
		requestAnimationFrame(main);
	}else{
		ctx.fillText("Game Over", 192,canvas.height/2);
	}
};

var replay = function(){
	time = 60;
	monstersCaught = 0;
	reset();
	main();
}
// ֧ requestAnimationFrame
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Let's play this game!
var then = Date.now();
reset();
main();
<commit_msg>全局闭包添加<commit_after>(function(){
	//
	var canvas = document.createElement("canvas");
	var container = document.getElementById("container");
	var ctx = canvas.getContext("2d");
	var direct = Math.random()*(2*Math.PI);
	var time = 60;
	canvas.width = 512;
	canvas.height = 480;
	container.appendChild(canvas);

// ͼʵ
	var bgReady = false;
	var bgImage = new Image();
	bgImage.onload = function () {
		bgReady = true;
	};
	bgImage.src = "images/background.png";

// Ӣ
	var heroReady = false;
	var heroImage = new Image();
	heroImage.onload = function () {
		heroReady = true;
	};
	heroImage.src = "images/hero.png";

// 粼
	var monsterReady = false;
	var monsterImage = new Image();
	monsterImage.onload = function () {
		monsterReady = true;
	};
	monsterImage.src = "images/monster.png";

// Ϸʵ
	var hero = {
		speed: 256 // movement in pixels per second
	};
	var monster = {
		speed:128
	};
	var monstersCaught = 0;

// ¼
	var keysDown = {};

	addEventListener("keydown", function (e) {
		keysDown[e.keyCode] = true;
	}, false);

	addEventListener("keyup", function (e) {
		delete keysDown[e.keyCode];
	}, false);

// 粼ֱץø粼
	var reset = function () {
		hero.x = canvas.width / 2;
		hero.y = canvas.height / 2;

		direct = Math.random()*(2*Math.PI);
		// ʾ粼
		monster.x = 32 + (Math.random() * (canvas.width - 64));
		monster.y = 32 + (Math.random() * (canvas.height - 64));
	};

// ʵʱ
	var update = function (modifier) {
		if (38 in keysDown) { // Player holding up
			hero.y -= hero.speed * modifier;
		}
		if (40 in keysDown) { // Player holding down
			hero.y += hero.speed * modifier;
		}
		if (37 in keysDown) { // Player holding left
			hero.x -= hero.speed * modifier;
		}
		if (39 in keysDown) { // Player holding right
			hero.x += hero.speed * modifier;
		}
		//Ӣ۱߽紦
		if(hero.y<0){
			hero.y=canvas.height;
		}
		if(hero.y>canvas.height){
			hero.y=0;
		}
		if(hero.x<0){
			hero.x=canvas.width;
		}
		if(hero.x>canvas.width){
			hero.x=0;
		}
		//粼ײ߽紦
		if(monster.y<=0){
			direct=(Math.PI)*Math.random();
		}
		if(monster.y>=canvas.height){
			direct=Math.PI+(Math.PI)*Math.random();
		}
		if(monster.x<=0){
			direct=3*Math.PI/2+(Math.PI)*Math.random();
		}
		if(monster.x>=canvas.width){
			direct=Math.PI/2+(Math.PI)*Math.random();
		}
		//粼ƶ
		monster.x += Math.cos(direct)*monster.speed*modifier;
		monster.y += Math.sin(direct)*monster.speed*modifier;
		// жǷץס粼
		if (
			hero.x <= (monster.x + 32)
			&& monster.x <= (hero.x + 32)
			&& hero.y <= (monster.y + 32)
			&& monster.y <= (hero.y + 32)
		) {
			++monstersCaught;
			monster.speed+=2;
			++time;
			reset();
		}
	};

//
	var render = function () {
		if (bgReady) {
			ctx.drawImage(bgImage, 0, 0);
		}

		if (heroReady) {
			ctx.drawImage(heroImage, hero.x, hero.y);
		}

		if (monsterReady) {
			ctx.drawImage(monsterImage, monster.x, monster.y);
		}

		// ÷뵹ʱ
		ctx.fillStyle = "rgb(250, 250, 250)";
		ctx.font = "24px Helvetica";
		ctx.textAlign = "left";
		ctx.textBaseline = "top";
		ctx.fillText("Goblins caught: " + monstersCaught, 32, 32);
		ctx.fillText("Time: " + parseInt(time), 32, 64);
	};

// ѭ
	var main = function () {
		var now = Date.now();
		var delta = now - then;

		update(delta / 1000);
		render();

		then = now;
		time -= delta/1000;
		if(time>=0){
			// ֡
			requestAnimationFrame(main);
		}else{
			ctx.fillText("Game Over", 192,canvas.height/2);
		}
	};

	var replay = function(){
		time = 60;
		monstersCaught = 0;
		reset();
		main();
	}
// ֧ requestAnimationFrame
	var w = window;
	requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Let's play this game!
	var then = Date.now();
	reset();
	main();
})();

<|endoftext|>


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

/**
 * Represents a data series that has a color and associated data points which may change.  The change is signified with
 * an Emitter.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( require => {
  'use strict';

  // modules
  const Emitter = require( 'AXON/Emitter' );
  const griddle = require( 'GRIDDLE/griddle' );
  const merge = require( 'PHET_CORE/merge' );
  const Vector2 = require( 'DOT/Vector2' );

  class DynamicSeries {

    /**
     * @param {Object} [options]
     */
    constructor( options ) {

      // @private {Vector2[]} - the data points in the series.  A NaN "y" value indicates there is no sample at that
      // point in time
      this.data = [];

      // @private {Emitter} -  sends notification when the data series changes
      this.emitter = new Emitter();

      options = merge( {
        color: 'black',
        lineWidth: 1,
        radius: 2 // TODO: https://github.com/phetsims/griddle/issues/46 eliminate?
      }, options );

      // @public (read-only) {Color}
      this.color = options.color;

      // @public (read-only) {number}
      this.lineWidth = options.lineWidth;

      this.radius = options.radius; // TODO: https://github.com/phetsims/griddle/issues/46 eliminate or document
    }

    /**
     * Removes the first data point
     * @public
     */
    shiftData() {
      this.data.shift();
      this.emitter.emit();
    }

    /**
     * Returns the number of points in the data series.
     * @returns {number}
     * @public
     */
    getLength() {
      return this.data.length;
    }

    /**
     * Adds a listener when the data series changes.
     * @param {function} listener
     * @public
     */
    addDynamicSeriesListener( listener ) {
      this.emitter.addListener( listener );
    }

    /**
     * Removes a listener when the data series changes.
     * @param {function} listener
     * @public
     */
    removeDynamicSeriesListener( listener ) {
      this.emitter.removeListener( listener );
    }

    /**
     * Remove all data from the DynamicSeries
     * @public
     */
    clear() {
      this.data.length = 0;
      this.emitter.emit();
    }

    /**
     * Adds an (x,y) point
     * @param {number} x
     * @param {number} y
     * @public
     */
    addXYDataPoint( x, y ) {
      this.addDataPoint( new Vector2( x, y ) );
    }

    /**
     * Adds a Vector2 data point
     * @param {Vector2} dataPoint
     * @public
     */
    addDataPoint( dataPoint ) {
      this.data.push( dataPoint );
      this.emitter.emit();
    }

    /**
     * Returns the data point at the specified index.
     * @param {number} index
     * @returns {Vector2}
     */
    getDataPoint( index ) {
      return this.data[ index ];
    }

    /**
     * Returns true if there are any data points.
     * @returns {boolean}
     */
    hasData() {
      return this.data.length > 0;
    }

    /**
     * Remove a point in the data series with the provided x value. Does not remove duplicates, only the first
     * occurrence of the value starting at the beginning of the xPoints list.
     * @param {number} x
     * @public
     */
    removePointAtX( x ) {
      for ( let i = 0; i < this.data.length; i++ ) {
        const point = this.data[ i ];
        if ( point.x === x ) {
          this.data.splice( i, 1 );
          this.emitter.emit();
          break;
        }
      }
    }
  }

  return griddle.register( 'DynamicSeries', DynamicSeries );
} );<commit_msg>Update TODOs, see https://github.com/phetsims/griddle/issues/46<commit_after>// Copyright 2018-2019, University of Colorado Boulder

/**
 * Represents a data series that has a color and associated data points which may change.  The change is signified with
 * an Emitter.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( require => {
  'use strict';

  // modules
  const Emitter = require( 'AXON/Emitter' );
  const griddle = require( 'GRIDDLE/griddle' );
  const merge = require( 'PHET_CORE/merge' );
  const Vector2 = require( 'DOT/Vector2' );

  class DynamicSeries {

    /**
     * @param {Object} [options]
     */
    constructor( options ) {

      // @private {Vector2[]} - the data points in the series.  A NaN "y" value indicates there is no sample at that
      // point in time
      this.data = [];

      // @private {Emitter} -  sends notification when the data series changes
      this.emitter = new Emitter();

      options = merge( {
        color: 'black',
        lineWidth: 1,
        radius: 2
      }, options );

      // @public (read-only) {Color}
      this.color = options.color;

      // @public (read-only) {number}
      this.lineWidth = options.lineWidth;

      // @public (read-only) {number}
      this.radius = options.radius;
    }

    /**
     * Removes the first data point
     * @public
     */
    shiftData() {
      this.data.shift();
      this.emitter.emit();
    }

    /**
     * Returns the number of points in the data series.
     * @returns {number}
     * @public
     */
    getLength() {
      return this.data.length;
    }

    /**
     * Adds a listener when the data series changes.
     * @param {function} listener
     * @public
     */
    addDynamicSeriesListener( listener ) {
      this.emitter.addListener( listener );
    }

    /**
     * Removes a listener when the data series changes.
     * @param {function} listener
     * @public
     */
    removeDynamicSeriesListener( listener ) {
      this.emitter.removeListener( listener );
    }

    /**
     * Remove all data from the DynamicSeries
     * @public
     */
    clear() {
      this.data.length = 0;
      this.emitter.emit();
    }

    /**
     * Adds an (x,y) point
     * @param {number} x
     * @param {number} y
     * @public
     */
    addXYDataPoint( x, y ) {
      this.addDataPoint( new Vector2( x, y ) );
    }

    /**
     * Adds a Vector2 data point
     * @param {Vector2} dataPoint
     * @public
     */
    addDataPoint( dataPoint ) {
      this.data.push( dataPoint );
      this.emitter.emit();
    }

    /**
     * Returns the data point at the specified index.
     * @param {number} index
     * @returns {Vector2}
     */
    getDataPoint( index ) {
      return this.data[ index ];
    }

    /**
     * Returns true if there are any data points.
     * @returns {boolean}
     */
    hasData() {
      return this.data.length > 0;
    }

    /**
     * Remove a point in the data series with the provided x value. Does not remove duplicates, only the first
     * occurrence of the value starting at the beginning of the xPoints list.
     * @param {number} x
     * @public
     */
    removePointAtX( x ) {
      for ( let i = 0; i < this.data.length; i++ ) {
        const point = this.data[ i ];
        if ( point.x === x ) {
          this.data.splice( i, 1 );
          this.emitter.emit();
          break;
        }
      }
    }
  }

  return griddle.register( 'DynamicSeries', DynamicSeries );
} );<|endoftext|>


<commit_before>/*
    String Format function from http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#4673436
*/
String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != 'undefined'
            ? args[number]
            : match
        ;
    });
};

/*
    Alerts the user of the server's response after an API call
    Parameter       Description
    response        JSON response returned from server
    successMessage  Message to show if response was a "success"
*/
function parseResponse(response, successMessage) {
    parsed = JSON.parse(response);
    if (parsed.success = "TRUE") {
        showMessage("success", successMessage);

    } else {
        showMessage("error", parsed.error_message);
    }
}

/*
    Displays a message to the user using slide down animation
*/
function showMessage(type, message) {
    var div = $("<div>");
    div.addClass(type);
    div.text(message);
    div.hide();
    $("body").append(div);
    div.slideDown(500);

    setTimeout(function() {
        div.slideUp(500, function() {
            div.remove();
        });
    }, 3000);
}<commit_msg>changed = to == in if statement.<commit_after>/*
    String Format function from http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4673436#4673436
*/
String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) {
        return typeof args[number] != 'undefined'
            ? args[number]
            : match
        ;
    });
};

/*
    Alerts the user of the server's response after an API call
    Parameter       Description
    response        JSON response returned from server
    successMessage  Message to show if response was a "success"
*/
function parseResponse(response, successMessage) {
    parsed = JSON.parse(response);
    if (parsed.success == "TRUE") {
        showMessage("success", successMessage);

    } else {
        showMessage("error", parsed.error_message);
    }
}

/*
    Displays a message to the user using slide down animation
*/
function showMessage(type, message) {
    var div = $("<div>");
    div.addClass(type);
    div.text(message);
    div.hide();
    $("body").append(div);
    div.slideDown(500);

    setTimeout(function() {
        div.slideUp(500, function() {
            div.remove();
        });
    }, 3000);
}<|endoftext|>


<commit_before>var MJS = {};

MJS.fakeGuid = function () {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }

    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};

function _emptyStringIfNull(obj) {
    try {
        return obj ? obj : "";
    } catch (ex) {

    }

    return "";
}

MJS.infoToGridHtml = function (info, options) {
    opt = {
        labelSize: 4,
        labelBold: true,
        labelClasses: "",
        rowClasses: "half-margin"
    }

    if (options) {
        if (options.labelSize && options.labelSize <= 11)
            opt.labelSize = options.labelSize;
        if (options.labelBold != undefined && typeof options.labelBold == "boolean")
            opt.labelBold = options.labelBold;
        if (options.labelClasses != undefined && typeof options.labelClasses == "string")
            opt.labelClasses = options.labelClasses;
    }

    var text = "";

    var labelTag = "b";
    var infoTag = "span";

    if (!opt.labelBold) {
        labelTag = "span";
    }

    $.each(info, function (i, o) {
        //if(i > 0) text += "
";

        text += "
";
        text += "
<" + labelTag + " class='" + opt.labelClasses + "'>" + o.label + "</" + labelTag + ">
";
        text += "
<" + infoTag + "'>" + o.info + "</" + infoTag + ">
";
        text += "
";
    });

    text += "
";

    return text;
};

MJS.buttonHtml = function (info) {
    if (!info)
        info = {};
    if (typeof info != "object") {
        toast("Error: MaterializeJS.buttonHtml - info must be an object!", 2500);
        return;
    }
    var res = "" + (info.icon_classes == null ? "" : "") + _emptyStringIfNull(info.text) + "";
    return res;
};

MJS.imageCardHtml = function (info) {
    var res = "
\n" + "
\n" + (info.image ? "
\n" : "") + "
\n" + "
\n" + "        " + info.title + "\n" + "
" + info.text + "
\n" + "
\n" +
	//"
\n" +
	//"        This is a link\n" +
	//"        This is a link\n" +
	//"
\n" +
	"
";
    return res;
};

MJS.plainPanelCardHtml = function (info) {
    var res = "
" + "" + _emptyStringIfNull(info.text) + " " + "
" + "
";
    return res;
};

MJS.revealCardHtml = function (id, title, image, info) {
    var res = "
" + "
" + (image ? "" : "") + "
" + "
" + "" + title + "" + "" +
	//"
This is a link
" +
	"
" + "
" + "" + title + "" + "
" + info + "
" + "
" + "
";
    return res;
};

MJS.makeCardDraggable = function (element) {

    var mc = new Hammer.Manager(element);

    mc.add(new Hammer.Pan({
        threshold: 0,
        pointers: 0
    }));
    mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));

    mc.on("panstart panmove", MaterializeJS.onCardDrag);
    mc.on("panend", MaterializeJS.onCardDragEnd);
};

MJS.makeCardsDraggable = function (selector) {

    $.each($(selector), function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

// listen to events...
MJS.onCardDrag = function (ev) {
    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its childern
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).setTranslate2D(ev.deltaX, ev.deltaY);
    var pos = $(elem)[0].getBoundingClientRect();
    $("#posSpan").text("X: " + pos.left + " Y: " + pos.top);
};

MJS.onCardDragEnd = function (ev) {
    $("#posSpan").text("");

    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its childern
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).velocity({
        translateX: ev.deltaX,
        translateY: ev.deltaY
    }, 1).velocity({
        translateX: 0,
        translateY: 0
    }, 500);
};

///////////////////////////////////////////////////////////////////
// MJS List Class /////////////////////////////////////////////////

MJS.list = function () {
    this.items = [];
    this._element = null;
    this.onSelect = null;
};

// Todo add select events, List Label, and ID options

MJS.list.prototype.getElement = function () {
    return this._element;
};

MJS.list.prototype.selectFirstItem = function (text) {
    this._element.children().first().click();
};

MJS.list.prototype.selectItemByText = function (text) {
    this._element.children().filter(function () {
        return $(this).text() == text
    }).click();
};

MJS.list.prototype.getSelectText = function (list) {
    return $(list).children(".active").text();
};

MJS.list.prototype.infoToList = function (info, options) {
    opt = {
        ID: "MJS_list" + MJS.fakeGuid(),
        onSelect: null,
        selectedClasses: "grey white-text",
        itemClasses: "white grey-text text-darken-2"
    }

    if (options) {
        if (options.selectedClasses != undefined && typeof options.selectedClasses == "string")
            opt.selectedClasses = options.selectedClasses;
        if (options.itemClasses != undefined && typeof options.itemClasses == "string")
            opt.itemClasses = options.itemClasses;
    }

    // Create list element
    var element = $("

");

    $.each(info.items, function (i, o) {
        var itemElement = $("" + o.text + "");
        itemElement.click(function () {
            var o = $(this);

            //
            o.siblings().removeClass("active");
            o.siblings().removeClass(opt.selectedClasses);
            o.siblings().addClass(opt.itemClasses);

            //
            o.removeClass(opt.itemClasses);
            o.addClass("active");
            o.addClass(opt.selectedClasses);

        });
        element.append(itemElement);
    });

    this._element = element;
    this.selectFirstItem();
    return element;
};

///////////////////////////////////////////////////////////////////
// jQuery Plug-ins /////////////////////////////////////////////////

jQuery.fn.makeCardsDraggable = function (info) {
    $.each(this, function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

jQuery.fn.addButton = function (info) {
    // It's your element
    var o = $(this[0]);

    newElement = $($.parseHTML(MaterializeJS.buttonHtml(info)));
    newElement.addClass("btn");
    newElement.addClass(_emptyStringIfNull(info.classes));
    newElement.attr("onclick", _emptyStringIfNull(info.onClick));
    newElement.width(info.width);
    o.append(newElement);
};

jQuery.fn.addImageCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.imageCardHtml(info)));
    newElement.attr("onclick", _emptyStringIfNull(info.onclick));
    o.append(newElement);
};

jQuery.fn.addPlainPanelCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.plainPanelCardHtml(info)));

    newElement.addClass(_emptyStringIfNull(info.classes));
    o.append(newElement);
};

jQuery.fn.setTranslate2D = function (x, y) {
    // It's your element
    var el = $(this[0])[0];

    var value = 'translateX(' + x + 'px) translateY(' + y + 'px)';

    //el.style.webkitTransform = value;
    //el.style.mozTransform = value;
    el.style.transform = value;
    ticking = false;
};

jQuery.fn.MaterializeJS_Data = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // If the user passes data commit it to the element
    if (info) {
        o.data("MaterializeJS", info);
    }

        // Otherwise return the data from the element to the user
    else {
        var data = o.data("MaterializeJS");
        return data ? data : {};
    }
};

jQuery.fn.openNewDialogue = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // Create div for the dialogue
    var newElement = $("

");

    // Add styling to the div
    // newElement.addClass("card-panel z-depth-3");
    newElement.height(info.fillTarget.height());
    newElement.width(info.fillTarget.width());
    newElement.css("background-color", o.css("background-color"));
    //newElement.css("border-radius", "500px");
    newElement.css("opacity", "0");
    newElement.css("margin", "0px");
    newElement.css("top", (o.offset().top + o.height() * 0.5 - newElement.height() * 0.5) + "px");
    newElement.css("left", (o.offset().left + o.width() * 0.5 - newElement.width() * 0.5) + "px");

    newElement.velocity({
        "scale": "0"
    }, 0);
    //newElement.velocity("finish");

    // Get MaterializeJS Data for the fill target
    var fData = info.fillTarget.MaterializeJS_Data();
    //debugger
    if (fData.currentDialogue) {
        fData.currentDialogue.closeDialogue();
    }

    // Add new div to the DOM
    $("body").append(newElement);
    if (info.onStart && typeof info.onStart == "function") {
        info.onStart(newElement);
    }

    // Set MaterializeJS Data for the fill target
    fData.currentDialogue = newElement;
    info.fillTarget.MaterializeJS_Data(fData);

    //
    var mData = newElement.MaterializeJS_Data();
    mData.origonalOffset = newElement.offset();
    newElement.MaterializeJS_Data(mData);

    newElement.velocity({
        top: info.fillTarget.offset().top + "px",
        left: info.fillTarget.offset().left + "px",
        opacity: 2,
        scale: 1
    }, 300, function () {
        newElement.addClass("card-panel z-depth-3");
    });
};

jQuery.fn.closeDialogue = function (info) {
    // It's your element
    var o = $(this[0]);

    var mData = o.MaterializeJS_Data();
    var returnOffset = mData.origonalOffset;

    o.removeClass("card-panel z-depth-3");

    o.velocity({
        scale: "0",
        top: returnOffset.top + "px",
        left: returnOffset.left + "px"
    }, 300, function () {
        // Get MaterializeJS Data for the fill target
        var fData = info.fillTarget.MaterializeJS_Data();

        if (fData.currentDialogue == o) {
            fData.currentDialogue = null;
            // Set MaterializeJS Data for the fill target
            info.fillTarget.MaterializeJS_Data(fData);
        }
        o.remove();
    });
};

MaterializeJS = MJS;
<commit_msg>Bug fixes and list select call back added<commit_after>var MJS = {};

MJS.fakeGuid = function () {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }

    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
};

function _emptyStringIfNull(obj) {
    try {
        return obj ? obj : "";
    } catch (ex) {

    }

    return "";
}

MJS.infoToGridHtml = function (info, options) {
    opt = {
        labelSize: 4,
        labelBold: true,
        labelClasses: "",
        rowClasses: "half-margin"
    }

    if (options) {
        if (options.labelSize && options.labelSize <= 11)
            opt.labelSize = options.labelSize;
        if (options.labelBold != undefined && typeof options.labelBold == "boolean")
            opt.labelBold = options.labelBold;
        if (options.labelClasses != undefined && typeof options.labelClasses == "string")
            opt.labelClasses = options.labelClasses;
    }

    var text = "";

    var labelTag = "b";
    var infoTag = "span";

    if (!opt.labelBold) {
        labelTag = "span";
    }

    $.each(info, function (i, o) {
        //if(i > 0) text += "
";

        text += "
";
        text += "
<" + labelTag + " class='" + opt.labelClasses + "'>" + o.label + "</" + labelTag + ">
";
        text += "
<" + infoTag + "'>" + o.info + "</" + infoTag + ">
";
        text += "
";
    });

    text += "
";

    return text;
};

MJS.buttonHtml = function (info) {
    if (!info)
        info = {};
    if (typeof info != "object") {
        toast("Error: MaterializeJS.buttonHtml - info must be an object!", 2500);
        return;
    }
    var res = "" + (info.icon_classes == null ? "" : "") + _emptyStringIfNull(info.text) + "";
    return res;
};

MJS.imageCardHtml = function (info) {
    var res = "
\n" + "
\n" + (info.image ? "
\n" : "") + "
\n" + "
\n" + "        " + info.title + "\n" + "
" + info.text + "
\n" + "
\n" +
	//"
\n" +
	//"        This is a link\n" +
	//"        This is a link\n" +
	//"
\n" +
	"
";
    return res;
};

MJS.plainPanelCardHtml = function (info) {
    var res = "
" + "" + _emptyStringIfNull(info.text) + " " + "
" + "
";
    return res;
};

MJS.revealCardHtml = function (id, title, image, info) {
    var res = "
" + "
" + (image ? "" : "") + "
" + "
" + "" + title + "" + "" +
	//"
This is a link
" +
	"
" + "
" + "" + title + "" + "
" + info + "
" + "
" + "
";
    return res;
};

MJS.makeCardDraggable = function (element) {

    var mc = new Hammer.Manager(element);

    mc.add(new Hammer.Pan({
        threshold: 0,
        pointers: 0
    }));
    mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));

    mc.on("panstart panmove", MaterializeJS.onCardDrag);
    mc.on("panend", MaterializeJS.onCardDragEnd);
};

MJS.makeCardsDraggable = function (selector) {

    $.each($(selector), function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

// listen to events...
MJS.onCardDrag = function (ev) {
    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its childern
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).setTranslate2D(ev.deltaX, ev.deltaY);
    var pos = $(elem)[0].getBoundingClientRect();
    $("#posSpan").text("X: " + pos.left + " Y: " + pos.top);
};

MJS.onCardDragEnd = function (ev) {
    $("#posSpan").text("");

    // Get the events target element
    var elem = ev.target;

    // Make sure we work on the card instead of one of its childern
    if (!$(elem).hasClass(".card-panel")) {
        elem = $(elem).closest(".card-panel")[0];
    }

    $(elem).velocity({
        translateX: ev.deltaX,
        translateY: ev.deltaY
    }, 1).velocity({
        translateX: 0,
        translateY: 0
    }, 500);
};

///////////////////////////////////////////////////////////////////
// MJS List Class /////////////////////////////////////////////////

MJS.list = function () {
    this.items = [];
    this._element = null;
    this.onSelect = null;
};

// Todo List Label, and ID options

MJS.list.prototype.getElement = function () {
    return this._element;
};

MJS.list.prototype.clearSelection = function (text) {
    this._element.children().removeClass("active");
    this._element.children().removeClass(opt.selectedClasses);
    this._element.children().addClass(opt.itemClasses);
};

MJS.list.prototype.selectFirstItem = function (text) {
    this._element.children().first().click();
};

MJS.list.prototype.selectItemByText = function (text) {
    this._element.children().filter(function () {
        return $(this).text() == text
    }).click();
};

MJS.list.prototype.getSelectedText = function () {
    return this._element.children(".active").text();
};

MJS.list.prototype.infoToList = function (info, options) {
    opt = {
        ID: "MJS_list" + MJS.fakeGuid(),
        onSelect: null,
        selectedClasses: "grey white-text",
        itemClasses: "white grey-text text-darken-2"
    }

    if (options) {
        if (options.selectedClasses != undefined && typeof options.selectedClasses == "string")
            opt.selectedClasses = options.selectedClasses;
        if (options.itemClasses != undefined && typeof options.itemClasses == "string")
            opt.itemClasses = options.itemClasses;
    }

    // Create list element
    var element = $("

");

    var list = this;

    $.each(info.items, function (i, o) {
        var itemElement = $("" + o.text + "");
        itemElement.click(function () {
            var o = $(this);

            //
            o.siblings().removeClass("active");
            o.siblings().removeClass(opt.selectedClasses);
            o.siblings().addClass(opt.itemClasses);

            //
            o.removeClass(opt.itemClasses);
            o.addClass("active");
            o.addClass(opt.selectedClasses);

            if (list.onSelect) list.onSelect();
        });
        element.append(itemElement);
    });

    this._element = element;
    this.clearSelection();
    return element;
};

///////////////////////////////////////////////////////////////////
// jQuery Plug-ins /////////////////////////////////////////////////

jQuery.fn.makeCardsDraggable = function (info) {
    $.each(this, function (i, o) {
        MaterializeJS.makeCardDraggable(o);
    });
};

jQuery.fn.addButton = function (info) {
    // It's your element
    var o = $(this[0]);

    newElement = $($.parseHTML(MaterializeJS.buttonHtml(info)));
    newElement.addClass("btn");
    newElement.addClass(_emptyStringIfNull(info.classes));
    newElement.attr("onclick", _emptyStringIfNull(info.onClick));
    newElement.width(info.width);
    o.append(newElement);
};

jQuery.fn.addImageCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.imageCardHtml(info)));
    newElement.attr("onclick", _emptyStringIfNull(info.onclick));
    o.append(newElement);
};

jQuery.fn.addPlainPanelCard = function (info) {
    var o = $(this[0]);
    // It's your element
    newElement = $($.parseHTML(MaterializeJS.plainPanelCardHtml(info)));

    newElement.addClass(_emptyStringIfNull(info.classes));
    o.append(newElement);
};

jQuery.fn.setTranslate2D = function (x, y) {
    // It's your element
    var el = $(this[0])[0];

    var value = 'translateX(' + x + 'px) translateY(' + y + 'px)';

    //el.style.webkitTransform = value;
    //el.style.mozTransform = value;
    el.style.transform = value;
    ticking = false;
};

jQuery.fn.MaterializeJS_Data = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // If the user passes data commit it to the element
    if (info) {
        o.data("MaterializeJS", info);
    }

        // Otherwise return the data from the element to the user
    else {
        var data = o.data("MaterializeJS");
        return data ? data : {};
    }
};

jQuery.fn.openNewDialogue = function (info) {
    // Get the jQuery element
    var o = $(this[0]);

    // Create div for the dialogue
    var newElement = $("

");

    // Add styling to the div
    // newElement.addClass("card-panel z-depth-3");
    newElement.height(info.fillTarget.height());
    newElement.width(info.fillTarget.width());
    newElement.css("background-color", o.css("background-color"));
    //newElement.css("border-radius", "500px");
    newElement.css("opacity", "0");
    newElement.css("margin", "0px");
    newElement.css("top", (o.offset().top + o.height() * 0.5 - newElement.height() * 0.5) + "px");
    newElement.css("left", (o.offset().left + o.width() * 0.5 - newElement.width() * 0.5) + "px");

    newElement.velocity({
        "scale": "0"
    }, 0);
    //newElement.velocity("finish");

    // Get MaterializeJS Data for the fill target
    var fData = info.fillTarget.MaterializeJS_Data();
    //debugger
    if (fData.currentDialogue) {
        fData.currentDialogue.closeDialogue(info);
    }

    // Add new div to the DOM
    $("body").append(newElement);
    if (info.onStart && typeof info.onStart == "function") {
        info.onStart(newElement);
    }

    // Set MaterializeJS Data for the fill target
    fData.currentDialogue = newElement;
    info.fillTarget.MaterializeJS_Data(fData);

    //
    var mData = newElement.MaterializeJS_Data();
    mData.origonalOffset = newElement.offset();
    newElement.MaterializeJS_Data(mData);

    newElement.velocity({
        top: info.fillTarget.offset().top + "px",
        left: info.fillTarget.offset().left + "px",
        opacity: 2,
        scale: 1
    }, 300, function () {
        newElement.addClass("card-panel z-depth-3");
    });
};

jQuery.fn.closeDialogue = function (info) {
    // It's your element
    var o = $(this[0]);

    var mData = o.MaterializeJS_Data();
    var returnOffset = mData.origonalOffset;

    o.removeClass("card-panel z-depth-3");

    // Get MaterializeJS Data for the fill target
    var fData = info.fillTarget.MaterializeJS_Data();

    if (fData.currentDialogue == o) {
        fData.currentDialogue = null;
        // Set MaterializeJS Data for the fill target
        info.fillTarget.MaterializeJS_Data(fData);
    }

    o.velocity({
        scale: "0",
        top: returnOffset.top + "px",
        left: returnOffset.left + "px"
    }, {
        duration: 300,
        /* Log all the animated divs. */
        complete: function () {
            o.remove();
        }
    });
};

MaterializeJS = MJS;
<|endoftext|>


<commit_before>(function() {
    Module["locateFile"] = function(url) {
        const scriptUrl = document.currentScript.src;
        return scriptUrl.substr(0, scriptUrl.lastIndexOf("/") + 1) + url;
    }
    const libs = Module["dynamicLibraries"];
    Module["dynamicLibraries"] = [];
    libs.forEach(lib => Module["dynamicLibraries"] += Module["locateFile"](lib));
})();
<commit_msg>[Web] temporary patch unresolved symbol _SDL_CloseAudio<commit_after>(function() {
    Module["locateFile"] = function(url) {
        const scriptUrl = document.currentScript.src;
        return scriptUrl.substr(0, scriptUrl.lastIndexOf("/") + 1) + url;
    }
    const libs = Module["dynamicLibraries"];
    Module["dynamicLibraries"] = [];
    libs.forEach(lib => Module["dynamicLibraries"] += Module["locateFile"](lib));
})();
// This is meaningless, but occurs runtime error on removed...
var _SDL_CloseAudio=function(){};
<|endoftext|>


<commit_before>function _emptyStringIfNull(obj) {
	try {
		return obj ? obj : "";
	} catch(ex) {

	}

	return "";
}

var MaterializeJS = {};

MaterializeJS.infoToGridHtml = function (info, options) {
    opt = {
        labelSize: 4,
        labelBold: true,
        labelClasses: "",
        rowClasses: "half-margin"
    }

    if (options) {
        if (options.labelSize && options.labelSize <= 11)
            opt.labelSize = options.labelSize;
        if (options.labelBold != undefined && typeof options.labelBold == "boolean")
            opt.labelBold = options.labelBold;
        if (options.labelClasses != undefined && typeof options.labelClasses == "string")
            opt.labelClasses = options.labelClasses;
    }

    var text = "";

    var labelTag = "b";
    var infoTag = "span";

    if (!opt.labelBold) {
        labelTag = "span";
    }

    $.each(info, function (i, o) {
        //if(i > 0) text += "
";

        text += "
";
        text += "
<" + labelTag + " class='" + opt.labelClasses + "'>" + o.label + "</" + labelTag + ">
";
        text += "
<" + infoTag + "'>" + o.info + "</" + infoTag + ">
";
        text += "
";
    });

    text += "
";

    return text;
}

MaterializeJS.buttonHtml = function(info) {
	if (!info)
		info = {};
	if ( typeof info != "object") {
		toast("Error: MaterializeJS.buttonHtml - info must be an object!", 2500);
		return;
	}
	var res = "" + (info.icon_classes == null ? "" : "" ) + _emptyStringIfNull(info.text) + "";
	return res;
};

MaterializeJS.imageCardHtml = function(info) {
	var res = "
\n" + "
\n" + (info.image ? "
\n" : "") + "
\n" + "
\n" + "        " + info.title + "\n" + "
" + info.text + "
\n" + "
\n" +
	//"
\n" +
	//"        This is a link\n" +
	//"        This is a link\n" +
	//"
\n" +
	"
";
	return res;
};

MaterializeJS.plainPanelCardHtml = function(info) {
	var res = "
" + "" + _emptyStringIfNull(info.text) + " " + "
" + "
";
	return res;
};

MaterializeJS.revealCardHtml = function(id, title, image, info) {
	var res = "
" + "
" + ( image ? "" : "" ) + "
" + "
" + "" + title + "" + "" +
	//"
This is a link
" +
	"
" + "
" + "" + title + "" + "
" + info + "
" + "
" + "
";
	return res;
};

MaterializeJS.makeCardDraggable = function(element) {

	var mc = new Hammer.Manager(element);

	mc.add(new Hammer.Pan({
		threshold : 0,
		pointers : 0
	}));
	mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));

	mc.on("panstart panmove", MaterializeJS.onCardDrag);
	mc.on("panend", MaterializeJS.onCardDragEnd);
}

MaterializeJS.makeCardsDraggable = function(selector) {

	$.each($(selector), function(i, o) {
		MaterializeJS.makeCardDraggable(o);
	});
}
// listen to events...
MaterializeJS.onCardDrag = function(ev) {
	// Get the events target element
	var elem = ev.target;

	// Make sure we work on the card instead of one of its childern
	if (!$(elem).hasClass(".card-panel")) {
		elem = $(elem).closest(".card-panel")[0];
	}

	$(elem).setTranslate2D(ev.deltaX, ev.deltaY);
	var pos = $(elem)[0].getBoundingClientRect();
	$("#posSpan").text("X: " + pos.left + " Y: " + pos.top);
}

MaterializeJS.onCardDragEnd = function(ev) {
	$("#posSpan").text("");

	// Get the events target element
	var elem = ev.target;

	// Make sure we work on the card instead of one of its childern
	if (!$(elem).hasClass(".card-panel")) {
		elem = $(elem).closest(".card-panel")[0];
	}

	$(elem).velocity({
		translateX : ev.deltaX,
		translateY : ev.deltaY
	}, 1).velocity({
		translateX : 0,
		translateY : 0
	}, 500);

}
///////////////////////////////////////////////////////////////////
// jQuery Plugins /////////////////////////////////////////////////

jQuery.fn.makeCardsDraggable = function(info) {
	$.each(this, function(i, o) {
		MaterializeJS.makeCardDraggable(o);
	});
};

jQuery.fn.addButton = function(info) {
	// It's your element
	var o = $(this[0]);

	newElement = $($.parseHTML(MaterializeJS.buttonHtml(info)));
	newElement.addClass("btn");
	newElement.addClass(_emptyStringIfNull(info.classes));
	newElement.attr("onclick", _emptyStringIfNull(info.onClick));
	newElement.width(info.width);
	o.append(newElement);
};

jQuery.fn.addImageCard = function(info) {
	var o = $(this[0]);
	// It's your element
	newElement = $($.parseHTML(MaterializeJS.imageCardHtml(info)));
	newElement.attr("onclick", _emptyStringIfNull(info.onclick));
	o.append(newElement);
};

jQuery.fn.addPlainPanelCard = function(info) {
	var o = $(this[0]);
	// It's your element
	newElement = $($.parseHTML(MaterializeJS.plainPanelCardHtml(info)));

	newElement.addClass(_emptyStringIfNull(info.classes));
	o.append(newElement);
};

jQuery.fn.setTranslate2D = function(x, y) {
	// It's your element
	var el = $(this[0])[0];

	var value = 'translateX(' + x + 'px) translateY(' + y + 'px)';

	//el.style.webkitTransform = value;
	//el.style.mozTransform = value;
	el.style.transform = value;
	ticking = false;
};

jQuery.fn.MaterializeJS_Data = function(info) {
	// Get the jQuery element
	var o = $(this[0]);

	// If the uesr passes data commit it to the element
	if (info) {
		o.data("MaterializeJS", info);
	}

	// Otherwise return the data from the element to the user
	else {
		var data = o.data("MaterializeJS");
		return data ? data : {};
	}
}

jQuery.fn.openNewDialogue = function(info) {
	// Get the jQuery element
	var o = $(this[0]);

	// Create div for the dialogue
	var newElement = $("

");

	// Add styling to the div
	// newElement.addClass("card-panel z-depth-3");
	newElement.height(info.fillTarget.height());
	newElement.width(info.fillTarget.width());
	newElement.css("background-color", o.css("background-color"));
	//newElement.css("border-radius", "500px");
	newElement.css("opacity", "0");
	newElement.css("margin", "0px");
	newElement.css("top", (o.offset().top + o.height() * 0.5 - newElement.height() * 0.5) + "px");
	newElement.css("left", (o.offset().left + o.width() * 0.5 - newElement.width() * 0.5) + "px");

	newElement.velocity({
		"scale" : "0"
	}, 0);
	//newElement.velocity("finish");

	// Get MaterializeJS Data for the fill target
	var fData = info.fillTarget.MaterializeJS_Data();
	//debugger
	if (fData.currentDialogue) {
		fData.currentDialogue.closeDialogue();
	}

	// Add new div to the DOM
	$("body").append(newElement);
  if(info.onStart && typeof info.onStart == "function"){
    info.onStart(newElement);
  }

	// Set MaterializeJS Data for the fill target
	fData.currentDialogue = newElement;
	info.fillTarget.MaterializeJS_Data(fData);

	//
	var mData = newElement.MaterializeJS_Data();
	mData.origonalOffset = newElement.offset();
	newElement.MaterializeJS_Data(mData);

	newElement.velocity({
		top : info.fillTarget.offset().top + "px",
		left : info.fillTarget.offset().left + "px",
		opacity : 2,
		scale : 1,
		//borderRadius : "3"
	}, 300, function(){
     newElement.addClass("card-panel z-depth-3");
  });
};

jQuery.fn.closeDialogue = function(info) {
	// It's your element
	var o = $(this[0]);

	var mData = o.MaterializeJS_Data();
	var returnOffset = mData.origonalOffset;

  o.removeClass("card-panel z-depth-3");

	o.velocity({
		scale : "0",
		top : returnOffset.top + "px",
		left : returnOffset.left + "px",
		//borderRadius : "500",
	}, 300, function() {
		// Get MaterializeJS Data for the fill target
		var fData = info.fillTarget.MaterializeJS_Data();

		if (fData.currentDialogue == o) {
			fData.currentDialogue = null;
			// Set MaterializeJS Data for the fill target
			info.fillTarget.MaterializeJS_Data(fData);
		}
		o.remove();
	});
};
<commit_msg>Added list class to lib<commit_after>MJS = {};

MJS.fakeGuid = function() {
	function s4() {
		return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
	}

	return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

function _emptyStringIfNull(obj) {
	try {
		return obj ? obj : "";
	} catch(ex) {

	}

	return "";
}

MJS.infoToGridHtml = function(info, options) {
	opt = {
		labelSize : 4,
		labelBold : true,
		labelClasses : "",
		rowClasses : "half-margin"
	}

	if (options) {
		if (options.labelSize && options.labelSize <= 11)
			opt.labelSize = options.labelSize;
		if (options.labelBold != undefined && typeof options.labelBold == "boolean")
			opt.labelBold = options.labelBold;
		if (options.labelClasses != undefined && typeof options.labelClasses == "string")
			opt.labelClasses = options.labelClasses;
	}

	var text = "";

	var labelTag = "b";
	var infoTag = "span";

	if (!opt.labelBold) {
		labelTag = "span";
	}

	$.each(info, function(i, o) {
		//if(i > 0) text += "
";

		text += "
";
		text += "
<" + labelTag + " class='" + opt.labelClasses + "'>" + o.label + "</" + labelTag + ">
";
		text += "
<" + infoTag + "'>" + o.info + "</" + infoTag + ">
";
		text += "
";
	});

	text += "
";

	return text;
}

MJS.buttonHtml = function(info) {
	if (!info)
		info = {};
	if ( typeof info != "object") {
		toast("Error: MaterializeJS.buttonHtml - info must be an object!", 2500);
		return;
	}
	var res = "" + (info.icon_classes == null ? "" : "" ) + _emptyStringIfNull(info.text) + "";
	return res;
};

MJS.imageCardHtml = function(info) {
	var res = "
\n" + "
\n" + (info.image ? "
\n" : "") + "
\n" + "
\n" + "        " + info.title + "\n" + "
" + info.text + "
\n" + "
\n" +
	//"
\n" +
	//"        This is a link\n" +
	//"        This is a link\n" +
	//"
\n" +
	"
";
	return res;
};

MJS.plainPanelCardHtml = function(info) {
	var res = "
" + "" + _emptyStringIfNull(info.text) + " " + "
" + "
";
	return res;
};

MJS.revealCardHtml = function(id, title, image, info) {
	var res = "
" + "
" + ( image ? "" : "" ) + "
" + "
" + "" + title + "" + "" +
	//"
This is a link
" +
	"
" + "
" + "" + title + "" + "
" + info + "
" + "
" + "
";
	return res;
};

MJS.makeCardDraggable = function(element) {

	var mc = new Hammer.Manager(element);

	mc.add(new Hammer.Pan({
		threshold : 0,
		pointers : 0
	}));
	mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));

	mc.on("panstart panmove", MaterializeJS.onCardDrag);
	mc.on("panend", MaterializeJS.onCardDragEnd);
}

MJS.makeCardsDraggable = function(selector) {

	$.each($(selector), function(i, o) {
		MaterializeJS.makeCardDraggable(o);
	});
}
// listen to events...
MJS.onCardDrag = function(ev) {
	// Get the events target element
	var elem = ev.target;

	// Make sure we work on the card instead of one of its childern
	if (!$(elem).hasClass(".card-panel")) {
		elem = $(elem).closest(".card-panel")[0];
	}

	$(elem).setTranslate2D(ev.deltaX, ev.deltaY);
	var pos = $(elem)[0].getBoundingClientRect();
	$("#posSpan").text("X: " + pos.left + " Y: " + pos.top);
}

MJS.onCardDragEnd = function(ev) {
	$("#posSpan").text("");

	// Get the events target element
	var elem = ev.target;

	// Make sure we work on the card instead of one of its childern
	if (!$(elem).hasClass(".card-panel")) {
		elem = $(elem).closest(".card-panel")[0];
	}

	$(elem).velocity({
		translateX : ev.deltaX,
		translateY : ev.deltaY
	}, 1).velocity({
		translateX : 0,
		translateY : 0
	}, 500);

}

///////////////////////////////////////////////////////////////////
// MJS List Class /////////////////////////////////////////////////

MJS.list = function() {
	this.items = [];
};

// Todo add select events, List Lable, and ID options

MJS.list.prototype.selectItemByText = function(text) {
	this.listElement.children().filter(function() {
		return $(this).text() == text
	}).click();
}

MJS.list.prototype.getSelectText = function(list) {
	return $(list).children(".active").text();
}

MJS.list.prototype.infoToList = function(info, options) {
	opt = {
		ID : "MJS_list" + MJS.fakeGuid(),
		onSelect : null,
		selectedClasses : "grey white-text",
		itemClasses : "white grey-text text-darken-2"
	}

	if (options) {
		if (options.selectedClasses != undefined && typeof options.selectedClasses == "string")
			opt.selectedClasses = options.selectedClasses;
		if (options.itemClasses != undefined && typeof options.itemClasses == "string")
			opt.itemClasses = options.itemClasses;
	}

	// Create list element
	var listElement = $("

");

	$.each(info.items, function(i, o) {
		var itemElement = $("" + o.text + "");
		itemElement.click(function() {
			var o = $(this);

			//
			o.siblings().removeClass("active");
			o.siblings().removeClass(opt.selectedClasses);
			o.siblings().addClass(opt.itemClasses);

			//
			o.removeClass(opt.itemClasses);
			o.addClass("active");
			o.addClass(opt.selectedClasses);

		});
		listElement.append(itemElement);
	});

	this.listElement = listElement;
	return listElement;
}

///////////////////////////////////////////////////////////////////
// jQuery Plugins /////////////////////////////////////////////////

jQuery.fn.makeCardsDraggable = function(info) {
	$.each(this, function(i, o) {
		MaterializeJS.makeCardDraggable(o);
	});
};

jQuery.fn.addButton = function(info) {
	// It's your element
	var o = $(this[0]);

	newElement = $($.parseHTML(MaterializeJS.buttonHtml(info)));
	newElement.addClass("btn");
	newElement.addClass(_emptyStringIfNull(info.classes));
	newElement.attr("onclick", _emptyStringIfNull(info.onClick));
	newElement.width(info.width);
	o.append(newElement);
};

jQuery.fn.addImageCard = function(info) {
	var o = $(this[0]);
	// It's your element
	newElement = $($.parseHTML(MaterializeJS.imageCardHtml(info)));
	newElement.attr("onclick", _emptyStringIfNull(info.onclick));
	o.append(newElement);
};

jQuery.fn.addPlainPanelCard = function(info) {
	var o = $(this[0]);
	// It's your element
	newElement = $($.parseHTML(MaterializeJS.plainPanelCardHtml(info)));

	newElement.addClass(_emptyStringIfNull(info.classes));
	o.append(newElement);
};

jQuery.fn.setTranslate2D = function(x, y) {
	// It's your element
	var el = $(this[0])[0];

	var value = 'translateX(' + x + 'px) translateY(' + y + 'px)';

	//el.style.webkitTransform = value;
	//el.style.mozTransform = value;
	el.style.transform = value;
	ticking = false;
};

jQuery.fn.MaterializeJS_Data = function(info) {
	// Get the jQuery element
	var o = $(this[0]);

	// If the uesr passes data commit it to the element
	if (info) {
		o.data("MaterializeJS", info);
	}

	// Otherwise return the data from the element to the user
	else {
		var data = o.data("MaterializeJS");
		return data ? data : {};
	}
}

jQuery.fn.openNewDialogue = function(info) {
	// Get the jQuery element
	var o = $(this[0]);

	// Create div for the dialogue
	var newElement = $("

");

	// Add styling to the div
	// newElement.addClass("card-panel z-depth-3");
	newElement.height(info.fillTarget.height());
	newElement.width(info.fillTarget.width());
	newElement.css("background-color", o.css("background-color"));
	//newElement.css("border-radius", "500px");
	newElement.css("opacity", "0");
	newElement.css("margin", "0px");
	newElement.css("top", (o.offset().top + o.height() * 0.5 - newElement.height() * 0.5) + "px");
	newElement.css("left", (o.offset().left + o.width() * 0.5 - newElement.width() * 0.5) + "px");

	newElement.velocity({
		"scale" : "0"
	}, 0);
	//newElement.velocity("finish");

	// Get MaterializeJS Data for the fill target
	var fData = info.fillTarget.MaterializeJS_Data();
	//debugger
	if (fData.currentDialogue) {
		fData.currentDialogue.closeDialogue();
	}

	// Add new div to the DOM
	$("body").append(newElement);
	if (info.onStart && typeof info.onStart == "function") {
		info.onStart(newElement);
	}

	// Set MaterializeJS Data for the fill target
	fData.currentDialogue = newElement;
	info.fillTarget.MaterializeJS_Data(fData);

	//
	var mData = newElement.MaterializeJS_Data();
	mData.origonalOffset = newElement.offset();
	newElement.MaterializeJS_Data(mData);

	newElement.velocity({
		top : info.fillTarget.offset().top + "px",
		left : info.fillTarget.offset().left + "px",
		opacity : 2,
		scale : 1,
		//borderRadius : "3"
	}, 300, function() {
		newElement.addClass("card-panel z-depth-3");
	});
};

jQuery.fn.closeDialogue = function(info) {
	// It's your element
	var o = $(this[0]);

	var mData = o.MaterializeJS_Data();
	var returnOffset = mData.origonalOffset;

	o.removeClass("card-panel z-depth-3");

	o.velocity({
		scale : "0",
		top : returnOffset.top + "px",
		left : returnOffset.left + "px",
		//borderRadius : "500",
	}, 300, function() {
		// Get MaterializeJS Data for the fill target
		var fData = info.fillTarget.MaterializeJS_Data();

		if (fData.currentDialogue == o) {
			fData.currentDialogue = null;
			// Set MaterializeJS Data for the fill target
			info.fillTarget.MaterializeJS_Data(fData);
		}
		o.remove();
	});
};

MaterializeJS = MJS;
<|endoftext|>