<commit_before>(function (window, document, angular, undefined) {
    'use strict';

    var DEBUG_BAR_MODULE = angular.module('angular-debug-bar', []);

    DEBUG_BAR_MODULE.provider('debugBar', function () {

        var DEFAULT_INTERVAL = 1000,
            INITIAL_TIMEOUT = 100,
            PLUGINS = {},
            PERFORMANCE = window.performance || window.msPerformance || window.webkitPerformance || window.mozPerformance,
            DEFAULT_SETTINGS_KEYS = ['label', 'icon', 'unit'],
            PluginAbstract = function () {},
            _pick = function (object, props) {
                var index = -1,
                    length = props.length,
                    result = {};

                while (++index < length) {
                    var key = props[index];
                    if (key in object) {
                        result[key] = object[key];
                    }
                }
                return result;
            },
            setUpDefaultPlugins = function (that) {
                that.registerPlugin('watchCount', function () {
                    var root = angular.element(document.getElementsByTagName('html')),
                        watchers = [],
                        func = function (element) {
                            if (element.data().hasOwnProperty('$scope')) {
                                angular.forEach(element.data().$scope.$$watchers, function (watcher) {
                                    watchers.push(watcher);
                                });
                            }

                            angular.forEach(element.children(), function (childElement) {
                                func(angular.element(childElement));
                            });
                        };
                    if (0 === watchers.length) {
                        func(root);
                    }
                    return watchers.length;
                }, {
                    label: 'Watchers',
                    icon: 'adb-icon-eye'
                });

                that.registerPlugin('listenerCount', function () {
                    var root = angular.element(document.getElementsByTagName('html')),
                        listeners = [],
                        func = function (element) {
                            if (element.data().hasOwnProperty('$scope')) {
                                angular.forEach(element.data().$scope.$$listeners, function (listener) {
                                    listeners.push(listener);
                                });
                            }

                            angular.forEach(element.children(), function (childElement) {
                                func(angular.element(childElement));
                            });
                        };
                    if (0 === listeners.length) {
                        func(root);
                    }
                    return listeners.length;
                }, {
                    label: 'Listeners',
                    icon: 'adb-icon-headphones'
                });

                that.registerPlugin('DOMObjectCount', function () {
                    return document.all.length;
                }, {
                    label: 'DOM objects',
                    icon: 'adb-icon-home'
                });

                that.registerPlugin('loadTime', function () {
                    return (PERFORMANCE.timing.loadEventStart - PERFORMANCE.timing.navigationStart);
                }, {
                    label: 'Load time',
                    unit: 'ms'
                });

                that.registerPlugin('latency', function () {
                    return (PERFORMANCE.timing.responseStart - PERFORMANCE.timing.connectStart);
                }, {
                    label: 'Latency',
                    unit: 'ms'
                });

                that.registerPlugin('cssFilesCount', function () {
                    return document.querySelectorAll('link[rel="stylesheet"]').length;
                }, {
                    label: 'CSS files'
                });

                that.registerPlugin('jsFilesCount', function () {
                    return document.querySelectorAll('script').length;
                }, {
                    label: 'JS files'
                });

                that.registerPlugin('imagesCount', function () {
                    return document.querySelectorAll('img').length;
                }, {
                    label: 'Images'
                });

                that.registerPlugin('numberOfRequests', function () {
                    if ('getEntriesByType' in window.performance) {
                        return window.performance.getEntriesByType('resource').length
                    }
                    return 'N/A';
                }, {
                    label: 'Number of requests'
                });
            };

        angular.extend(PluginAbstract.prototype, {
            extendedScope: undefined,
            settings: undefined,
            invokeFn: angular.noop,
            setScope: function (scope) {
                Object.getPrototypeOf(this).extendedScope = scope;
            },
            getSettings: function () {
                return this.settings;
            },
            run: function () {
                this.extendedScope[this.settings.name] = this.invokeFn();
            }
        });

        this.clearDefaultPlugins = function () {
            PLUGINS = {};
        };

        this.setRefreshInterval = function (interval) {
            DEFAULT_INTERVAL = parseInt(interval, 10) || DEFAULT_INTERVAL;
        };

        this.registerPlugin = function (name, invokeFn, settings, undefined) {
            if (!angular.isString(name) && '' !== name) {
                throw new Error('Plugin name: "' + name + '" is not valid string value!');
            }

            if (PLUGINS[name]) {
                throw new Error('Plugin "' + name + '" already exists!');
            }

            if (!angular.isFunction(invokeFn)) {
                throw new Error('Value function is required!');
            }
            if (settings && !angular.isObject(settings)) {
                throw new Error('Settings is not an object!');
            }

            if (!settings) {
                settings = {};
            } else {
                settings = _pick(settings, DEFAULT_SETTINGS_KEYS);
            }

            angular.extend(settings, {
                name: name
            });

            var Fn = function () {};
            Fn.prototype = new PluginAbstract();
            angular.extend(Fn.prototype, {
                settings: angular.extend(angular.copy(DEFAULT_SETTINGS_KEYS), settings),
                invokeFn: invokeFn
            });
            PLUGINS[name] = new Fn();
        };

        setUpDefaultPlugins(this);

        this.$get = ['$interval', '$timeout', function ($interval, $timeout) {
            var INTERVAL;

            return {
                getPlugins: function () {
                    return angular.copy(PLUGINS);
                },
                run: function () {
                    var runForEach = function () {
                        $timeout(function () {
                            angular.forEach(PLUGINS, function (plugin) {
                                plugin.run();
                            });
                        }, !INTERVAL ? INITIAL_TIMEOUT : 0);
                    };

                    if (INTERVAL) {
                        $interval.cancel(INTERVAL);
                    } else {
                        runForEach();
                    }
                    INTERVAL = $interval(runForEach, DEFAULT_INTERVAL);
                }
            };
        }];

    });

    DEBUG_BAR_MODULE.directive('angularDebugBarPlugins', [
        '$compile',
        function ($compile) {
            var template = function (settings) {
                var template = '

';
                if (settings.icon) {
                    template += '';
                }
                template += '';
                if (settings.unit) {
                    template += '' + settings.unit + '';
                }
                template += '
';
                if (settings.label) {
                    template += '
' + settings.label + '
';
                }
                return template + '
';
            };

            return {
                restrict: 'E',
                replace: true,
                scope: false,
                template: '

',
                link: function (scope, element) {
                    angular.forEach(scope.plugins, function (plugin) {
                        plugin.setScope(scope);
                        element.append($compile(template(plugin.getSettings()))(scope));
                    });
                }
            };
        }
    ]);

    DEBUG_BAR_MODULE.directive('angularDebugBar', [
        '$compile', 'debugBar',
        function ($compile, debugBar) {
            return {
                restrict: 'E',
                replace: true,
                scope: true,
                controller: ['$scope', function ($scope) {
                    var localStorage = window.localStorage,
                        localStorageKey = 'adb.open',
                        isLocalStorageAvailable = function () {
                            return !!localStorage;
                        };

                    $scope.plugins = {};
                    $scope.show = isLocalStorageAvailable() ? JSON.parse(localStorage.getItem(localStorageKey)) : false;
                    if ($scope.show) {
                        debugBar.run();
                    }

                    $scope.showHide = function (event) {
                        event.preventDefault();
                        $scope.show = !$scope.show;
                        if (isLocalStorageAvailable()) {
                            localStorage.setItem(localStorageKey, $scope.show);
                        }
                        if ($scope.show) {
                            debugBar.run();
                        }
                    };
                }],
                compile: function ($element) {
                    var template = '
' +
                        '<button class="adb-icon-cog" ng-click="showHide($event)"></button>' +
                        '<angular-debug-bar-plugins></angular-debug-bar-plugins>' +
                        '
';

                    return function ($scope) {
                        $scope.plugins = debugBar.getPlugins();
                        $element.replaceWith($compile(template)($scope));
                    };
                }
            };
        }
    ]);
})(window, window.document, window.angular);
<commit_msg>optionally retain plugins for clearDefaultPlugins<commit_after>(function (window, document, angular, undefined) {
    'use strict';

    var DEBUG_BAR_MODULE = angular.module('angular-debug-bar', []);

    DEBUG_BAR_MODULE.provider('debugBar', function () {

        var DEFAULT_INTERVAL = 1000,
            INITIAL_TIMEOUT = 100,
            PLUGINS = {},
            PERFORMANCE = window.performance || window.msPerformance || window.webkitPerformance || window.mozPerformance,
            DEFAULT_SETTINGS_KEYS = ['label', 'icon', 'unit'],
            PluginAbstract = function () {},
            _pick = function (object, props) {
                var index = -1,
                    length = props.length,
                    result = {};

                while (++index < length) {
                    var key = props[index];
                    if (key in object) {
                        result[key] = object[key];
                    }
                }
                return result;
            },
            setUpDefaultPlugins = function (that) {
                that.registerPlugin('watchCount', function () {
                    var root = angular.element(document.getElementsByTagName('html')),
                        watchers = [],
                        func = function (element) {
                            if (element.data().hasOwnProperty('$scope')) {
                                angular.forEach(element.data().$scope.$$watchers, function (watcher) {
                                    watchers.push(watcher);
                                });
                            }

                            angular.forEach(element.children(), function (childElement) {
                                func(angular.element(childElement));
                            });
                        };
                    if (0 === watchers.length) {
                        func(root);
                    }
                    return watchers.length;
                }, {
                    label: 'Watchers',
                    icon: 'adb-icon-eye'
                });

                that.registerPlugin('listenerCount', function () {
                    var root = angular.element(document.getElementsByTagName('html')),
                        listeners = [],
                        func = function (element) {
                            if (element.data().hasOwnProperty('$scope')) {
                                angular.forEach(element.data().$scope.$$listeners, function (listener) {
                                    listeners.push(listener);
                                });
                            }

                            angular.forEach(element.children(), function (childElement) {
                                func(angular.element(childElement));
                            });
                        };
                    if (0 === listeners.length) {
                        func(root);
                    }
                    return listeners.length;
                }, {
                    label: 'Listeners',
                    icon: 'adb-icon-headphones'
                });

                that.registerPlugin('DOMObjectCount', function () {
                    return document.all.length;
                }, {
                    label: 'DOM objects',
                    icon: 'adb-icon-home'
                });

                that.registerPlugin('loadTime', function () {
                    return (PERFORMANCE.timing.loadEventStart - PERFORMANCE.timing.navigationStart);
                }, {
                    label: 'Load time',
                    unit: 'ms'
                });

                that.registerPlugin('latency', function () {
                    return (PERFORMANCE.timing.responseStart - PERFORMANCE.timing.connectStart);
                }, {
                    label: 'Latency',
                    unit: 'ms'
                });

                that.registerPlugin('cssFilesCount', function () {
                    return document.querySelectorAll('link[rel="stylesheet"]').length;
                }, {
                    label: 'CSS files'
                });

                that.registerPlugin('jsFilesCount', function () {
                    return document.querySelectorAll('script').length;
                }, {
                    label: 'JS files'
                });

                that.registerPlugin('imagesCount', function () {
                    return document.querySelectorAll('img').length;
                }, {
                    label: 'Images'
                });

                that.registerPlugin('numberOfRequests', function () {
                    if ('getEntriesByType' in window.performance) {
                        return window.performance.getEntriesByType('resource').length
                    }
                    return 'N/A';
                }, {
                    label: 'Number of requests'
                });
            };

        angular.extend(PluginAbstract.prototype, {
            extendedScope: undefined,
            settings: undefined,
            invokeFn: angular.noop,
            setScope: function (scope) {
                Object.getPrototypeOf(this).extendedScope = scope;
            },
            getSettings: function () {
                return this.settings;
            },
            run: function () {
                this.extendedScope[this.settings.name] = this.invokeFn();
            }
        });

        this.clearDefaultPlugins = function (keepPlugins) {
            keepPlugins = keepPlugins || [];
            PLUGINS = _pick(PLUGINS, keepPlugins);
        };

        this.setRefreshInterval = function (interval) {
            DEFAULT_INTERVAL = parseInt(interval, 10) || DEFAULT_INTERVAL;
        };

        this.registerPlugin = function (name, invokeFn, settings, undefined) {
            if (!angular.isString(name) && '' !== name) {
                throw new Error('Plugin name: "' + name + '" is not valid string value!');
            }

            if (PLUGINS[name]) {
                throw new Error('Plugin "' + name + '" already exists!');
            }

            if (!angular.isFunction(invokeFn)) {
                throw new Error('Value function is required!');
            }
            if (settings && !angular.isObject(settings)) {
                throw new Error('Settings is not an object!');
            }

            if (!settings) {
                settings = {};
            } else {
                settings = _pick(settings, DEFAULT_SETTINGS_KEYS);
            }

            angular.extend(settings, {
                name: name
            });

            var Fn = function () {};
            Fn.prototype = new PluginAbstract();
            angular.extend(Fn.prototype, {
                settings: angular.extend(angular.copy(DEFAULT_SETTINGS_KEYS), settings),
                invokeFn: invokeFn
            });
            PLUGINS[name] = new Fn();
        };

        setUpDefaultPlugins(this);

        this.$get = ['$interval', '$timeout', function ($interval, $timeout) {
            var INTERVAL;

            return {
                getPlugins: function () {
                    return angular.copy(PLUGINS);
                },
                run: function () {
                    var runForEach = function () {
                        $timeout(function () {
                            angular.forEach(PLUGINS, function (plugin) {
                                plugin.run();
                            });
                        }, !INTERVAL ? INITIAL_TIMEOUT : 0);
                    };

                    if (INTERVAL) {
                        $interval.cancel(INTERVAL);
                    } else {
                        runForEach();
                    }
                    INTERVAL = $interval(runForEach, DEFAULT_INTERVAL);
                }
            };
        }];

    });

    DEBUG_BAR_MODULE.directive('angularDebugBarPlugins', [
        '$compile',
        function ($compile) {
            var template = function (settings) {
                var template = '

';
                if (settings.icon) {
                    template += '';
                }
                template += '';
                if (settings.unit) {
                    template += '' + settings.unit + '';
                }
                template += '
';
                if (settings.label) {
                    template += '
' + settings.label + '
';
                }
                return template + '
';
            };

            return {
                restrict: 'E',
                replace: true,
                scope: false,
                template: '

',
                link: function (scope, element) {
                    angular.forEach(scope.plugins, function (plugin) {
                        plugin.setScope(scope);
                        element.append($compile(template(plugin.getSettings()))(scope));
                    });
                }
            };
        }
    ]);

    DEBUG_BAR_MODULE.directive('angularDebugBar', [
        '$compile', 'debugBar',
        function ($compile, debugBar) {
            return {
                restrict: 'E',
                replace: true,
                scope: true,
                controller: ['$scope', function ($scope) {
                    var localStorage = window.localStorage,
                        localStorageKey = 'adb.open',
                        isLocalStorageAvailable = function () {
                            return !!localStorage;
                        };

                    $scope.plugins = {};
                    $scope.show = isLocalStorageAvailable() ? JSON.parse(localStorage.getItem(localStorageKey)) : false;
                    if ($scope.show) {
                        debugBar.run();
                    }

                    $scope.showHide = function (event) {
                        event.preventDefault();
                        $scope.show = !$scope.show;
                        if (isLocalStorageAvailable()) {
                            localStorage.setItem(localStorageKey, $scope.show);
                        }
                        if ($scope.show) {
                            debugBar.run();
                        }
                    };
                }],
                compile: function ($element) {
                    var template = '
' +
                        '<button class="adb-icon-cog" ng-click="showHide($event)"></button>' +
                        '<angular-debug-bar-plugins></angular-debug-bar-plugins>' +
                        '
';

                    return function ($scope) {
                        $scope.plugins = debugBar.getPlugins();
                        $element.replaceWith($compile(template)($scope));
                    };
                }
            };
        }
    ]);
})(window, window.document, window.angular);
<|endoftext|>


<commit_before>/**
 * Contains everything that belongs into the html footer
 * License, Credits
 * @author Fabian Beuke <mail@beuke.org>
 * @license AGPL-3.0
 */

import React from 'react'

export default class Footer extends React.Component {
    shouldComponentUpdate (nextProps, nextState) {
        return false
    }

    render () {
        return (

                        Credits to Carlo Zapponi

                        This work is licensed under the
                        GNU Affero General Public License

        )
    }
}
<commit_msg>Footer class -> functional component<commit_after>/**
 * Contains everything that belongs into the html footer
 * License, Credits
 * @author Fabian Beuke <mail@beuke.org>
 * @license AGPL-3.0
 */
import React from "react"

export default function Footer() {
    return (

                Credits to Carlo Zapponi

                This work is licensed under the{" "}

                    GNU Affero General Public License

    )
}
<|endoftext|>


<commit_before>/*
Angular-ui bootstrap editable timepicker
http://angular-ui.github.io/bootstrap/#/timepicker
*/
angular.module('xeditable').directive('editableBstime', ['editableDirectiveFactory',
  function(editableDirectiveFactory) {
    return editableDirectiveFactory({
      directiveName: 'editableBstime',
      inputTpl: '<timepicker></timepicker>',
      render: function() {
        this.parent.render.call(this);

        // timepicker can't update model when ng-model set directly to it
        // see: https://github.com/angular-ui/bootstrap/issues/1141
        // so we wrap it into DIV
        var div = angular.element('

');

        // move ng-model
        div.attr('ng-model', this.inputEl.attr('ng-model'));
        this.inputEl.removeAttr('ng-model');

        // move ng-change
        if(this.attrs.eNgChange) {
          div.attr('ng-change', this.inputEl.attr('ng-change'));
          this.inputEl.removeAttr('ng-change');
        }

        // wrap
        this.inputEl.wrap(div);
      }
    });
}]);<commit_msg>bstime: comments<commit_after>/*
Angular-ui bootstrap editable timepicker
http://angular-ui.github.io/bootstrap/#/timepicker
*/
angular.module('xeditable').directive('editableBstime', ['editableDirectiveFactory',
  function(editableDirectiveFactory) {
    return editableDirectiveFactory({
      directiveName: 'editableBstime',
      inputTpl: '<timepicker></timepicker>',
      render: function() {
        this.parent.render.call(this);

        // timepicker can't update model when ng-model set directly to it
        // see: https://github.com/angular-ui/bootstrap/issues/1141
        // so we wrap it into DIV
        var div = angular.element('

');

        // move ng-model to wrapping div
        div.attr('ng-model', this.inputEl.attr('ng-model'));
        this.inputEl.removeAttr('ng-model');

        // move ng-change to wrapping div
        if(this.attrs.eNgChange) {
          div.attr('ng-change', this.inputEl.attr('ng-change'));
          this.inputEl.removeAttr('ng-change');
        }

        // wrap
        this.inputEl.wrap(div);
      }
    });
}]);<|endoftext|>


<commit_before>import { Media } from "../Media";
import { loadJS } from "../../core/Load";
import { ajax } from "../../net/Net";
import { ratio } from "../../core/Util";
import TLError from "../../core/TLError";

export default class Imgur extends Media {

    _loadMedia() {
        try {
            var self = this;

            if (this.data.url.match("<blockquote class=['\"]imgur-embed-pub['\"]")) {
                var found = this.data.url.match(/(imgur\.com)\/(\w+)/);
                this.media_id = found[2];
                this.data.url = "http://imgur.com/gallery/" + this.media_id;
            } else if (this.data.url) {
                this.media_id = this.data.url.split('/').slice(-1)[0];
            }

            loadJS([
                    'https://s.imgur.com/min/embed.js'
                ],
                function() {
                    self.createMedia();
                }
            );

        } catch (e) {
            this.loadErrorDisplay(this._("imgur_invalidurl_err"));
        }
    }

    createMedia() {
        var self = this;
        var api_url = "https://api.imgur.com/oembed.json?url=" + this.data.url;

        // Content div
        this._el.content_item = this.domCreate("div", "tl-media-item tl-media-image tl-media-imgur",
            this._el.content);

        // API Call

        ajax({
            type: 'GET',
            url: api_url,
            dataType: 'json',
            success: function(data) {
                try {
                    self._el.content_item.innerHTML = data.html;
                    setInterval(function() {
                        if (document.querySelector("blockquote.imgur-embed-pub") == null) {
                            clearInterval();
                        } else {
                            imgurEmbed.createIframe();
                            document.getElementById("imageElement").removeAttribute("style");
                            document.getElementById("image").removeAttribute("style");
                        }
                    }, 2000);
                } catch (e) {
                    console.log("Error processing imgur ajax response", e)
                }
            },
            error: function(xhr, errorType, error) {
                if (errorType == 'parsererror') {
                    var error = new TLError("invalid_url_err");
                } else {
                    var error = new TLError("unknown_read_err", errorType);
                }
                self.loadErrorDisplay(self._("imgur_invalidurl_err"));
            }
        });
        this.onLoaded();

    }

    _updateMediaDisplay() {
        //this.el.content_item = document.getElementById(this._el.content_item.id);
        this._el.content_item.style.width = this.options.width + "px";
        this._el.content_item.style.height = ratio.r16_9({ w: this.options.width }) + "px";
    }

}<commit_msg>fix error message code<commit_after>import { Media } from "../Media";
import { loadJS } from "../../core/Load";
import { ajax } from "../../net/Net";
import { ratio } from "../../core/Util";
import TLError from "../../core/TLError";

export default class Imgur extends Media {

    _loadMedia() {
        try {
            var self = this;

            if (this.data.url.match("<blockquote class=['\"]imgur-embed-pub['\"]")) {
                var found = this.data.url.match(/(imgur\.com)\/(\w+)/);
                this.media_id = found[2];
                this.data.url = "http://imgur.com/gallery/" + this.media_id;
            } else if (this.data.url) {
                this.media_id = this.data.url.split('/').slice(-1)[0];
            }

            loadJS([
                    'https://s.imgur.com/min/embed.js'
                ],
                function() {
                    self.createMedia();
                }
            );

        } catch (e) {
            this.loadErrorDisplay(this._("imgur_invalidurl_err"));
        }
    }

    createMedia() {
        var self = this;
        var api_url = "https://api.imgur.com/oembed.json?url=" + this.data.url;

        // Content div
        this._el.content_item = this.domCreate("div", "tl-media-item tl-media-image tl-media-imgur",
            this._el.content);

        // API Call

        ajax({
            type: 'GET',
            url: api_url,
            dataType: 'json',
            success: function(data) {
                try {
                    self._el.content_item.innerHTML = data.html;
                    setInterval(function() {
                        if (document.querySelector("blockquote.imgur-embed-pub") == null) {
                            clearInterval();
                        } else {
                            imgurEmbed.createIframe();
                            document.getElementById("imageElement").removeAttribute("style");
                            document.getElementById("image").removeAttribute("style");
                        }
                    }, 2000);
                } catch (e) {
                    console.log("Error processing imgur ajax response", e)
                }
            },
            error: function(xhr, errorType, error) {
                if (errorType == 'parsererror') {
                    self.loadErrorDisplay(self._("imgur_invalidurl_err"));
                } else {
                    self.loadErrorDisplay(self._("unknown_read_err", errorType));
                }
            }
        });
        this.onLoaded();

    }

    _updateMediaDisplay() {
        //this.el.content_item = document.getElementById(this._el.content_item.id);
        this._el.content_item.style.width = this.options.width + "px";
        this._el.content_item.style.height = ratio.r16_9({ w: this.options.width }) + "px";
    }

}<|endoftext|>


<commit_before>function notlarComboBoxOlustur(index) {
    let not_cb_html = '<select id="not' + index + '" class="form-control">' +
        '<option >Seçiniz</option>' +
        '<option value="4.0">AA</option>' +
        '<option value="3.5">BA</option>' +
        '<option value="3.0">BB</option>' +
        '<option value="2.5">CB</option>' +
        '<option value="2.0">CC</option>' +
        '<option value="1.5">DC</option>' +
        '<option value="1.0">DD</option>' +
        '<option value="0.5">FD</option>' +
        '<option value="0.0">FF</option>' +
        '</select>';
    return not_cb_html;
}

function kredilerComboBoxOlustur(index) {
    let kredi_cb_html = '<select id="kredi' + index + '" class="form-control"> ';
    for (i = 0; i < 30; i++) {
        kredi_cb_html += '<option value="' + (i + 1) + '">' + (i + 1) + '</option>';
    }
    kredi_cb_html += '</select>';

    return kredi_cb_html;
}

function dersKredisiniGetir(all_courses, course_code) {
    let course = all_courses.find(function (course) {
        return course.course_code === course_code;
    });
    if (course === undefined) {
        alert("course_ects.json'da bulunamayan ders: " + course_code);
        console.log("Bunulanamayan ders: [" + course_code + "]");
    }

    return course.course_ects[0];
}

function tabloyaDersEkle(course_code, course_name, index) {
    let course_name_html = '<input type="text" class="form-control col-sm-10" id="dersadi' + index + '" value="' + course_name + '">';
    let course_credits_html = kredilerComboBoxOlustur(index);
    let course_grades_html = notlarComboBoxOlustur(index);

    $("#not_tablosu").find('tbody')
        .append($('
')
            .append($('').append(course_code))
            .append($('').append(course_name_html))
            .append($('').append(course_credits_html))
            .append($('').append(course_grades_html))
            .append($('').append('<input color="black" class="silinicekSatir" type="button" value="Sil">'))
        );
}
let VALID_GRADES = ["AA", "BA", "BB", "CB", "CC", "DC", "DD", "FD", "FF"];

function ganoHesaplaYazdir() {
    let not_kredi_dict = {};
    $("tr").each(function () {
        let id = $(this).attr('id');
        let not = $("#not" + id + " option:selected").val();
        let kredi = $("#kredi" + id + " option:selected").val();

        if (not !== "Seçiniz") {
            not = parseFloat(not);
            if (not_kredi_dict[not]) {
                not_kredi_dict[not] = not_kredi_dict[not] + parseInt(kredi);
            } else {
                not_kredi_dict[not] = parseInt(kredi);
            }
        }
    });

    delete not_kredi_dict['NaN'];

    let tamamlananKredi = 0;
    let gano = 0.0;

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        tamamlananKredi = tamamlananKredi + kredi;
    }

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        gano = gano + kredi * not;
    }
    gano = gano / tamamlananKredi;
    gano = parseFloat(gano).toFixed(2);

    $("#gano").text(gano);
    $("#akts").text(tamamlananKredi);
}

chrome.storage.sync.get("parsed_courses", function (items) {

    $.getJSON("https://raw.githubusercontent.com/cankatabaci/ChromeEklenti-v1/master/src/course_ects.json", function (json) {
        let all_courses = json;
        let parsed_courses = items.parsed_courses;

        let satirIndisi = 0;

        for (index = 0; index < parsed_courses.length; ++index) {

            if (VALID_GRADES.includes(parsed_courses[index].course_grade.toString()) || parsed_courses[index].course_grade.toString() === "A") {

                let course_code = parsed_courses[index].course_code;
                let course_name = parsed_courses[index].course_name;
                tabloyaDersEkle(course_code, course_name, satirIndisi);

                let course_credit = dersKredisiniGetir(all_courses, course_code);

                $("#not" + satirIndisi + " option").filter(function () { // selecting grade options based on its text
                    return $(this).text() === parsed_courses[index].course_grade;
                }).prop("selected", true);

                $("#kredi" + satirIndisi + " option").filter(function () { // selecting credits options based on its text
                    return $(this).text() === course_credit.toString();
                }).prop("selected", true);

                ganoHesaplaYazdir();

                satirIndisi++;
            } else {
                console.log(parsed_courses[index].course_grade);
            }
        }

    });
});

function satirdakiDersAdiniGetirme(satirID) {
    let degisken = "dersadi" + satirID;
    return $("#" + degisken).val();
}

$(document).ready(function () {

    $('#not_tablosu').on('click', 'select', function () {
        ganoHesaplaYazdir();
    });

    $('#not_tablosu').on('click', '.silinicekSatir', function () {
        let aktif = $(this);
        let satirID = aktif.closest("tr").attr('id');
        let dersAd = satirdakiDersAdiniGetirme(satirID);
        if (confirm(dersAd + ' Dersini Silmek İstediğinizden Emin Misiniz?')) {
            $(this).parent('td').parent('tr').remove();
            ganoHesaplaYazdir();
        }
    });

    $('#btn').click(function () {
        let kod = "Eklenen";
        let name = "";
        let id = $('#not_tablosu tr:last').attr('id');

        tabloyaDersEkle(kod, name, id + 1);
        alert("Yeni Ders Satırı Eklenmiştir");
        $("html, body").animate({scrollTop: $(document).height() - $(window).height()});//Scrolls to bottom.
    });

    $('#yenile').click(function () {
        location.reload();
    });

});
<commit_msg>Sil butonu class güncellendi<commit_after>function notlarComboBoxOlustur(index) {
    let not_cb_html = '<select id="not' + index + '" class="form-control">' +
        '<option >Seçiniz</option>' +
        '<option value="4.0">AA</option>' +
        '<option value="3.5">BA</option>' +
        '<option value="3.0">BB</option>' +
        '<option value="2.5">CB</option>' +
        '<option value="2.0">CC</option>' +
        '<option value="1.5">DC</option>' +
        '<option value="1.0">DD</option>' +
        '<option value="0.5">FD</option>' +
        '<option value="0.0">FF</option>' +
        '</select>';
    return not_cb_html;
}

function kredilerComboBoxOlustur(index) {
    let kredi_cb_html = '<select id="kredi' + index + '" class="form-control"> ';
    for (i = 0; i < 30; i++) {
        kredi_cb_html += '<option value="' + (i + 1) + '">' + (i + 1) + '</option>';
    }
    kredi_cb_html += '</select>';

    return kredi_cb_html;
}

function dersKredisiniGetir(all_courses, course_code) {
    let course = all_courses.find(function (course) {
        return course.course_code === course_code;
    });
    if (course === undefined) {
        alert("course_ects.json'da bulunamayan ders: " + course_code);
        console.log("Bunulanamayan ders: [" + course_code + "]");
    }

    return course.course_ects[0];
}

function tabloyaDersEkle(course_code, course_name, index) {
    let course_name_html = '<input type="text" class="form-control col-sm-10" id="dersadi' + index + '" value="' + course_name + '">';
    let course_credits_html = kredilerComboBoxOlustur(index);
    let course_grades_html = notlarComboBoxOlustur(index);

    $("#not_tablosu").find('tbody')
        .append($('
')
            .append($('').append(course_code))
            .append($('').append(course_name_html))
            .append($('').append(course_credits_html))
            .append($('').append(course_grades_html))
            .append($('').append('<input color="black" class="btn btn-default" id="silinicekSatir" type="button" value="Sil">'))
        );
}
let VALID_GRADES = ["AA", "BA", "BB", "CB", "CC", "DC", "DD", "FD", "FF"];

function ganoHesaplaYazdir() {
    let not_kredi_dict = {};
    $("tr").each(function () {
        let id = $(this).attr('id');
        let not = $("#not" + id + " option:selected").val();
        let kredi = $("#kredi" + id + " option:selected").val();

        if (not !== "Seçiniz") {
            not = parseFloat(not);
            if (not_kredi_dict[not]) {
                not_kredi_dict[not] = not_kredi_dict[not] + parseInt(kredi);
            } else {
                not_kredi_dict[not] = parseInt(kredi);
            }
        }
    });

    delete not_kredi_dict['NaN'];

    let tamamlananKredi = 0;
    let gano = 0.0;

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        tamamlananKredi = tamamlananKredi + kredi;
    }

    for (let not in not_kredi_dict) {
        let kredi = parseInt(not_kredi_dict[not]);
        gano = gano + kredi * not;
    }
    gano = gano / tamamlananKredi;
    gano = parseFloat(gano).toFixed(2);

    $("#gano").text(gano);
    $("#akts").text(tamamlananKredi);
}

chrome.storage.sync.get("parsed_courses", function (items) {

    $.getJSON("https://raw.githubusercontent.com/cankatabaci/ChromeEklenti-v1/master/src/course_ects.json", function (json) {
        let all_courses = json;
        let parsed_courses = items.parsed_courses;

        let satirIndisi = 0;

        for (index = 0; index < parsed_courses.length; ++index) {

            if (VALID_GRADES.includes(parsed_courses[index].course_grade.toString()) || parsed_courses[index].course_grade.toString() === "A") {

                let course_code = parsed_courses[index].course_code;
                let course_name = parsed_courses[index].course_name;
                tabloyaDersEkle(course_code, course_name, satirIndisi);

                let course_credit = dersKredisiniGetir(all_courses, course_code);

                $("#not" + satirIndisi + " option").filter(function () { // selecting grade options based on its text
                    return $(this).text() === parsed_courses[index].course_grade;
                }).prop("selected", true);

                $("#kredi" + satirIndisi + " option").filter(function () { // selecting credits options based on its text
                    return $(this).text() === course_credit.toString();
                }).prop("selected", true);

                ganoHesaplaYazdir();

                satirIndisi++;
            } else {
                console.log(parsed_courses[index].course_grade);
            }
        }

    });
});

function satirdakiDersAdiniGetirme(satirID) {
    let degisken = "dersadi" + satirID;
    return $("#" + degisken).val();
}

$(document).ready(function () {

    $('#not_tablosu').on('click', 'select', function () {
        ganoHesaplaYazdir();
    });

    $('#not_tablosu').on('click', '#silinicekSatir', function () {
        let aktif = $(this);
        let satirID = aktif.closest("tr").attr('id');
        let dersAd = satirdakiDersAdiniGetirme(satirID);
        if (confirm(dersAd + ' Dersini Silmek İstediğinizden Emin Misiniz?')) {
            $(this).parent('td').parent('tr').remove();
            ganoHesaplaYazdir();
        }
    });

    $('#btn').click(function () {
        let kod = "Eklenen";
        let name = "";
        let id = $('#not_tablosu tr:last').attr('id');

        tabloyaDersEkle(kod, name, id + 1);
        alert("Yeni Ders Satırı Eklenmiştir");
        $("html, body").animate({scrollTop: $(document).height() - $(window).height()});//Scrolls to bottom.
    });

    $('#yenile').click(function () {
        location.reload();
    });

});
<|endoftext|>


<commit_before>/*
 *
 * {
 "course_code": "CBU 4401",
 "course_grade": "A",
 "course_name": "Girişimcilik"
 }

 {
 "course_code": "FIZ 1301",
 "course_ects": [
 5
 ]
 }

 * */

function notlarComboBoxOlustur(index) {
    let not_cb_html = '<select id="not' + index + '" class="form-control">' +
        '<option >Seçiniz</option>' +
        '<option value="4.0">AA</option>' +
        '<option value="3.5">BA</option>' +
        '<option value="3.0">BB</option>' +
        '<option value="2.5">CB</option>' +
        '<option value="2.0">CC</option>' +
        '<option value="1.5">DC</option>' +
        '<option value="1.0">DD</option>' +
        '<option value="0.5">FD</option>' +
        '<option value="0.0">FF</option>' +
        '</select>';
    return not_cb_html;
}

function kredilerComboBoxOlustur(index) {
    let kredi_cb_html = '<select id="kredi' + index + '" class="form-control"> ';
    for (i = 0; i < 30; i++) {
        kredi_cb_html += '<option value="' + (i + 1) + '">' + (i + 1) + '</option>';
    }
    kredi_cb_html += '</select>';

    return kredi_cb_html;
}

let VALID_GRADES = ["AA", "BA", "BB", "CB", "CC", "DC", "DD", "FD", "FF"];

chrome.storage.sync.get("parsed_courses", function (items) {

    $.getJSON("https://raw.githubusercontent.com/cankatabaci/ChromeEklenti-v1/master/src/course_ects.json", function (json) {
        let all_courses = json;
        let parsed_courses = items.parsed_courses;

        // TODO: 1. Loop through all parsed courses,  (done) add a row,
        //       2.  (done) Write course name inside "dersadi(n)" element
        //       3. Find course credit using course code from all_courses
        //       4. Select course credit (done) put inside "kredi(n)" element
        //       5. (done) Select course grade, (done) put insie "not(n)" element

        for (index = 0; index < parsed_courses.length; ++index) {

            if (VALID_GRADES.includes(parsed_courses[index].course_grade.toString()) || parsed_courses[index].course_grade.toString() === "A") {
                let course_name_html = '<input type="text" class="form-control col-sm-10" name="dersadi' + index + '" value="' + parsed_courses[index].course_name + '">';
                let course_credits_html = kredilerComboBoxOlustur(index);
                let course_grades_html = notlarComboBoxOlustur(index);

                $("#not_tablosu").find('tbody')
                    .append($('
')
                        .append($('').append(parsed_courses[index].course_code))
                        .append($('').append(course_name_html))
                        .append($('').append(course_credits_html))
                        .append($('').append(course_grades_html))
						.append($('').append('Sil'))
                    );

                $("#not" + index + " option").filter(function () { // selecting options based on its text
                    return $(this).text() === parsed_courses[index].course_grade;
                }).prop("selected", true);
            } else {
                console.log(parsed_courses[index].course_grade);
            }

        }

    });
});

	$(document).ready(function() {
		$('#not_tablosu').on('click','.silinicekSatir', function (){
			if (confirm('Dersi Silmek İstediğinizden Emin Misiniz?')){
			$(this).parent('td').parent('tr').remove();
			}
		});
	});  <commit_msg>Course credits added automatically<commit_after>/*
 *
 * {
 "course_code": "CBU 4401",
 "course_grade": "A",
 "course_name": "Girişimcilik"
 }

 {
 "course_code": "FIZ 1301",
 "course_ects": [
 5
 ]
 }

 * */

function notlarComboBoxOlustur(index) {
    let not_cb_html = '<select id="not' + index + '" class="form-control">' +
        '<option >Seçiniz</option>' +
        '<option value="4.0">AA</option>' +
        '<option value="3.5">BA</option>' +
        '<option value="3.0">BB</option>' +
        '<option value="2.5">CB</option>' +
        '<option value="2.0">CC</option>' +
        '<option value="1.5">DC</option>' +
        '<option value="1.0">DD</option>' +
        '<option value="0.5">FD</option>' +
        '<option value="0.0">FF</option>' +
        '</select>';
    return not_cb_html;
}

function kredilerComboBoxOlustur(index) {
    let kredi_cb_html = '<select id="kredi' + index + '" class="form-control"> ';
    for (i = 0; i < 30; i++) {
        kredi_cb_html += '<option value="' + (i + 1) + '">' + (i + 1) + '</option>';
    }
    kredi_cb_html += '</select>';

    return kredi_cb_html;
}

function dersKredisiniGetir(all_courses, course_code) {
    let course = all_courses.find(function (course) {
        return course.course_code === course_code;
    });
    if (course) {
        console.log("course ects");
        console.log(course.course_ects[0]);
    } else {
        console.log("course code");
        console.log(course_code);
    }

    return course.course_ects[0];
}

let VALID_GRADES = ["AA", "BA", "BB", "CB", "CC", "DC", "DD", "FD", "FF"];

chrome.storage.sync.get("parsed_courses", function (items) {

    $.getJSON("https://raw.githubusercontent.com/cankatabaci/ChromeEklenti-v1/master/src/course_ects.json", function (json) {
        let all_courses = json;
        let parsed_courses = items.parsed_courses;

        // TODO: 1. Loop through all parsed courses,  (done) add a row,
        //       2.  (done) Write course name inside "dersadi(n)" element
        //       3. Find course credit using course code from all_courses
        //       4. Select course credit (done) put inside "kredi(n)" element
        //       5. (done) Select course grade, (done) put insie "not(n)" element

        for (index = 0; index < parsed_courses.length; ++index) {

            if (VALID_GRADES.includes(parsed_courses[index].course_grade.toString()) || parsed_courses[index].course_grade.toString() === "A") {
                let course_name_html = '<input type="text" class="form-control col-sm-10" name="dersadi' + index + '" value="' + parsed_courses[index].course_name + '">';
                let course_credits_html = kredilerComboBoxOlustur(index);
                let course_grades_html = notlarComboBoxOlustur(index);
                let course_credit = dersKredisiniGetir(all_courses, parsed_courses[index].course_code);

                console.log("course_credit");
                console.log(course_credit);

                $("#not_tablosu").find('tbody')
                    .append($('
')
                        .append($('').append(parsed_courses[index].course_code))
                        .append($('').append(course_name_html))
                        .append($('').append(course_credits_html))
                        .append($('').append(course_grades_html))
						.append($('').append('Sil'))
                    );

                $("#not" + index + " option").filter(function () { // selecting grade options based on its text
                    return $(this).text() === parsed_courses[index].course_grade;
                }).prop("selected", true);

                $("#kredi" + index + " option").filter(function () { // selecting credits options based on its text
                    return $(this).text() === course_credit.toString();
                }).prop("selected", true);

            } else {
                console.log(parsed_courses[index].course_grade);
            }
        }

    });
});

	$(document).ready(function() {
		$('#not_tablosu').on('click','.silinicekSatir', function (){
			if (confirm('Dersi Silmek İstediğinizden Emin Misiniz?')){
			$(this).parent('td').parent('tr').remove();
			}
		});
	});  <|endoftext|>


<commit_before>var hasLS = !!window.localStorage;

export default ['youtubePlayer', 'youtubeAPI', 'playListVolume', '$rootScope', function(ytPlayer, ytAPI, playListVolume, $rootScope) {
    var nowPlaying = null,
        st = {
            UNKNOWN: -1,
            INITIAL: 0,
            PLAYING: 1,
            PAUSING: 2,
            STOPPED: 3,
            BUFFERING: 4
        },
        state = st.INITIAL,
        currentTime = 0,
        that = this;

    this.playlist = getSavedList();
    this.st = st;

    $rootScope.$on('youtubePlayer:infoDelivery', function(e, data) {
        if (data.info.hasOwnProperty('currentTime')) {
            currentTime = data.info.currentTime;
        }
    });
    $rootScope.$on('youtubePlayer:onStateChange', function(e, data) {
        var currentItem,
            stopAt,
            playNext;
        if (data.info === YT.PlayerState.PLAYING) {
            state = st.PLAYING;
            setNowPlaying(nowPlaying);
        }
        if (data.info === YT.PlayerState.PAUSED) {
            state = st.PAUSING;
            setNowPlaying(false);
        }
        if (data.info === YT.PlayerState.ENDED) {
            state = st.STOPPED;
            currentItem = that.getNowPlaying();
            stopAt = getStopAt();
            playNext = getPlayNext();

            if (currentItem.repeatTrack)
                that.play(nowPlaying);

            else if (typeof playNext === 'number') {
                that.play(playNext);
                that.playlist[playNext].playNext = false;
            } else if (stopAt === nowPlaying) {
                setNowPlaying(null);
                currentItem.stopHere = false;
            } else if (that.hasNext())
                that.next();

            else
                setNowPlaying(null);
        }
        if (data.info === YT.PlayerState.BUFFERING) {
            state = st.BUFFERING;
        }
        $rootScope.$broadcast('playList:stateChanged', state);
    });

    // Register keyboard sortcuts
    document.addEventListener('keyup', function(e) {
        var actions = {
            // Space
            32: function() {
                that.togglePlay();
            },
            // Left Arrow
            37: function() {
                var seekTo = currentTime - 5 >= 0 ?
                    currentTime - 5 :
                    0;
                ytPlayer.seek(seekTo);
            },
            // Right Arrow
            39: function() {
                ytPlayer.seek(currentTime + 5);
            }
        };

        if (e.target.tagName.toLowerCase() !== 'input' &&
            actions.hasOwnProperty(e.keyCode)) {
            e.preventDefault();
            actions[e.keyCode]();
        }
    });

    function getSavedList() {
        var list = [],
            lsVal;
        if (hasLS) {
            lsVal = localStorage.playlist;
            if (lsVal) list = JSON.parse(lsVal);
        }

        return list;
    }

    function setNowPlaying(idx) {
        var endingSound;
        if (typeof idx === 'number')
            nowPlaying = idx;
        else if (idx === null) {
            nowPlaying = null;
            $rootScope.$broadcast('toast::notify', {
                text: 'The playlist has ended.'
            });
            endingSound = new Audio('js/assets/indian-bell-chime.wav');
            endingSound.volume = playListVolume.get() / 100;
            endingSound.play();
        }

    }

    function getPlayNext() {
        var idx;
        that.playlist.forEach(function(item, i) {
            if (item.playNext)
                idx = i;
        });
        return idx;
    }

    function getStopAt() {
        var idx;
        that.playlist.forEach(function(item, i) {
            if (item.stopHere)
                idx = i;
        });
        return idx;
    }

    this.saveList = function(name) {
        if (hasLS) {
            if (typeof name !== 'string')
                name = 'playlist';
            localStorage[name] = JSON.stringify(that.playlist);
        }
    };

    this.clearList = function() {
        this.stop();
        this.playlist.length = 0;
        this.saveList();
    };

    this.addItem = function(idx, item) {
        that.playlist.splice(idx, 0, item);
        this.saveList();
    };

    this.removeItem = function(idx) {
        that.playlist.splice(idx, 1);

        // Fix the 'nowPlaying' var, if necessary
        if (idx < nowPlaying) {
            nowPlaying -= 1;
        }

        this.saveList();
    };

    this.getState = function() {
        return state;
    };

    this.save = function() {
        this.saveList();
    };

    this.setNowPlaying = function(idx) {
        return setNowPlaying(idx);
    };

    this.getNowPlaying = function() {
        return that.playlist[nowPlaying];
    };

    this.getNowPlayingIdx = function() {
        return nowPlaying;
    };

    this.add = function(videoId, idx) {
        var that = this;

        ytAPI.getVideo(videoId).then(function(resp) {
            var item = resp.data.items[0],
                thumb = item.snippet.thumbnails.default.url,
                title = item.snippet.title,
                trimmed = title.length >= 30 ? title.substr(0, 27) + '...' :
                title,
                text = 'Track "' + trimmed + '" has been added to playlist';

            that.addItem(idx, item);
            if (that.playlist.length === 1 ||
                (idx === that.playlist.length - 1 && state === st.STOPPED))
                that.play(idx);

            $rootScope.$broadcast('toast::notify', {
                thumb: thumb,
                text: text
            });
        });
    };

    this.addFirst = function(videoId) {
        this.add(videoId, 0);
    };

    this.addLast = function(videoId) {
        this.add(videoId, this.playlist.length);
    };

    this.remove = function(idx) {
        var fixPlay = (idx === nowPlaying),
            isLast = (idx === this.playlist.length - 1);
        this.removeItem(idx);

        if (fixPlay) {
            if (isLast) {
                this.stop();
            } else {
                this.play(idx, true);
            }
        } else
            this.play();
    };

    this.togglePlay = function() {
        if (state === st.PLAYING) this.pause();
        else this.play();
    };

    this.play = function(index, force) {
        var idx = typeof index === 'number' ? index : (nowPlaying || 0),
            videoId = this.playlist[idx].id;

        if (idx === nowPlaying && !force) {
            return ytPlayer.play();
        } else {
            return ytPlayer.loadVideo(videoId).then(function() {
                ytPlayer.play();
                setNowPlaying(idx);
            });
        }
    };

    this.pause = function() {
        ytPlayer.pause();
        //setNowPlaying(false);
    };

    this.stop = function() {
        ytPlayer.seek(0);
        ytPlayer.stop();
        setNowPlaying(null);
    };

    this.next = function() {
        if (this.hasNext())
            this.play(nowPlaying + 1);
    };

    this.hasNext = function() {
        return nowPlaying < this.playlist.length - 1;
    };

    this.prev = function() {
        if (nowPlaying !== 0)
            this.play(nowPlaying - 1);
    };

    this.playNext = function(idx) {
        var that = this;
        that.playlist.forEach(function(item) {
            item.playNext = false;
        });
        if (typeof idx === 'number')
            that.playlist[idx].playNext = true;

        this.saveList();
    };

    this.stopAt = function(idx) {
        var that = this;
        that.playlist.forEach(function(item) {
            item.stopHere = false;
        });
        if (typeof idx === 'number')
            that.playlist[idx].stopHere = true;

        this.saveList();
    };

    this.repeatTrack = function(idx) {
        var that = this;
        that.playlist.forEach(function(item) {
            item.repeatTrack = false;
        });
        if (typeof idx === 'number')
            that.playlist[idx].repeatTrack = true;

        this.saveList();
    };
}];
<commit_msg>Fix the issue where calling clearList before track is played throws error<commit_after>var hasLS = !!window.localStorage;

export default ['youtubePlayer', 'youtubeAPI', 'playListVolume', '$rootScope', function(ytPlayer, ytAPI, playListVolume, $rootScope) {
    var nowPlaying = null,
        st = {
            UNKNOWN: -1,
            INITIAL: 0,
            PLAYING: 1,
            PAUSING: 2,
            STOPPED: 3,
            BUFFERING: 4
        },
        state = st.INITIAL,
        currentTime = 0,
        that = this;

    this.playlist = getSavedList();
    this.st = st;

    $rootScope.$on('youtubePlayer:infoDelivery', function(e, data) {
        if (data.info.hasOwnProperty('currentTime')) {
            currentTime = data.info.currentTime;
        }
    });
    $rootScope.$on('youtubePlayer:onStateChange', function(e, data) {
        var currentItem,
            stopAt,
            playNext;
        if (data.info === YT.PlayerState.PLAYING) {
            state = st.PLAYING;
            setNowPlaying(nowPlaying);
        }
        if (data.info === YT.PlayerState.PAUSED) {
            state = st.PAUSING;
            setNowPlaying(false);
        }
        if (data.info === YT.PlayerState.ENDED) {
            state = st.STOPPED;
            currentItem = that.getNowPlaying();
            stopAt = getStopAt();
            playNext = getPlayNext();

            if (currentItem.repeatTrack)
                that.play(nowPlaying);

            else if (typeof playNext === 'number') {
                that.play(playNext);
                that.playlist[playNext].playNext = false;
            } else if (stopAt === nowPlaying) {
                setNowPlaying(null);
                currentItem.stopHere = false;
            } else if (that.hasNext())
                that.next();

            else
                setNowPlaying(null);
        }
        if (data.info === YT.PlayerState.BUFFERING) {
            state = st.BUFFERING;
        }
        $rootScope.$broadcast('playList:stateChanged', state);
    });

    // Register keyboard sortcuts
    document.addEventListener('keyup', function(e) {
        var actions = {
            // Space
            32: function() {
                that.togglePlay();
            },
            // Left Arrow
            37: function() {
                var seekTo = currentTime - 5 >= 0 ?
                    currentTime - 5 :
                    0;
                ytPlayer.seek(seekTo);
            },
            // Right Arrow
            39: function() {
                ytPlayer.seek(currentTime + 5);
            }
        };

        if (e.target.tagName.toLowerCase() !== 'input' &&
            actions.hasOwnProperty(e.keyCode)) {
            e.preventDefault();
            actions[e.keyCode]();
        }
    });

    function getSavedList() {
        var list = [],
            lsVal;
        if (hasLS) {
            lsVal = localStorage.playlist;
            if (lsVal) list = JSON.parse(lsVal);
        }

        return list;
    }

    function setNowPlaying(idx) {
        var endingSound;
        if (typeof idx === 'number')
            nowPlaying = idx;
        else if (idx === null) {
            nowPlaying = null;
            $rootScope.$broadcast('toast::notify', {
                text: 'The playlist has ended.'
            });
            endingSound = new Audio('js/assets/indian-bell-chime.wav');
            endingSound.volume = playListVolume.get() / 100;
            endingSound.play();
        }

    }

    function getPlayNext() {
        var idx;
        that.playlist.forEach(function(item, i) {
            if (item.playNext)
                idx = i;
        });
        return idx;
    }

    function getStopAt() {
        var idx;
        that.playlist.forEach(function(item, i) {
            if (item.stopHere)
                idx = i;
        });
        return idx;
    }

    this.saveList = function(name) {
        if (hasLS) {
            if (typeof name !== 'string')
                name = 'playlist';
            localStorage[name] = JSON.stringify(that.playlist);
        }
    };

    this.clearList = function() {
        if (state !== st.INITIAL) this.stop();

        this.playlist.length = 0;
        this.saveList();
    };

    this.addItem = function(idx, item) {
        that.playlist.splice(idx, 0, item);
        this.saveList();
    };

    this.removeItem = function(idx) {
        that.playlist.splice(idx, 1);

        // Fix the 'nowPlaying' var, if necessary
        if (idx < nowPlaying) {
            nowPlaying -= 1;
        }

        this.saveList();
    };

    this.getState = function() {
        return state;
    };

    this.save = function() {
        this.saveList();
    };

    this.setNowPlaying = function(idx) {
        return setNowPlaying(idx);
    };

    this.getNowPlaying = function() {
        return that.playlist[nowPlaying];
    };

    this.getNowPlayingIdx = function() {
        return nowPlaying;
    };

    this.add = function(videoId, idx) {
        var that = this;

        ytAPI.getVideo(videoId).then(function(resp) {
            var item = resp.data.items[0],
                thumb = item.snippet.thumbnails.default.url,
                title = item.snippet.title,
                trimmed = title.length >= 30 ? title.substr(0, 27) + '...' :
                title,
                text = 'Track "' + trimmed + '" has been added to playlist';

            that.addItem(idx, item);
            if (that.playlist.length === 1 ||
                (idx === that.playlist.length - 1 && state === st.STOPPED))
                that.play(idx);

            $rootScope.$broadcast('toast::notify', {
                thumb: thumb,
                text: text
            });
        });
    };

    this.addFirst = function(videoId) {
        this.add(videoId, 0);
    };

    this.addLast = function(videoId) {
        this.add(videoId, this.playlist.length);
    };

    this.remove = function(idx) {
        var fixPlay = (idx === nowPlaying),
            isLast = (idx === this.playlist.length - 1);
        this.removeItem(idx);

        if (fixPlay) {
            if (isLast) {
                this.stop();
            } else {
                this.play(idx, true);
            }
        } else
            this.play();
    };

    this.togglePlay = function() {
        if (state === st.PLAYING) this.pause();
        else this.play();
    };

    this.play = function(index, force) {
        var idx = typeof index === 'number' ? index : (nowPlaying || 0),
            videoId = this.playlist[idx].id;

        if (idx === nowPlaying && !force) {
            return ytPlayer.play();
        } else {
            return ytPlayer.loadVideo(videoId).then(function() {
                ytPlayer.play();
                setNowPlaying(idx);
            });
        }
    };

    this.pause = function() {
        ytPlayer.pause();
        //setNowPlaying(false);
    };

    this.stop = function() {
        ytPlayer.seek(0);
        ytPlayer.stop();
        setNowPlaying(null);
    };

    this.next = function() {
        if (this.hasNext())
            this.play(nowPlaying + 1);
    };

    this.hasNext = function() {
        return nowPlaying < this.playlist.length - 1;
    };

    this.prev = function() {
        if (nowPlaying !== 0)
            this.play(nowPlaying - 1);
    };

    this.playNext = function(idx) {
        var that = this;
        that.playlist.forEach(function(item) {
            item.playNext = false;
        });
        if (typeof idx === 'number')
            that.playlist[idx].playNext = true;

        this.saveList();
    };

    this.stopAt = function(idx) {
        var that = this;
        that.playlist.forEach(function(item) {
            item.stopHere = false;
        });
        if (typeof idx === 'number')
            that.playlist[idx].stopHere = true;

        this.saveList();
    };

    this.repeatTrack = function(idx) {
        var that = this;
        that.playlist.forEach(function(item) {
            item.repeatTrack = false;
        });
        if (typeof idx === 'number')
            that.playlist[idx].repeatTrack = true;

        this.saveList();
    };
}];
<|endoftext|>


<commit_before>"use strict";

// SCHEMA
//    jid: 'string',
//    ver: 'string'

function RosterVerStorage(storage) {
    this.storage = storage;
}

RosterVerStorage.prototype = {
    constructor: {
        value: RosterVerStorage
    },
    setup: function (db) {
        if (db.objectStoreNames.contains('rosterver')) {
            db.deleteObjectStore('rosterver');
        }
        db.createObjectStore('rosterver', {
            keyPath: 'jid'
        });
    },
    transaction: function (mode) {
        var trans = this.storage.db.transaction('rosterver', mode);
        return trans.objectStore('rosterver');
    },
    set: function (jid, ver, cb) {
        cb = cb || function () {};
        var data = {
            jid: jid,
            ver: ver
        };
        var request = this.transaction('readwrite').put(data);
        request.onsuccess = function () {
            cb(false, data);
        };
        request.onerror = cb;
    },
    get: function (jid, cb) {
        cb = cb || function () {};
        if (!jid) {
            return cb('not-found');
        }
        var request = this.transaction('readonly').get(jid);
        request.onsuccess = function (e) {
            var res = request.result;
            if (res === undefined) {
                return cb('not-found');
            }
            cb(false, request.result);
        };
        request.onerror = cb;
    },
    remove: function (jid, cb) {
        cb = cb || function () {};
        var request = this.transaction('readwrite')['delete'](id);
        request.onsuccess = function (e) {
            cb(false, request.result);
        };
        request.onerror = cb;
    }
};

module.exports = RosterVerStorage;
<commit_msg>fix typo in contact deletion<commit_after>"use strict";

// SCHEMA
//    jid: 'string',
//    ver: 'string'

function RosterVerStorage(storage) {
    this.storage = storage;
}

RosterVerStorage.prototype = {
    constructor: {
        value: RosterVerStorage
    },
    setup: function (db) {
        if (db.objectStoreNames.contains('rosterver')) {
            db.deleteObjectStore('rosterver');
        }
        db.createObjectStore('rosterver', {
            keyPath: 'jid'
        });
    },
    transaction: function (mode) {
        var trans = this.storage.db.transaction('rosterver', mode);
        return trans.objectStore('rosterver');
    },
    set: function (jid, ver, cb) {
        cb = cb || function () {};
        var data = {
            jid: jid,
            ver: ver
        };
        var request = this.transaction('readwrite').put(data);
        request.onsuccess = function () {
            cb(false, data);
        };
        request.onerror = cb;
    },
    get: function (jid, cb) {
        cb = cb || function () {};
        if (!jid) {
            return cb('not-found');
        }
        var request = this.transaction('readonly').get(jid);
        request.onsuccess = function (e) {
            var res = request.result;
            if (res === undefined) {
                return cb('not-found');
            }
            cb(false, request.result);
        };
        request.onerror = cb;
    },
    remove: function (jid, cb) {
        cb = cb || function () {};
        var request = this.transaction('readwrite')['delete'](jid);
        request.onsuccess = function (e) {
            cb(false, request.result);
        };
        request.onerror = cb;
    }
};

module.exports = RosterVerStorage;
<|endoftext|>


<commit_before>/*global require, module*/
var InvalidArgumentError = require("../error/invalid-argument-error"),
    easyGid = require("easy-guid"),
    validator = require('validator'),
    _ = require("lodash"),
    settings = require("./settings-manager");

var TimeEntry = function (issueId, issueName, projectName, taskUrl) {
    "use strict";
    if (!validator.isInt(issueId)) {
        throw new InvalidArgumentError("Parameter issueId must be an integer.");
    }

    if (typeof issueName !== "string") {
        throw new InvalidArgumentError("Parameter issueName must be a string.");
    }

    if (typeof projectName !== "string") {
        throw new InvalidArgumentError("Parameter projectName must be a string.");
    }

    if (!validator.isURL(taskUrl)) {
        throw new InvalidArgumentError("Parameter taskUrl must be a URL.");
    }

    this.id = easyGid.new();
    this.issueId = issueId;
    this.issueName = issueName;
    this.projectName = projectName;
    this.taskUrl = taskUrl;
    this.spentOn = null;
    this.hours = null;
    this.activityId = null;
    this.comments = null;
    this.updated = false;
    this.customFields = _.cloneDeep(settings.customFields);
};

TimeEntry.prototype = (function () {
    "use strict";
    var dateFormat = "YYYY-MM-DD",
        setCustomField = function (id, value) {
            var field = _.find(this.customFields, { 'id': id });
            if (field) {
                field.value = value;
            }

            this.updated = isUpdated.call(this);
            return this;
        },
        setSpentOn = function (spentOn) {
            if (!spentOn || !spentOn._isAMomentObject) {
                throw new InvalidArgumentError("Parameter spentOn must be a moment object.");
            }

            this.spentOn = spentOn;
            return this;
        },
        isUpdated  = function () {
            var index = 0,
                length = this.customFields.length,
                field;

            for (index; length > index; index++) {
                field = this.customFields[index];
                if (field.required && (field.value === "" || field.value === null || field.value === "undefined")) {
                    return false;
                }
            }

            return this.activityId !== null && this.hours !== null;
        },
        setHours = function (hours) {
            if (!(validator.isInt(hours) || validator.isFloat(hours))) {
                this.updated = false;
                this.hours = null;
                return this;
            }

            this.hours = parseFloat(hours);
            if (this.hours <= 0) {
                this.hours = null;
                this.updated = false;
                return this;
            }

            this.updated = isUpdated.call(this);
            return this;
        },
        setActivityId = function (activityId) {
            if (!validator.isInt(activityId)) {
                this.updated = false;
                this.activityId = null;
                return this;
            }

            this.activityId = parseInt(activityId, 10);
            this.updated = isUpdated.call(this);
            return this;
        },
        setComments = function (comments) {
            this.comments = comments;
            return this;
        },
        clearTimeEntry = function () {
            this.spentOn = null;
            this.hours = null;
            this.activityId = null;
            this.comments = null;
            this.updated = false;
            this.customFields.map(function (field) {
                field.value = null;
            });
        },
        buildPostEntry = function () {
            var entry = {
                issue_id: this.issueId,
                spent_on: this.spentOn.format(dateFormat),
                hours: this.hours,
                activity_id: this.activityId,
                comments: this.comments
            };

            if (this.customFields.length) {
                entry.custom_fields = this.customFields;
            }

            return {
                time_entry: entry
            };
        };
    return {
        setCustomField: setCustomField,
        setHours: setHours,
        setActivityId: setActivityId,
        setComments: setComments,
        buildPostEntry: buildPostEntry,
        setSpentOn: setSpentOn,
        clearTimeEntry: clearTimeEntry
    };
}());

TimeEntry.createInstance = function (issueId, issueName, projectName, taskUrl) {
    "use strict";
    return new TimeEntry(issueId, issueName, projectName, taskUrl);
};

module.exports = TimeEntry;<commit_msg>Newly added tasks time entry gets updated without selecting the colour.Fix<commit_after>/*global require, module*/
var InvalidArgumentError = require("../error/invalid-argument-error"),
    easyGid = require("easy-guid"),
    validator = require('validator'),
    _ = require("lodash"),
    settings = require("./settings-manager");

var TimeEntry = function (issueId, issueName, projectName, taskUrl) {
    "use strict";
    if (!validator.isInt(issueId)) {
        throw new InvalidArgumentError("Parameter issueId must be an integer.");
    }

    if (typeof issueName !== "string") {
        throw new InvalidArgumentError("Parameter issueName must be a string.");
    }

    if (typeof projectName !== "string") {
        throw new InvalidArgumentError("Parameter projectName must be a string.");
    }

    if (!validator.isURL(taskUrl)) {
        throw new InvalidArgumentError("Parameter taskUrl must be a URL.");
    }

    this.id = easyGid.new();
    this.issueId = issueId;
    this.issueName = issueName;
    this.projectName = projectName;
    this.taskUrl = taskUrl;
    this.spentOn = null;
    this.hours = null;
    this.activityId = null;
    this.comments = null;
    this.updated = false;
    this.customFields = _.cloneDeep(settings.timeEntryCustomFieldData);
};

TimeEntry.prototype = (function () {
    "use strict";
    var dateFormat = "YYYY-MM-DD",
        setCustomField = function (id, value) {
            var field = _.find(this.customFields, { 'id': id });
            if (field) {
                field.value = value;
            }

            this.updated = isUpdated.call(this);
            return this;
        },
        setSpentOn = function (spentOn) {
            if (!spentOn || !spentOn._isAMomentObject) {
                throw new InvalidArgumentError("Parameter spentOn must be a moment object.");
            }

            this.spentOn = spentOn;
            return this;
        },
        isUpdated  = function () {
            debugger;
            var index = 0,
                length = this.customFields.length,
                field;

            for (index; length > index; index++) {
                field = this.customFields[index];
                if (field.required && (field.value === "" || field.value === null || typeof field.value === "undefined")) {
                    return false;
                }
            }

            return this.activityId !== null && this.hours !== null;
        },
        setHours = function (hours) {
            if (!(validator.isInt(hours) || validator.isFloat(hours))) {
                this.updated = false;
                this.hours = null;
                return this;
            }

            this.hours = parseFloat(hours);
            if (this.hours <= 0) {
                this.hours = null;
                this.updated = false;
                return this;
            }

            this.updated = isUpdated.call(this);
            return this;
        },
        setActivityId = function (activityId) {
            if (!validator.isInt(activityId)) {
                this.updated = false;
                this.activityId = null;
                return this;
            }

            this.activityId = parseInt(activityId, 10);
            this.updated = isUpdated.call(this);
            return this;
        },
        setComments = function (comments) {
            this.comments = comments;
            return this;
        },
        clearTimeEntry = function () {
            this.spentOn = null;
            this.hours = null;
            this.activityId = null;
            this.comments = null;
            this.updated = false;
            this.customFields.map(function (field) {
                field.value = null;
            });
        },
        buildPostEntry = function () {
            var entry = {
                issue_id: this.issueId,
                spent_on: this.spentOn.format(dateFormat),
                hours: this.hours,
                activity_id: this.activityId,
                comments: this.comments
            };

            if (this.customFields.length) {
                entry.custom_fields = this.customFields;
            }

            return {
                time_entry: entry
            };
        };
    return {
        setCustomField: setCustomField,
        setHours: setHours,
        setActivityId: setActivityId,
        setComments: setComments,
        buildPostEntry: buildPostEntry,
        setSpentOn: setSpentOn,
        clearTimeEntry: clearTimeEntry
    };
}());

TimeEntry.createInstance = function (issueId, issueName, projectName, taskUrl) {
    "use strict";
    return new TimeEntry(issueId, issueName, projectName, taskUrl);
};

module.exports = TimeEntry;<|endoftext|>


<commit_before>/*
Blockly generators for Gamefroot
*/

Blockly.JavaScript[ 'kiwi_game_open_url' ] = function( block ) {
  var value_url = Blockly.JavaScript.valueToCode(block, 'URL', Blockly.JavaScript.ORDER_ATOMIC);
  var code = '';

  code += '// Confirm that user wants to leave the site.\n';
  code += 'if ( !' + value_url + '.match( /^http[s]?:\\/\\//gi ) ) {\n';
  code += '  // User did not supply the protocol.\n';
  code += '  window.alert( "URL " + ' + value_url + ' + " missing protocol. Add \'http:\\/\\/\' or \'https:\\/\\/\' to the address and try again." );\n';
  code += '} else if (\n';
  code += '  ' + value_url + '.match( /^http[s]?:\\/\\/make\.gamefroot\\.com\\//gi ) ) {\n';
  code += '  // Site is on Gamefroot, and we regard it as safe.\n';
  code += '  window.open( ' + value_url + ' );\n';
  code += '} else if ( window.confirm(\n';
  code += '  "You are about to leave Gamefroot and go to " + ' + value_url + ' ) ) {\n';
  code += '  // Site is not on Gamefroot. We should confirm user intent.\n';
  code += '  window.open( ' + value_url + ' );\n';
  code += '}\n';

  return code;
};

// Does the instance exist?
Blockly.JavaScript[ "kiwi_instance_exists" ] = function( block ) {
  var value_inst = Blockly.Kiwifroot.valueToCode(
    block, 'INST', Blockly.Kiwifroot.ORDER_ATOMIC) || "(null)";
  var code = "( " + value_inst + " && " + value_inst + ".exists )";
  return [ code, Blockly.Kiwifroot.ORDER_ATOMIC ];
};

/*
Overrides for blocks already in the core.
*/

// Override clock type.
Blockly.Kiwifroot['kiwi_event_time'] = function(block) {

  var funcName = defineFunctionFromBranch('onTick', block, 'Executed after time period of time.');

  var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT) || 16;

  var constructorCode = errorCheck( this.workspace, ('!' + tick), '`Interval Time Event` block is missing a numeric value.' ) +
    'this.' + funcName + '_ = this.state.clocks.world.setInterval( function() { \n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'if( this.owner && this.owner.exists ) {\n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'this.' + funcName + '();\n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + '}\n' +
    Blockly.Kiwifroot.INDENT + '}, ' + tick + ', this);';

  var destructorCode = 'if( this.' + funcName + '_ ) this.' + funcName + '_.stop();\n';
  destructorCode += 'this.state.clocks.world.removeTimer( this.' + funcName + '_ );';

  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR,constructorCode);
  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  return null;
};

// Override clock type.
Blockly.Kiwifroot['kiwi_event_time_single'] = function(block) {

  var funcName = Blockly.Kiwifroot.variableDB_.getDistinctName('onSingleTick', Blockly.Procedures.NAME_TYPE);
  var branch = Blockly.Kiwifroot.statementToCode(block, 'STACK');

  var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT) || 16;

  var code = errorCheck( this.workspace, ('!' + tick), '`Single Time Control` block is missing a numeric value.' ) +
    'this.' + funcName + '_ = this.state.clocks.world.setTimeout( function() { \n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'if( this.owner && this.owner.exists ) {\n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + branch +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + '}\n' +
    Blockly.Kiwifroot.INDENT + '}, ' + tick + ', this);\n';

  var destructorCode = 'if( this.' + funcName + '_ ) this.' + funcName + '_.stop();\n';
  destructorCode += 'this.state.clocks.world.removeTimer( this.' + funcName + '_ );';
  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  return code;
};

// Override clock type.
Blockly.Kiwifroot[ "kiwi_scratch_events_wait" ] = function( block ) {

  // Functionality copied from `kiwi_event_time_single`,
  // except this takes seconds instead of millis.

  var funcName = Blockly.Kiwifroot.variableDB_.getDistinctName(
      "wait", Blockly.Procedures.NAME_TYPE );
  var branch = Blockly.Kiwifroot.statementToCode( block, "STACK" );
  var tick = Blockly.Kiwifroot.valueToCode(
    block, "SECS", Blockly.Kiwifroot.ORDER_ASSIGNMENT ) || 1;
  var code = "";
  var destructorCode = "";

  code += errorCheck(
      this.workspace,
      ( "!" + tick ),
      "`Wait` block is missing a numeric value." ) +
    "this." + funcName + "_ = " +
    "this.state.clocks.world.setTimeout( function() {\n" +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT +
    "if ( this.owner && this.owner.exists ) {\n" +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT +
    branch +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT +
    "}\n" +
    Blockly.Kiwifroot.INDENT + "}, " + tick + " * 1000, this );\n";

  destructorCode +=
    "if ( this." + funcName + "_ ) this." + funcName + "_.stop();\n" +
    "this.state.clocks.world.removeTimer( this." + funcName + "_ );";

  Blockly.Kiwifroot.provideAddition(
    Blockly.Kiwifroot.DESTRUCTOR, destructorCode );

  return code;
};

// Override camera offset not returning to zero.
//
// Shake the camera using offset values...
Blockly.Kiwifroot[ "kiwi_camera_shake_offset" ] = function( block ) {
  var code = "",
    cam = Blockly.Kiwifroot.camera.COMPONENT_PREFIX + ".offset",
    tab = Blockly.Kiwifroot.INDENT,
    trackerName = Blockly.Kiwifroot.variableDB_.getDistinctName(
      "tracker", Blockly.Variables.NAME_TYPE ),
    axis = block.getFieldValue( "AXIS" ),
    duration = Blockly.Kiwifroot.valueToCode(
      block,
      "DURATION",
      Blockly.Kiwifroot.ORDER_ATOMIC ) || 0,
    amplitude = Blockly.Kiwifroot.valueToCode(
      block,
      "AMPLITUDE",
      Blockly.Kiwifroot.ORDER_ATOMIC ) || 0;

  Blockly.Kiwifroot.camera.addCameraToConstructor_.call( this );

  // Create a tracker to control the amplitude.
  code += "var " + trackerName + " = { k: " + amplitude + " };\n";

  // Create tween.
  code += "game.tweens.create( " + trackerName + " ).to(\n";
  code += tab + "{ k: 0 },\n";
  code += tab + duration + " * 1000,\n";
  code += tab + "Kiwi.Animations.Tweens.Easing.Exponential.Out,\n";
  code += tab + "true )\n";
  code += ".onUpdate(\n";

  // Update camera offsets with tween progress.
  code += tab + "function() {\n";
  code += tab + tab + cam + "." + axis + " = " + "Math.round( " +
    trackerName + ".k * Math.sin( this.game.idealFrame ) );\n";
  code += tab + "}, this );\n";

  return code;
};

// Override buggy definition.
// The original version didn't check whether the `getGameSoundByID` call
// returned structured data, and could crash the whole game on compile
// if it was pointing at the wrong data - e.g. in a remix situation.
Blockly.Kiwifroot[ "kiwi_get_editor_sounds" ] = function ( block ) {
  var script;
  var code = null;
  var dropdownProp = block.getFieldValue( "PROP" );
  if ( typeof LevelEditor !== "undefined" && dropdownProp !== "none" ) {
    script = LevelEditor.getGameSoundByID( dropdownProp );
    if ( script ) {
      code =  script.id;
    }
  }

  return [ code, Blockly.Kiwifroot.ORDER_ATOMIC ];
};

// Override textfield creation to add anchor point defaults.
Blockly.Kiwifroot['kiwi_text_create'] = function(block) {

  var value_text = Blockly.Kiwifroot.valueToCode( block, 'TEXT', Blockly.Kiwifroot.ORDER_ATOMIC ) || "''";
  var variable0 = Blockly.Kiwifroot.variableDB_.getName( block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE );

  var t = Blockly.Kiwifroot.INDENT;
  var code  = 'this.' + variable0 + ' = this.state.objects.create( {\n';
  code += t + '"type": "multiline-text",\n';
  code += t + '"x": 0,\n';
  code += t + '"y": 0,\n';
  code += t + '"maxWidth": Infinity,\n';
  code += t + '"text": ' + value_text.replace(/\\\\n/g, "\\n") + '\n';
  code += '}, this.owner.parent, true);\n';
  code += "// Render text so width and height are defined."
  code += "this." + variable0 + ".renderText();\n";
  code += "this." + variable0 + ".anchorPointX = this.state.game.info.data.anchorDefault.x * this." + variable0 + ".width;\n";
  code += "this." + variable0 + ".anchorPointY = this.state.game.info.data.anchorDefault.y * this." + variable0 + ".height;\n";
  code += "\n";

  return code;
};
<commit_msg>Add stubs for Phaserfroot-only blocks. They will just throw an error if they are invoked.<commit_after>/*
Blockly generators for Gamefroot
*/

Blockly.JavaScript[ 'kiwi_game_open_url' ] = function( block ) {
  var value_url = Blockly.JavaScript.valueToCode(block, 'URL', Blockly.JavaScript.ORDER_ATOMIC);
  var code = '';

  code += '// Confirm that user wants to leave the site.\n';
  code += 'if ( !' + value_url + '.match( /^http[s]?:\\/\\//gi ) ) {\n';
  code += '  // User did not supply the protocol.\n';
  code += '  window.alert( "URL " + ' + value_url + ' + " missing protocol. Add \'http:\\/\\/\' or \'https:\\/\\/\' to the address and try again." );\n';
  code += '} else if (\n';
  code += '  ' + value_url + '.match( /^http[s]?:\\/\\/make\.gamefroot\\.com\\//gi ) ) {\n';
  code += '  // Site is on Gamefroot, and we regard it as safe.\n';
  code += '  window.open( ' + value_url + ' );\n';
  code += '} else if ( window.confirm(\n';
  code += '  "You are about to leave Gamefroot and go to " + ' + value_url + ' ) ) {\n';
  code += '  // Site is not on Gamefroot. We should confirm user intent.\n';
  code += '  window.open( ' + value_url + ' );\n';
  code += '}\n';

  return code;
};

// Does the instance exist?
Blockly.JavaScript[ "kiwi_instance_exists" ] = function( block ) {
  var value_inst = Blockly.Kiwifroot.valueToCode(
    block, 'INST', Blockly.Kiwifroot.ORDER_ATOMIC) || "(null)";
  var code = "( " + value_inst + " && " + value_inst + ".exists )";
  return [ code, Blockly.Kiwifroot.ORDER_ATOMIC ];
};

/*
Overrides for blocks already in the core.
*/

// Override clock type.
Blockly.Kiwifroot['kiwi_event_time'] = function(block) {

  var funcName = defineFunctionFromBranch('onTick', block, 'Executed after time period of time.');

  var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT) || 16;

  var constructorCode = errorCheck( this.workspace, ('!' + tick), '`Interval Time Event` block is missing a numeric value.' ) +
    'this.' + funcName + '_ = this.state.clocks.world.setInterval( function() { \n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'if( this.owner && this.owner.exists ) {\n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'this.' + funcName + '();\n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + '}\n' +
    Blockly.Kiwifroot.INDENT + '}, ' + tick + ', this);';

  var destructorCode = 'if( this.' + funcName + '_ ) this.' + funcName + '_.stop();\n';
  destructorCode += 'this.state.clocks.world.removeTimer( this.' + funcName + '_ );';

  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.CONSTRUCTOR,constructorCode);
  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  return null;
};

// Override clock type.
Blockly.Kiwifroot['kiwi_event_time_single'] = function(block) {

  var funcName = Blockly.Kiwifroot.variableDB_.getDistinctName('onSingleTick', Blockly.Procedures.NAME_TYPE);
  var branch = Blockly.Kiwifroot.statementToCode(block, 'STACK');

  var tick = Blockly.Kiwifroot.valueToCode(block, 'MILLISECOND', Blockly.Kiwifroot.ORDER_ASSIGNMENT) || 16;

  var code = errorCheck( this.workspace, ('!' + tick), '`Single Time Control` block is missing a numeric value.' ) +
    'this.' + funcName + '_ = this.state.clocks.world.setTimeout( function() { \n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + 'if( this.owner && this.owner.exists ) {\n' +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + branch +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT + '}\n' +
    Blockly.Kiwifroot.INDENT + '}, ' + tick + ', this);\n';

  var destructorCode = 'if( this.' + funcName + '_ ) this.' + funcName + '_.stop();\n';
  destructorCode += 'this.state.clocks.world.removeTimer( this.' + funcName + '_ );';
  Blockly.Kiwifroot.provideAddition(Blockly.Kiwifroot.DESTRUCTOR, destructorCode);

  return code;
};

// Override clock type.
Blockly.Kiwifroot[ "kiwi_scratch_events_wait" ] = function( block ) {

  // Functionality copied from `kiwi_event_time_single`,
  // except this takes seconds instead of millis.

  var funcName = Blockly.Kiwifroot.variableDB_.getDistinctName(
      "wait", Blockly.Procedures.NAME_TYPE );
  var branch = Blockly.Kiwifroot.statementToCode( block, "STACK" );
  var tick = Blockly.Kiwifroot.valueToCode(
    block, "SECS", Blockly.Kiwifroot.ORDER_ASSIGNMENT ) || 1;
  var code = "";
  var destructorCode = "";

  code += errorCheck(
      this.workspace,
      ( "!" + tick ),
      "`Wait` block is missing a numeric value." ) +
    "this." + funcName + "_ = " +
    "this.state.clocks.world.setTimeout( function() {\n" +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT +
    "if ( this.owner && this.owner.exists ) {\n" +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT +
    branch +
    Blockly.Kiwifroot.INDENT + Blockly.Kiwifroot.INDENT +
    "}\n" +
    Blockly.Kiwifroot.INDENT + "}, " + tick + " * 1000, this );\n";

  destructorCode +=
    "if ( this." + funcName + "_ ) this." + funcName + "_.stop();\n" +
    "this.state.clocks.world.removeTimer( this." + funcName + "_ );";

  Blockly.Kiwifroot.provideAddition(
    Blockly.Kiwifroot.DESTRUCTOR, destructorCode );

  return code;
};

// Override camera offset not returning to zero.
//
// Shake the camera using offset values...
Blockly.Kiwifroot[ "kiwi_camera_shake_offset" ] = function( block ) {
  var code = "",
    cam = Blockly.Kiwifroot.camera.COMPONENT_PREFIX + ".offset",
    tab = Blockly.Kiwifroot.INDENT,
    trackerName = Blockly.Kiwifroot.variableDB_.getDistinctName(
      "tracker", Blockly.Variables.NAME_TYPE ),
    axis = block.getFieldValue( "AXIS" ),
    duration = Blockly.Kiwifroot.valueToCode(
      block,
      "DURATION",
      Blockly.Kiwifroot.ORDER_ATOMIC ) || 0,
    amplitude = Blockly.Kiwifroot.valueToCode(
      block,
      "AMPLITUDE",
      Blockly.Kiwifroot.ORDER_ATOMIC ) || 0;

  Blockly.Kiwifroot.camera.addCameraToConstructor_.call( this );

  // Create a tracker to control the amplitude.
  code += "var " + trackerName + " = { k: " + amplitude + " };\n";

  // Create tween.
  code += "game.tweens.create( " + trackerName + " ).to(\n";
  code += tab + "{ k: 0 },\n";
  code += tab + duration + " * 1000,\n";
  code += tab + "Kiwi.Animations.Tweens.Easing.Exponential.Out,\n";
  code += tab + "true )\n";
  code += ".onUpdate(\n";

  // Update camera offsets with tween progress.
  code += tab + "function() {\n";
  code += tab + tab + cam + "." + axis + " = " + "Math.round( " +
    trackerName + ".k * Math.sin( this.game.idealFrame ) );\n";
  code += tab + "}, this );\n";

  return code;
};

// Override buggy definition.
// The original version didn't check whether the `getGameSoundByID` call
// returned structured data, and could crash the whole game on compile
// if it was pointing at the wrong data - e.g. in a remix situation.
Blockly.Kiwifroot[ "kiwi_get_editor_sounds" ] = function ( block ) {
  var script;
  var code = null;
  var dropdownProp = block.getFieldValue( "PROP" );
  if ( typeof LevelEditor !== "undefined" && dropdownProp !== "none" ) {
    script = LevelEditor.getGameSoundByID( dropdownProp );
    if ( script ) {
      code =  script.id;
    }
  }

  return [ code, Blockly.Kiwifroot.ORDER_ATOMIC ];
};

// Override textfield creation to add anchor point defaults.
Blockly.Kiwifroot['kiwi_text_create'] = function(block) {

  var value_text = Blockly.Kiwifroot.valueToCode( block, 'TEXT', Blockly.Kiwifroot.ORDER_ATOMIC ) || "''";
  var variable0 = Blockly.Kiwifroot.variableDB_.getName( block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE );

  var t = Blockly.Kiwifroot.INDENT;
  var code  = 'this.' + variable0 + ' = this.state.objects.create( {\n';
  code += t + '"type": "multiline-text",\n';
  code += t + '"x": 0,\n';
  code += t + '"y": 0,\n';
  code += t + '"maxWidth": Infinity,\n';
  code += t + '"text": ' + value_text.replace(/\\\\n/g, "\\n") + '\n';
  code += '}, this.owner.parent, true);\n';
  code += "// Render text so width and height are defined."
  code += "this." + variable0 + ".renderText();\n";
  code += "this." + variable0 + ".anchorPointX = this.state.game.info.data.anchorDefault.x * this." + variable0 + ".width;\n";
  code += "this." + variable0 + ".anchorPointY = this.state.game.info.data.anchorDefault.y * this." + variable0 + ".height;\n";
  code += "\n";

  return code;
};

// Phaserfroot-only generator stubs
Blockly.Kiwifroot[ "phaserfroot_create_video_element" ] = function( block ) {
  var msg = "`phaserfroot_create_video_element` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
Blockly.Kiwifroot[ "phaserfroot_create_particle_manager" ] = function( block ) {
  var msg = "`phaserfroot_create_particle_manager` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
Blockly.Kiwifroot[ "phaserfroot_create_set_blend" ] = function( block ) {
  var msg = "`phaserfroot_create_set_blend` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
Blockly.Kiwifroot[ "phaserfroot_create_set_numeric" ] = function( block ) {
  var msg = "`phaserfroot_create_set_numeric` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
Blockly.Kiwifroot[ "phaserfroot_camera_effects_extended" ] = function( block ) {
  var msg = "`phaserfroot_camera_effects_extended` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
Blockly.Kiwifroot[ "phaserfroot_camera_grayscale_filter" ] = function( block ) {
  var msg = "`phaserfroot_camera_grayscale_filter` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
Blockly.Kiwifroot[ "phaserfroot_camera_spotlight_filter" ] = function( block ) {
  var msg = "`phaserfroot_camera_spotlight_filter` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
Blockly.Kiwifroot[ "phaserfroot_camera_remove_filter" ] = function( block ) {
  var msg = "`phaserfroot_camera_remove_filter` block will only work in the Phaser engine. Please disable this block or switch to Phaser.";
  return "this.scene.game.reportError( " + msg + ", " + msg + ", \"SCRIPT ERROR\" );\n";
};
<|endoftext|>