<commit_before>
msos.provide('apps.ngdemos.start');

apps.ngdemos.start.css = new msos.loader();

// Load the page specific css (but after ./config.js loaded css)
apps.ngdemos.start.css.load('apps_ngdemos_css_demo', msos.resource_url('apps', 'ngdemos/css/demo.css'), 'css');

msos.onload_functions.push(
	function () {

		var temp_sd = 'apps.ngdemos.start';

		msos.console.debug(temp_sd + ' -> start.');

		apps.ngdemos.start = angular.module('apps.ngdemos.start', ['ngRoute']);

		// The basic technique below was derived from the example at:
		// http://www.bennadel.com/blog/2554-loading-angularjs-components-with-requirejs-after-application-bootstrap.htm
		apps.ngdemos.start.config(
			function($controllerProvider, $provide, $compileProvider) {

				var app = apps.ngdemos.start;

				// Let's keep the older references.
				app._controller = app.controller;
				app._service = app.service;
				app._factory = app.factory;
				app._value = app.value;
				app._directive = app.directive;

				// Provider-based controller.
				app.controller = function (name, constructor) {
					$controllerProvider.register( name, constructor );
					return (this);
				};

				// Provider-based service.
				app.service = function (name, constructor) {
					$provide.service(name, constructor);
					return (this);
				};

				// Provider-based factory.
				app.factory = function (name, factory) {
					$provide.factory( name, factory );
					return (this);
				};

				// Provider-based value.
				app.value = function (name, value) {
					$provide.value(name, value);
					return (this);
				};

				// Provider-based directive.
				app.directive = function (name, factory) {
					$compileProvider.directive( name, factory );
					return (this);
				};
			}
		);

		apps.ngdemos.start.factory(
			"get_template",
			function ($templateCache, $http) {

				function load_template(scpe, pge) {

					msos.console.debug(temp_sd + ' - get_template -> called: ' + pge.url);

					scpe.template = pge.url;

					$http(
						{
							method: 'GET',
							url: pge.url,
							cache: $templateCache
						}
					).success(
						function (html) {
							scpe.html = html;
							$('textarea').text(html);	// Had to go with this due to IE
						}
					).error(
						function (html, status) {
							scpe.html = 'Unable to load code: ' + status;
						}
					);
				}

				return load_template;
			}
		);

		apps.ngdemos.start.factory(
			"get_script",
			function ($rootScope, $q, get_template) {

				var deferred = $q.defer();

				function load_script(scpe, pge) {

					msos.console.debug(temp_sd + ' - get_script -> called: ' + pge.script);

					jQuery.ajax(
						{
							url: pge.script,
							dataType: "script",
							cache: true
						}
					).done(
						function () {
							msos.console.debug(temp_sd + ' - get_script -> loaded: ' + pge.script);

							// possibly should be -> $rootScope.$evalAsync(function () { ... });
							$rootScope.$apply(
								function () {
									deferred.resolve();
									get_template(scpe, pge);
								}
							);
						}
					).fail(
						function (jqxhr, settings, e) {
							msos.console.debug(temp_sd + ' - get_script -> error: ', e);

							// possibly should be -> $rootScope.$evalAsync(function () { ... });
							$rootScope.$apply(
								function () {
									deferred.reject(e);
								}
							);
						}
					);
				};

				return load_script;
			}
		);

        apps.ngdemos.start.controller(
            'samplesController',
            function ($scope, get_template, get_script) {

				var res_url = msos.resource_url;

				$scope.template = '';
                $scope.html = '';
                $scope.pages = [
                    {
                        title: 'Data Binding Basics',
                        url: res_url('apps', 'ngdemos/pages/1_basics.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Initialize Data',
                        url: res_url('apps', 'ngdemos/pages/2_init.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Looping with ng-repeat',
                        url: res_url('apps', 'ngdemos/pages/3_looping.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Adding a Simple Controller',
                        url: res_url('apps', 'ngdemos/pages/4_controller.html'),
						script: res_url('apps', 'ngdemos/scripts/4_controller.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Filtering and Sorting Data',
                        url: res_url('apps', 'ngdemos/pages/5_filtering.html'),
						script: res_url('apps', 'ngdemos/scripts/5_filtering.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Simple Application w/Filtering',
                        url: res_url('apps', 'ngdemos/pages/6_simple.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using ng-init and ng-repeat w/Objects',
                        url: res_url('apps', 'ngdemos/pages/7_objects.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using Multiple Controllers',
                        url: res_url('apps', 'ngdemos/pages/8_multiple.html'),
						script: res_url('apps', 'ngdemos/scripts/8_multiple.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using Select Element',
                        url: res_url('apps', 'ngdemos/pages/9_select.html'),
						script: res_url('apps', 'ngdemos/scripts/9_select.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using Dropdown Menu',
                        url: res_url('apps', 'ngdemos/pages/10_dropdown.html'),
						script: res_url('apps', 'ngdemos/scripts/10_dropdown.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'MSOS-AngularJS, Ultra Simple',
                        url: '',
                        href: 'simple.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MSOS-AngularJS, Simple Routing',
                        url: '',
                        href: 'route.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MSOS-AngularJS, Simple Script Injection',
                        url: '',
                        href: 'script.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MSOS-AngularJS, Switchable Grid',
                        url: '',
                        href: 'switchable_grid.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'MSOS-AngularJS w/Std. Bootstrap-UI',
                        url: '',
                        href: 'bootstrap.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'MSOS-AngularJS, w/Lazy Loading Modular Bootstrap-UI',
                        url: '',
                        href: 'bootstrap2.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'Localstorage Module',
                        url: '',
                        href: 'localstorage.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'MobileSiteOS Culture Loading',
                        url: '',
                        href: 'culture.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'Customer Invoicing App',
                        url: '',
                        href: 'invoicing.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'Customer Management App',
                        url: '',
                        href: 'customer.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'Advanced Customer Mgt. App',
                        url: '',
                        href: 'customer2.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MongoLab Resource App',
                        url: '',
                        href: 'mongolab.html',
						icon: 'fa-external-link'
                    }
                ];

                $scope.loadPage = function (page) {

                    if (page.href) {
                        document.location = page.href;	// Load new page
                    }

					if (page.script)	{ get_script($scope, page); }
					else				{ get_template($scope, page); }
                }
            }
        );

		msos.console.debug(temp_sd + ' -> done!');
	}
);

msos.onload_func_done.push(
	function () {
		angular.bootstrap('body', ['apps.ngdemos.start']);
	}
);<commit_msg>Add AngularJS Mobile-UI link<commit_after>
msos.provide('apps.ngdemos.start');

apps.ngdemos.start.css = new msos.loader();

// Load the page specific css (but after ./config.js loaded css)
apps.ngdemos.start.css.load('apps_ngdemos_css_demo', msos.resource_url('apps', 'ngdemos/css/demo.css'), 'css');

msos.onload_functions.push(
	function () {

		var temp_sd = 'apps.ngdemos.start';

		msos.console.debug(temp_sd + ' -> start.');

		apps.ngdemos.start = angular.module('apps.ngdemos.start', ['ngRoute']);

		// The basic technique below was derived from the example at:
		// http://www.bennadel.com/blog/2554-loading-angularjs-components-with-requirejs-after-application-bootstrap.htm
		apps.ngdemos.start.config(
			function($controllerProvider, $provide, $compileProvider) {

				var app = apps.ngdemos.start;

				// Let's keep the older references.
				app._controller = app.controller;
				app._service = app.service;
				app._factory = app.factory;
				app._value = app.value;
				app._directive = app.directive;

				// Provider-based controller.
				app.controller = function (name, constructor) {
					$controllerProvider.register( name, constructor );
					return (this);
				};

				// Provider-based service.
				app.service = function (name, constructor) {
					$provide.service(name, constructor);
					return (this);
				};

				// Provider-based factory.
				app.factory = function (name, factory) {
					$provide.factory( name, factory );
					return (this);
				};

				// Provider-based value.
				app.value = function (name, value) {
					$provide.value(name, value);
					return (this);
				};

				// Provider-based directive.
				app.directive = function (name, factory) {
					$compileProvider.directive( name, factory );
					return (this);
				};
			}
		);

		apps.ngdemos.start.factory(
			"get_template",
			function ($templateCache, $http) {

				function load_template(scpe, pge) {

					msos.console.debug(temp_sd + ' - get_template -> called: ' + pge.url);

					scpe.template = pge.url;

					$http(
						{
							method: 'GET',
							url: pge.url,
							cache: $templateCache
						}
					).success(
						function (html) {
							scpe.html = html;
							$('textarea').text(html);	// Had to go with this due to IE
						}
					).error(
						function (html, status) {
							scpe.html = 'Unable to load code: ' + status;
						}
					);
				}

				return load_template;
			}
		);

		apps.ngdemos.start.factory(
			"get_script",
			function ($rootScope, $q, get_template) {

				var deferred = $q.defer();

				function load_script(scpe, pge) {

					msos.console.debug(temp_sd + ' - get_script -> called: ' + pge.script);

					jQuery.ajax(
						{
							url: pge.script,
							dataType: "script",
							cache: true
						}
					).done(
						function () {
							msos.console.debug(temp_sd + ' - get_script -> loaded: ' + pge.script);

							// possibly should be -> $rootScope.$evalAsync(function () { ... });
							$rootScope.$apply(
								function () {
									deferred.resolve();
									get_template(scpe, pge);
								}
							);
						}
					).fail(
						function (jqxhr, settings, e) {
							msos.console.debug(temp_sd + ' - get_script -> error: ', e);

							// possibly should be -> $rootScope.$evalAsync(function () { ... });
							$rootScope.$apply(
								function () {
									deferred.reject(e);
								}
							);
						}
					);
				};

				return load_script;
			}
		);

        apps.ngdemos.start.controller(
            'samplesController',
            function ($scope, get_template, get_script) {

				var res_url = msos.resource_url;

				$scope.template = '';
                $scope.html = '';
                $scope.pages = [
                    {
                        title: 'Data Binding Basics',
                        url: res_url('apps', 'ngdemos/pages/1_basics.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Initialize Data',
                        url: res_url('apps', 'ngdemos/pages/2_init.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Looping with ng-repeat',
                        url: res_url('apps', 'ngdemos/pages/3_looping.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Adding a Simple Controller',
                        url: res_url('apps', 'ngdemos/pages/4_controller.html'),
						script: res_url('apps', 'ngdemos/scripts/4_controller.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Filtering and Sorting Data',
                        url: res_url('apps', 'ngdemos/pages/5_filtering.html'),
						script: res_url('apps', 'ngdemos/scripts/5_filtering.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Simple Application w/Filtering',
                        url: res_url('apps', 'ngdemos/pages/6_simple.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using ng-init and ng-repeat w/Objects',
                        url: res_url('apps', 'ngdemos/pages/7_objects.html'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using Multiple Controllers',
                        url: res_url('apps', 'ngdemos/pages/8_multiple.html'),
						script: res_url('apps', 'ngdemos/scripts/8_multiple.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using Select Element',
                        url: res_url('apps', 'ngdemos/pages/9_select.html'),
						script: res_url('apps', 'ngdemos/scripts/9_select.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'Using Dropdown Menu',
                        url: res_url('apps', 'ngdemos/pages/10_dropdown.html'),
						script: res_url('apps', 'ngdemos/scripts/10_dropdown.js'),
						icon: 'fa-chevron-right'
                    },
                    {
                        title: 'MSOS-AngularJS, Ultra Simple',
                        url: '',
                        href: 'simple.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MSOS-AngularJS, Simple Routing',
                        url: '',
                        href: 'route.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MSOS-AngularJS, Simple Script Injection',
                        url: '',
                        href: 'script.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MSOS-AngularJS, Switchable Grid',
                        url: '',
                        href: 'switchable_grid.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'MSOS-AngularJS w/Std. Bootstrap-UI',
                        url: '',
                        href: 'bootstrap.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'MSOS-AngularJS, w/Lazy Loading Modular Bootstrap-UI',
                        url: '',
                        href: 'bootstrap2.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'MSOS-Mobile-AngularJS-UI, w/Lazy Loading Modules',
                        url: '',
                        href: '../angularjs_mobile/mobilesiteos.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'Localstorage Module',
                        url: '',
                        href: 'localstorage.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'MobileSiteOS Culture Loading',
                        url: '',
                        href: 'culture.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'Customer Invoicing App',
                        url: '',
                        href: 'invoicing.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'Customer Management App',
                        url: '',
                        href: 'customer.html',
						icon: 'fa-external-link'
                    },
					{
                        title: 'Advanced Customer Mgt. App',
                        url: '',
                        href: 'customer2.html',
						icon: 'fa-external-link'
                    },
                    {
                        title: 'MongoLab Resource App',
                        url: '',
                        href: 'mongolab.html',
						icon: 'fa-external-link'
                    }
                ];

                $scope.loadPage = function (page) {

                    if (page.href) {
                        document.location = page.href;	// Load new page
                    }

					if (page.script)	{ get_script($scope, page); }
					else				{ get_template($scope, page); }
                }
            }
        );

		msos.console.debug(temp_sd + ' -> done!');
	}
);

msos.onload_func_done.push(
	function () {
		angular.bootstrap('body', ['apps.ngdemos.start']);
	}
);<|endoftext|>


<commit_before>/**
 * ownCloud - owncollab_timetracker
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author andy <info@eventgineering.de>
 * @copyright andy 2016
 */

(function ($, OC) {

	$(document).ready(function () {
		$('#hello').click(function () {
			alert('Hello from your script file');
		});

		$('#echo').click(function () {
			var url = OC.generateUrl('/apps/owncollab_timetracker/echo');
			var data = {
				echo: $('#echo-content').val()
			};

			$.post(url, data).success(function (response) {
				$('#echo-result').text(response.echo);
			});

		});
	});

})(jQuery, OC);

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newEvent: $('#new-event-string').text()
};

// this events object holds all our events
var Events = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._events = [];
    this._activeEvent = undefined;
};

Events.prototype = {
    load: function (id) {
        var self = this;
        this._events.forEach(function (event) {
            if (event.id === id) {
                event.active = true;
                self._activeEvent = event;
            } else {
                event.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeEvent;
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeEvent.id;
        this._events.forEach(function (event, counter) {
            if (event.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active event if necessary
            if (this._activeEvent === this._events[index]) {
                delete this._activeEvent;
            }

            this._events.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (event) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(event)
        }).done(function (event) {
            self._events.push(event);
            self._activeEvent = event;
            self.load(event.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._events;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (events) {
            self._activeEvent = undefined;
            self._events = events;
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, start, end) {
        var event = this.getActive();
        event.title = title;
        event.content = content;
        event.start = start;
        event.end = end;

        return $.ajax({
            url: this._baseUrl + '/' + event.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(event)
        });
    }
};

// this will be the view that is used to update the html
var View = function (events) {
    this._events = events;
};

View.prototype = {
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({event: this._events.getActive()});

        $('#editor').html(html);

        // handle saves
        var textarea = $('#app-content textarea');
        var self = this;
        $('#app-content button').click(function () {
            if ($('#start').val()==''){
                var start = $('#start').attr('placeholder');
            }
            else{
                var start = $('#start').val();
            }
            if ($('#end').val()==''){
                var end = $('#end').attr('placeholder');
            }
            else{
                var end = $('#end').val();
            }
            if (textarea.val()==''){
                var content = textarea.attr('placeholder');
            }
            else{
                var content = textarea.val();
            }

            var title = content.split('\n')[0]; // first line is the title

            self._events.updateActive(title, content, start, end).done(function () {
                self.render();
            }).fail(function () {
                alert('Could not update event, not found');
            });
        });
    },
    renderNavigation: function () {
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({events: this._events.getAll()});

        $('#app-navigation ul').html(html);

        // create a new event
        var self = this;
        $('#new-event').click(function () {
            var event = {
                title: translations.newEvent,
                content: 'content here . . .',
		        start: '01.01.2016 00:00:00',
		        end: '01.01.2016 00:00:01'
            };

            self._events.create(event).done(function() {
                self.render();
                $('#editor textarea').focus();
            }).fail(function () {
                alert('Could not create event');
            });

        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a event
        $('#app-navigation .event .delete').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._events.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete event, not found');
            });
        });

        // load a event
        $('#app-navigation .event > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            self._events.load(id);
            self.render();
            $('#editor textarea').focus();

        });
    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var events = new Events(OC.generateUrl('/apps/owncollab_timetracker/events'));
var view = new View(events);
events.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load events');
});

});

})(OC, window, jQuery);
<commit_msg>test date<commit_after>/**
 * ownCloud - owncollab_timetracker
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author andy <info@eventgineering.de>
 * @copyright andy 2016
 */

(function ($, OC) {

	$(document).ready(function () {
		$('#hello').click(function () {
			alert('Hello from your script file');
		});

		$('#echo').click(function () {
			var url = OC.generateUrl('/apps/owncollab_timetracker/echo');
			var data = {
				echo: $('#echo-content').val()
			};

			$.post(url, data).success(function (response) {
				$('#echo-result').text(response.echo);
			});

		});
	});

})(jQuery, OC);

(function (OC, window, $, undefined) {
'use strict';

$(document).ready(function () {

var translations = {
    newEvent: $('#new-event-string').text()
};

// this events object holds all our events
var Events = function (baseUrl) {
    this._baseUrl = baseUrl;
    this._events = [];
    this._activeEvent = undefined;
};

Events.prototype = {
    load: function (id) {
        var self = this;
        this._events.forEach(function (event) {
            if (event.id === id) {
                event.active = true;
                self._activeEvent = event;
            } else {
                event.active = false;
            }
        });
    },
    getActive: function () {
        return this._activeEvent;
    },
    removeActive: function () {
        var index;
        var deferred = $.Deferred();
        var id = this._activeEvent.id;
        this._events.forEach(function (event, counter) {
            if (event.id === id) {
                index = counter;
            }
        });

        if (index !== undefined) {
            // delete cached active event if necessary
            if (this._activeEvent === this._events[index]) {
                delete this._activeEvent;
            }

            this._events.splice(index, 1);

            $.ajax({
                url: this._baseUrl + '/' + id,
                method: 'DELETE'
            }).done(function () {
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
        } else {
            deferred.reject();
        }
        return deferred.promise();
    },
    create: function (event) {
        var deferred = $.Deferred();
        var self = this;
        $.ajax({
            url: this._baseUrl,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(event)
        }).done(function (event) {
            self._events.push(event);
            self._activeEvent = event;
            self.load(event.id);
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    getAll: function () {
        return this._events;
    },
    loadAll: function () {
        var deferred = $.Deferred();
        var self = this;
        $.get(this._baseUrl).done(function (events) {
            self._activeEvent = undefined;
            self._events = events;
            deferred.resolve();
        }).fail(function () {
            deferred.reject();
        });
        return deferred.promise();
    },
    updateActive: function (title, content, start, end) {
        var event = this.getActive();
        event.title = title;
        event.content = content;
        event.start = start;
        event.end = end;

        return $.ajax({
            url: this._baseUrl + '/' + event.id,
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(event)
        });
    }
};

// this will be the view that is used to update the html
var View = function (events) {
    this._events = events;
};

View.prototype = {
    renderContent: function () {
        var source = $('#content-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({event: this._events.getActive()});

        $('#editor').html(html);

        // handle saves
        var textarea = $('#app-content textarea');
        var self = this;
        $('#app-content button').click(function () {
            if ($('#start').val()==''){
                var start = $('#start').attr('placeholder');
            }
            else{
                var start = $('#start').val();
            }
            if ($('#end').val()==''){
                var end = $('#end').attr('placeholder');
            }
            else{
                var end = $('#end').val();
            }
            if (textarea.val()==''){
                var content = textarea.attr('placeholder');
            }
            else{
                var content = textarea.val();
            }

            var title = content.split('\n')[0]; // first line is the title

            self._events.updateActive(title, content, start, end).done(function () {
                self.render();
            }).fail(function () {
                alert('Could not update event, not found');
            });
        });
    },
    renderNavigation: function () {
        var d = new toUTCString(Date());
        var source = $('#navigation-tpl').html();
        var template = Handlebars.compile(source);
        var html = template({events: this._events.getAll()});

        $('#app-navigation ul').html(html);

        // create a new event
        var self = this;
        $('#new-event').click(function () {
            var event = {
                title: translations.newEvent,
                content: 'content here . . .',
		        start: d,
		        end: '01.01.2016 00:00:01'
            };

            self._events.create(event).done(function() {
                self.render();
                $('#editor textarea').focus();
            }).fail(function () {
                alert('Could not create event');
            });

        });

        // show app menu
        $('#app-navigation .app-navigation-entry-utils-menu-button').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').toggleClass('open');
        });

        // delete a event
        $('#app-navigation .event .delete').click(function () {
            var entry = $(this).closest('.event');
            entry.find('.app-navigation-entry-menu').removeClass('open');

            self._events.removeActive().done(function () {
                self.render();
            }).fail(function () {
                alert('Could not delete event, not found');
            });
        });

        // load a event
        $('#app-navigation .event > a').click(function () {
            var id = parseInt($(this).parent().data('id'), 10);
            self._events.load(id);
            self.render();
            $('#editor textarea').focus();

        });
    },
    render: function () {
        this.renderNavigation();
        this.renderContent();
    }
};

var events = new Events(OC.generateUrl('/apps/owncollab_timetracker/events'));
var view = new View(events);
events.loadAll().done(function () {
    view.render();
}).fail(function () {
    alert('Could not load events');
});

});

})(OC, window, jQuery);
<|endoftext|>


<commit_before>(function(views) {

    views.AppView = Backbone.View.extend({

        el: '#app',

        events: {

        },

        initialize: function() {

        },

        viewMaker: function (config) {
            var that = this,
                arg = config.arg,
                elemId = config.elemId,
                viewName = config.viewName,
                selectId = config.selectId;

            // loading
            this.appView.loading();

            if (arg) {
                // model view
                // insurance the old view could be remove
                // if (route[viewName]) {
                //     route[viewName].remove();
                // };
                this[viewName] = new views[viewName]({arg : arg});
            } else {
                // collection view
                this[viewName] = new views[viewName]();
            }

            // tab highlight
            if (selectId) {
                this.footerView.select(selectId);
            }

            this[viewName].render(function(elem) {
                // loading
                that.appView.loaded();
                that.appView.render(elemId, elem);
            });
        },

        loading: function () {
            this.$('#prompt').show();
        },

        loaded: function () {
            this.$('#prompt').hide();
        },

        render: function (id, sHtml) {
            this.$(id).html(sHtml);
            this.loaded();
        }

    });

}).call(this, app.views);
<commit_msg>Fixing typos and layout<commit_after>(function(views) {

    views.AppView = Backbone.View.extend({

        el: '#app',

        events: {

        },

        initialize: function() {

        },

        viewMaker: function (config) {
            var that = this,
                arg = config.arg,
                elemId = config.elemId,
                viewName = config.viewName;

            // loading
            this.appView.loading();

            if (arg) {
                // model view
                // insurance the old view could be remove
                // if (route[viewName]) {
                //     route[viewName].remove();
                // };
                this[viewName] = new views[viewName]({arg : arg});
            } else {
                // collection view
                this[viewName] = new views[viewName]();
            }

            this[viewName].render(function(elem) {
                // loading
                that.appView.loaded();
                that.appView.render(elemId, elem);
            });
        },

        loading: function () {
            this.$('#prompt').show();
        },

        loaded: function () {
            this.$('#prompt').hide();
        },

        render: function (id, sHtml) {
            this.$(id).html(sHtml);
            this.loaded();
        }

    });

}).call(this, app.views);
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {
  Button, FormControl, Glyphicon
} from 'react-bootstrap';
import { DropTarget } from 'react-dnd';
import VirtualizedSelect from 'react-virtualized-select';
import DragDropItemTypes from './DragDropItemTypes';
import Sample from './models/Sample';
import Molecule from './models/Molecule';
import MoleculesFetcher from './fetchers/MoleculesFetcher';
import { ionic_liquids } from './staticDropdownOptions/ionic_liquids';
import { defaultMultiSolventsSmilesOptions } from './staticDropdownOptions/options';

const target = {
  drop(tagProps, monitor) {
    const { dropSample } = tagProps;
    const srcItem = monitor.getItem();
    const srcType = monitor.getItemType();
    if (srcType === DragDropItemTypes.SAMPLE) {
      dropSample(srcItem.element);
    } else if (srcType === DragDropItemTypes.MOLECULE) {
      dropSample(
        srcItem.element,
        null,
        true,
      );
    }
  },
  canDrop(tagProps, monitor) {
    const srcType = monitor.getItemType();
    const isCorrectType = srcType === DragDropItemTypes.SAMPLE
      || srcType === DragDropItemTypes.MOLECULE;
    return isCorrectType;
  },
};

const collect = (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop()
});

const SolventDetails = ({solvent, deleteSolvent, onChangeSolvent}) => {
  if (!solvent) {
    return (<></>)
  }

  const changeLabel = (event) => {
    solvent.label = event.target.value;
    onChangeSolvent(solvent);
  }

  const changeRatio = (event) => {
    solvent.ratio = event.target.value;
    onChangeSolvent(solvent);
  }

  // onChangeRatio
  return (

        <FormControl
          bsClass="bs-form--compact form-control"
          bsSize="small"
          type="text"
          name="solvent_label"
          value={solvent.label}
          onChange={changeLabel}
        />

        <FormControl
          bsClass="bs-form--compact form-control"
          bsSize="small"
          type="text"
          name="solvent_ratio"
          value={solvent.ratio}
          onChange={changeRatio}
        />

        <Button
          bsStyle="danger"
          bsSize="small"
          onClick={() => deleteSolvent(solvent)}
        >

        </Button>

  )
};

const SolventsGroup = ({
  materialGroup, sample, addDefaultSolvent, deleteSolvent, onChangeSolvent
}) => {
  const contents = []
  const sampleSolvents = sample.solvent
  if (sampleSolvents && sampleSolvents.length > 0) {
    let key = -1
    sampleSolvents.forEach((solv) => {
      key += 1
      contents.push((
        <SolventDetails
          key={key}
          solvent={solv}
          deleteSolvent={deleteSolvent}
          onChangeSolvent={onChangeSolvent}
        />
      ))
    })
  }

  const createDefaultSolvents = (event) => {
    const solvent = event.value;
    // MoleculesFetcher.fetchByMolfile(solvent.molfile)
    const smi = solvent.smiles;
    MoleculesFetcher.fetchBySmi(smi)
      .then((result) => {
        const molecule = new Molecule(result);
        const d = molecule.density;
        const solventDensity = solvent.density || 1;
        molecule.density = (d && d > 0) || solventDensity;
        addDefaultSolvent(molecule, null, materialGroup, solvent.external_label);
      }).catch((errorMessage) => {
        console.log(errorMessage);
      });
  };

  const solventOptions = Object.keys(ionic_liquids).reduce(
    (solvents, ionicLiquid) => solvents.concat({
      label: ionicLiquid,
      value: {
        external_label: ionicLiquid,
        smiles: ionic_liquids[ionicLiquid],
        density: 1.0
      }
    }), defaultMultiSolventsSmilesOptions
  );

  return (

              <VirtualizedSelect
                className="solvents-select"
                name="default solvents"
                multi={false}
                options={solventOptions}
                placeholder="Select solvents or drag-n-drop molecules from the sample list"
                onChange={createDefaultSolvents}
              />

            Label
            Ratio

          {contents.map(item => item)}

  );
};

class SampleDetailsSolventsDnd extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const {
      sample,
      isOver, canDrop, connectDropTarget, dropSample, deleteSolvent, onChangeSolvent
    } = this.props;
    const style = {
      padding: '2px 5px',
    };
    if (isOver && canDrop) {
      style.borderStyle = 'dashed';
      style.borderColor = '#337ab7';
    } else if (canDrop) {
      style.borderStyle = 'dashed';
    }
    return connectDropTarget(

        <SolventsGroup
          sample={sample}
          addDefaultSolvent={dropSample}
          deleteSolvent={deleteSolvent}
          onChangeSolvent={onChangeSolvent}
          />

    );
  }
}

export default DropTarget(
  [DragDropItemTypes.SAMPLE, DragDropItemTypes.MOLECULE],
  target,
  collect,
)(SampleDetailsSolventsDnd);

SampleDetailsSolventsDnd.propTypes = {
  sample: PropTypes.instanceOf(Sample).isRequired,
  headIndex: PropTypes.number,
  onChangeSolvent: PropTypes.func.isRequired,
  dropSample: PropTypes.func.isRequired,
  isOver: PropTypes.bool.isRequired,
  canDrop: PropTypes.bool.isRequired,
  connectDropTarget: PropTypes.func.isRequired,
  deleteSolvent: PropTypes.func.isRequired,
}
<commit_msg>Disabled solvent input field, only allow number in ratio input field<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {
  Button, FormControl, Glyphicon
} from 'react-bootstrap';
import { DropTarget } from 'react-dnd';
import VirtualizedSelect from 'react-virtualized-select';
import DragDropItemTypes from './DragDropItemTypes';
import Sample from './models/Sample';
import Molecule from './models/Molecule';
import MoleculesFetcher from './fetchers/MoleculesFetcher';
import { ionic_liquids } from './staticDropdownOptions/ionic_liquids';
import { defaultMultiSolventsSmilesOptions } from './staticDropdownOptions/options';

const target = {
  drop(tagProps, monitor) {
    const { dropSample } = tagProps;
    const srcItem = monitor.getItem();
    const srcType = monitor.getItemType();
    if (srcType === DragDropItemTypes.SAMPLE) {
      dropSample(srcItem.element);
    } else if (srcType === DragDropItemTypes.MOLECULE) {
      dropSample(
        srcItem.element,
        null,
        true,
      );
    }
  },
  canDrop(tagProps, monitor) {
    const srcType = monitor.getItemType();
    const isCorrectType = srcType === DragDropItemTypes.SAMPLE
      || srcType === DragDropItemTypes.MOLECULE;
    return isCorrectType;
  },
};

const collect = (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop()
});

const SolventDetails = ({solvent, deleteSolvent, onChangeSolvent}) => {
  if (!solvent) {
    return (<></>)
  }

  const changeLabel = (event) => {
    solvent.label = event.target.value;
    onChangeSolvent(solvent);
  }

  const changeRatio = (event) => {
    solvent.ratio = event.target.value;
    onChangeSolvent(solvent);
  }

  // onChangeRatio
  return (

        <FormControl
          bsClass="bs-form--compact form-control"
          bsSize="small"
          type="text"
          name="solvent_label"
          value={solvent.label}
          onChange={changeLabel}
          disabled
        />

        <FormControl
          bsClass="bs-form--compact form-control"
          bsSize="small"
          type="number"
          name="solvent_ratio"
          value={solvent.ratio}
          onChange={changeRatio}
        />

        <Button
          bsStyle="danger"
          bsSize="small"
          onClick={() => deleteSolvent(solvent)}
        >

        </Button>

  )
};

const SolventsGroup = ({
  materialGroup, sample, addDefaultSolvent, deleteSolvent, onChangeSolvent
}) => {
  const contents = []
  const sampleSolvents = sample.solvent
  if (sampleSolvents && sampleSolvents.length > 0) {
    let key = -1
    sampleSolvents.forEach((solv) => {
      key += 1
      contents.push((
        <SolventDetails
          key={key}
          solvent={solv}
          deleteSolvent={deleteSolvent}
          onChangeSolvent={onChangeSolvent}
        />
      ))
    })
  }

  const createDefaultSolvents = (event) => {
    const solvent = event.value;
    // MoleculesFetcher.fetchByMolfile(solvent.molfile)
    const smi = solvent.smiles;
    MoleculesFetcher.fetchBySmi(smi)
      .then((result) => {
        const molecule = new Molecule(result);
        const d = molecule.density;
        const solventDensity = solvent.density || 1;
        molecule.density = (d && d > 0) || solventDensity;
        addDefaultSolvent(molecule, null, materialGroup, solvent.external_label);
      }).catch((errorMessage) => {
        console.log(errorMessage);
      });
  };

  const solventOptions = Object.keys(ionic_liquids).reduce(
    (solvents, ionicLiquid) => solvents.concat({
      label: ionicLiquid,
      value: {
        external_label: ionicLiquid,
        smiles: ionic_liquids[ionicLiquid],
        density: 1.0
      }
    }), defaultMultiSolventsSmilesOptions
  );

  return (

              <VirtualizedSelect
                className="solvents-select"
                name="default solvents"
                multi={false}
                options={solventOptions}
                placeholder="Select solvents or drag-n-drop molecules from the sample list"
                onChange={createDefaultSolvents}
              />

            Label
            Ratio

          {contents.map(item => item)}

  );
};

class SampleDetailsSolventsDnd extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const {
      sample,
      isOver, canDrop, connectDropTarget, dropSample, deleteSolvent, onChangeSolvent
    } = this.props;
    const style = {
      padding: '2px 5px',
    };
    if (isOver && canDrop) {
      style.borderStyle = 'dashed';
      style.borderColor = '#337ab7';
    } else if (canDrop) {
      style.borderStyle = 'dashed';
    }
    return connectDropTarget(

        <SolventsGroup
          sample={sample}
          addDefaultSolvent={dropSample}
          deleteSolvent={deleteSolvent}
          onChangeSolvent={onChangeSolvent}
          />

    );
  }
}

export default DropTarget(
  [DragDropItemTypes.SAMPLE, DragDropItemTypes.MOLECULE],
  target,
  collect,
)(SampleDetailsSolventsDnd);

SampleDetailsSolventsDnd.propTypes = {
  sample: PropTypes.instanceOf(Sample).isRequired,
  headIndex: PropTypes.number,
  onChangeSolvent: PropTypes.func.isRequired,
  dropSample: PropTypes.func.isRequired,
  isOver: PropTypes.bool.isRequired,
  canDrop: PropTypes.bool.isRequired,
  connectDropTarget: PropTypes.func.isRequired,
  deleteSolvent: PropTypes.func.isRequired,
}
<|endoftext|>


<commit_before>var mainState= {
  preload: function(){
    game.load.audio('jump', '/assets/flappy_math/jump.wav');
    game.load.image('bird', '/assets/flappy_math/bird.png');
    game.load.image('blueBird', '/assets/flappy_math/blueBird.png');
    game.load.image('pipe', '/assets/flappy_math/pipe.png');
    game.load.image('circle', '/assets/flappy_math/circle.png');
    game.load.image('cloud', '/assets/flappy_math/cloud.png');
  },
  create: function(){
    this.jumpSound = game.add.audio('jump');
    this.p1score = 0;
    this.p2score = 0;

    this.player1score = game.add.text(20,20,"Player 1: "+this.p1score, { font: '30px Arial', fill: '#ff5733' });
    this.player2score = game.add.text(20,100,"Player 2: "+this.p2score, { font: '30px Arial', fill: '#4933ff' });

    this.pipes = game.add.group();
    this.correct = game.add.group();
    game.stage.backgroundColor = '#37edf8';
    game.physics.startSystem(Phaser.Physics.ARCADE);

    this.bird = game.add.sprite(100, 245, 'bird');
    game.physics.arcade.enable(this.bird);
    this.bird.body.gravity.y = 1000;

    var spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    spaceKey.onDown.add(this.jump, this);

    this.blueBird = game.add.sprite(100, 300, 'blueBird');
    game.physics.arcade.enable(this.blueBird);
    this.blueBird.body.gravity.y = 1000;

    key1 = game.input.keyboard.addKey(Phaser.Keyboard.ONE);
    key1.onDown.add(this.leap, this);

    this.bird.canScore = true;
    this.blueBird.canScore = true;

    this.timer = game.time.events.loop(4000, this.addRowOfPipes, this);
    this.timer = game.time.events.loop(3000, this.spawnCloud, this);

    this.bird.anchor.setTo(-0.2, 0.5);
    this.blueBird.anchor.setTo(-0.2, 0.5);
  },

  update: function(){
    if (this.bird.angle < 20){
       this.bird.angle += 1;
    }
    if (this.blueBird.angle < 20){
       this.blueBird.angle += 1;
    }

    if (this.bird.y < 0 || this.bird.y > 910){
      // this.bird.alive = false;
      this.takeDamage(1)
    }
    if (this.blueBird.y < 0 || this.blueBird.y > 910){
      // this.blueBird.alive = false;
      this.takeDamage(2);
    }
    //score on correct answer

      game.physics.arcade.overlap(this.bird, this.correct, this.p1Score, null,this);
      game.physics.arcade.overlap(this.bird, this.pipes, this.hitPipe1, null, this);

      game.physics.arcade.overlap(this.blueBird, this.correct, this.p2Score, null, this);
      game.physics.arcade.overlap(this.blueBird, this.pipes, this.hitPipe2, null, this);
  },
  hitPipe1: function(){
      if (this.bird.alive === false){
        return;
      }
      // this.bird.alive = false;
      this.takeDamage(1);
  },

  hitPipe2: function(){
      if (this.blueBird.alive === false){
        return;
      }
      // this.blueBird.alive = false;
      this.takeDamage(2);
  },

  takeDamage: function(player){
    if (player === 1 && this.bird.alive){
      that = this;
      this.bird.alpha = 0.5;
      this.bird.alive = false;

      setTimeout(function(){
        that.bird.y = 500;
        that.bird.body.velocity.y = -350;
        that.bird.alive = true;
        that.bird.alpha = 1;
      }, 2000);

    } else if (player === 2 && this.blueBird.alive){
      that = this;
      this.blueBird.alpha = 0.5;

      this.blueBird.alive = false;

      setTimeout(function(){
        that.blueBird.y = 500;
        that.blueBird.body.velocity.y = -350;
        that.blueBird.alive = true;
        that.blueBird.alpha = 1;
      }, 2000);

    }
  },

  jump: function(){
    if (this.bird.alive === false){
      return;
    }
    var animation = game.add.tween(this.bird);
    animation.to({angle: -20}, 100);
    animation.start();
    this.jumpSound.play();
    this.bird.body.velocity.y = -350;
  },

  leap: function(){
    if (this.blueBird.alive === false){
      return;
    }
    var bbanimation = game.add.tween(this.blueBird);
    bbanimation.to({angle: -20}, 100);
    bbanimation.start();
    this.jumpSound.play();
    this.blueBird.body.velocity.y = -350;
  },

  restartGame: function(){
    game.state.start('main');
  },

  spawnCloud:function(){
    var cloud = game.add.sprite(1000,Math.floor(Math.random()*900), 'cloud');
    var multiplier = Math.floor(Math.random()*3)
    cloud.height *= multiplier;
    cloud.width *= multiplier;
    game.physics.arcade.enable(cloud);
    cloud.body.velocity.x = Math.floor(Math.random()*50)-75;
  },

  p1Score: function(){
    if ( this.bird.canScore ){
      this.bird.canScore = false;
      this.p1score  += 1;
      this.player1score.text = "Player 1: "+this.p1score;
      that = this;
      setTimeout(function(){that.bird.canScore=true}, 1000);
    }
  },

  p2Score: function(){
    if ( this.blueBird.canScore ){
      this.blueBird.canScore = false;
      this.p2score  += 1;
      this.player2score.text = "Player 2: "+this.p2score;
      that = this;
      setTimeout(function(){that.blueBird.canScore=true}, 1000);
    }
  },

  spawnQuestion1: function (skill){
    var problem = game.add.text(20,60, "", { font: '30px Arial', fill: '#ffffff#' });

    param1 = Math.floor(Math.random()*10);
    param2 = Math.floor(Math.random()*10);

    problem.text = param1.toString() + " + " + param2.toString()

    that = this;
    setTimeout(function(){problem.kill()}, 4000);
    return (param1 + param2);
  },

  spawnQuestion2: function (skill){
    var problem = game.add.text(20,130, "", { font: '30px Arial', fill: '#ffffff#' });

    param1 = Math.floor(Math.random()*10);
    param2 = param1 + Math.floor(Math.random()*10);

    problem.text = param2.toString() + " - " + param1.toString()

    that = this;
    setTimeout(function(){problem.kill()}, 4000);
    return (param2 - param1);
  },
  addOnePipe: function (x,y){
      var pipe = game.add.sprite(x,y, 'pipe');

      this.pipes.add(pipe);

      game.physics.arcade.enable(pipe);

      pipe.body.velocity.x = -200

      pipe.checkWorldsBounds = true;
      pipe.outOfBoundsKill = true;
    },

  spawnAnswer: function (x, y, num, correct){
      var answer = game.add.text(x,y, num, { font: '30px Arial', fill: '#ffffff#' });
      game.physics.arcade.enable(answer);
      answer.body.velocity.x = -200;

      if (correct){
        this.correct.add(answer);

      }
    },

  currentConfig: function(){
    var configs = [[1,0,2,0,1,1,0,2,0,1,1,0,2,0,1],
      [0,2,1,1,1,0,2,0,2,0,1,1,1,2,0],
      [2,0,0,0,2,1,1,1,1,1,1,1,1,1,1],
      [1,1,1,1,1,1,1,1,1,1,2,0,0,0,2],
      [0,2,0,1,1,1,1,2,1,1,1,1,0,2,0],
      [1,1,0,2,0,1,1,1,1,1,0,2,0,1,1]];

    return configs[Math.floor(Math.random()*configs.length)];
  },

  addRowOfPipes: function() {
    a1 = this.spawnQuestion1();
    a2 = this.spawnQuestion2();

    var config = this.currentConfig();

    var count = 0;
    for(var i = 0; i < config.length; ++i){
      if(config[i] == 2) count++;
    }
    var loc1 =  Math.floor(Math.random()*count)
    var loc2 =  Math.floor(Math.random()*count)

    var answers = []

    for (var i=0 ; i < count ; ++i){
      if (i === loc1){
        answers.push(a1)
      } else if (i === loc2){
        answers.push(a2)
      } else {
        answers.push(2)
      }
    }

    for (var i=0 ; i<config.length ; i++){
      if (config[i] === 1){
        this.addOnePipe(1000, i * 60 + 10);
      }
      else if(config[i] === 2){
        this.spawnAnswer(1005, i*60+15, answers.pop(), true);
      }
    }
  }
};

var game = new Phaser.Game(1000,910, Phaser.AUTO, 'flappy-bird');

game.state.add('main', mainState);

game.state.start('main');
<commit_msg>Full math functionality<commit_after>var mainState= {
  preload: function(){
    game.load.audio('jump', '/assets/flappy_math/jump.wav');
    game.load.image('bird', '/assets/flappy_math/bird.png');
    game.load.image('blueBird', '/assets/flappy_math/blueBird.png');
    game.load.image('pipe', '/assets/flappy_math/pipe.png');
    game.load.image('circle', '/assets/flappy_math/circle.png');
    game.load.image('cloud', '/assets/flappy_math/cloud.png');
  },
  create: function(){
    this.jumpSound = game.add.audio('jump');
    this.p1score = 0;
    this.p2score = 0;

    this.player1score = game.add.text(20,20,"Player 1: "+this.p1score, { font: '30px Arial', fill: '#ff5733' });
    this.player2score = game.add.text(20,100,"Player 2: "+this.p2score, { font: '30px Arial', fill: '#4933ff' });

    this.pipes = game.add.group();
    this.correct1 = game.add.group();
    this.correct2 = game.add.group();
    game.stage.backgroundColor = '#37edf8';
    game.physics.startSystem(Phaser.Physics.ARCADE);

    this.bird = game.add.sprite(100, 245, 'bird');
    game.physics.arcade.enable(this.bird);
    this.bird.body.gravity.y = 1000;

    var spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
    spaceKey.onDown.add(this.jump, this);

    this.blueBird = game.add.sprite(100, 300, 'blueBird');
    game.physics.arcade.enable(this.blueBird);
    this.blueBird.body.gravity.y = 1000;

    key1 = game.input.keyboard.addKey(Phaser.Keyboard.ONE);
    key1.onDown.add(this.leap, this);

    this.bird.canScore = true;
    this.blueBird.canScore = true;

    this.timer = game.time.events.loop(4500, this.addRowOfPipes, this);
    this.timer = game.time.events.loop(3000, this.spawnCloud, this);

    this.bird.anchor.setTo(-0.2, 0.5);
    this.blueBird.anchor.setTo(-0.2, 0.5);
  },

  update: function(){
    if (this.bird.angle < 20){
       this.bird.angle += 1;
    }
    if (this.blueBird.angle < 20){
       this.blueBird.angle += 1;
    }

    if (this.bird.y < 0 || this.bird.y > 910){
      // this.bird.alive = false;
      this.takeDamage(1)
    }
    if (this.blueBird.y < 0 || this.blueBird.y > 910){
      // this.blueBird.alive = false;
      this.takeDamage(2);
    }
    //score on correct answer

      game.physics.arcade.overlap(this.bird, this.correct1, this.p1Score, null,this);
      game.physics.arcade.overlap(this.bird, this.pipes, this.hitPipe1, null, this);

      game.physics.arcade.overlap(this.blueBird, this.correct2, this.p2Score, null, this);
      game.physics.arcade.overlap(this.blueBird, this.pipes, this.hitPipe2, null, this);
  },
  hitPipe1: function(){
      if (this.bird.alive === false){
        return;
      }
      // this.bird.alive = false;
      this.takeDamage(1);
  },

  hitPipe2: function(){
      if (this.blueBird.alive === false){
        return;
      }
      // this.blueBird.alive = false;
      this.takeDamage(2);
  },

  takeDamage: function(player){
    if (player === 1 && this.bird.alive){
      that = this;
      this.bird.alpha = 0.5;
      this.bird.alive = false;

      setTimeout(function(){
        that.bird.y = 500;
        that.bird.body.velocity.y = -350;
        that.bird.alive = true;
        that.bird.alpha = 1;
      }, 2000);

    } else if (player === 2 && this.blueBird.alive){
      that = this;
      this.blueBird.alpha = 0.5;

      this.blueBird.alive = false;

      setTimeout(function(){
        that.blueBird.y = 500;
        that.blueBird.body.velocity.y = -350;
        that.blueBird.alive = true;
        that.blueBird.alpha = 1;
      }, 2000);

    }
  },

  jump: function(){
    if (this.bird.alive === false){
      return;
    }
    var animation = game.add.tween(this.bird);
    animation.to({angle: -20}, 100);
    animation.start();
    this.jumpSound.play();
    this.bird.body.velocity.y = -350;
  },

  leap: function(){
    if (this.blueBird.alive === false){
      return;
    }
    var bbanimation = game.add.tween(this.blueBird);
    bbanimation.to({angle: -20}, 100);
    bbanimation.start();
    this.jumpSound.play();
    this.blueBird.body.velocity.y = -350;
  },

  restartGame: function(){
    game.state.start('main');
  },

  spawnCloud:function(){
    var cloud = game.add.sprite(1000,Math.floor(Math.random()*900), 'cloud');
    var multiplier = Math.floor(Math.random()*3)
    cloud.height *= multiplier;
    cloud.width *= multiplier;
    game.physics.arcade.enable(cloud);
    cloud.body.velocity.x = Math.floor(Math.random()*50)-75;
  },

  p1Score: function(){
    if ( this.bird.canScore ){
      this.bird.canScore = false;
      this.p1score  += 1;
      this.player1score.text = "Player 1: "+this.p1score;
      that = this;
      setTimeout(function(){that.bird.canScore=true}, 1000);
    }
  },

  p2Score: function(){
    if ( this.blueBird.canScore ){
      this.blueBird.canScore = false;
      this.p2score  += 1;
      this.player2score.text = "Player 2: "+this.p2score;
      that = this;
      setTimeout(function(){that.blueBird.canScore=true}, 1000);
    }
  },

  spawnQuestion1: function (skill){
    var problem = game.add.text(20,60, "", { font: '30px Arial', fill: '#ffffff#' });

    param1 = Math.floor(Math.random()*10);
    param2 = Math.floor(Math.random()*10);

    problem.text = param1.toString() + " + " + param2.toString()

    that = this;
    setTimeout(function(){problem.kill()}, 4500);
    return (param1 + param2);
  },

  spawnQuestion2: function (skill){
    var problem = game.add.text(20,130, "", { font: '30px Arial', fill: '#ffffff#' });

    param1 = Math.floor(Math.random()*10);
    param2 = param1 + Math.floor(Math.random()*10);

    problem.text = param2.toString() + " - " + param1.toString()

    that = this;
    setTimeout(function(){problem.kill()}, 4500);
    return (param2 - param1);
  },
  addOnePipe: function (x,y){
      var pipe = game.add.sprite(x,y, 'pipe');

      this.pipes.add(pipe);

      game.physics.arcade.enable(pipe);

      pipe.body.velocity.x = -200

      pipe.checkWorldsBounds = true;
      pipe.outOfBoundsKill = true;
    },

  spawnAnswer: function (x, y, num, correct1, correct2){
      var answer = game.add.text(x,y, num, { font: '30px Arial', fill: '#ffffff#' });
      game.physics.arcade.enable(answer);
      answer.body.velocity.x = -200;

      if (correct1){
        this.correct1.add(answer)
      } else if (correct2) {
        this.correct2.add(answer)
      }
    },

  currentConfig: function(){
    var configs = [[1,0,2,0,1,1,0,2,0,1,1,0,2,0,1],
      [0,2,1,1,1,0,2,0,2,0,1,1,1,2,0],
      [2,0,0,0,2,1,1,1,1,1,1,1,1,1,1],
      [1,1,1,1,1,1,1,1,1,1,2,0,0,0,2],
      [0,2,0,1,1,1,1,2,1,1,1,1,0,2,0],
      [1,1,0,2,0,1,1,1,1,1,0,2,0,1,1]];

    return configs[Math.floor(Math.random()*configs.length)];
  },

  addRowOfPipes: function() {
    a1 = this.spawnQuestion1();
    a2 = this.spawnQuestion2();
    console.log(a1)

    var config = this.currentConfig();

    var count = 0;
    for(var i = 0; i < config.length; ++i){
      if(config[i] == 2) count++;
    }
    var loc1 =  Math.floor(Math.random()*count)
    var loc2 =  Math.floor(Math.random()*count)

    var answers = []

    for (var i=0 ; i < count ; ++i){
      if (i === loc1){
        answers.push(a1)
      } else if (i === loc2){
        answers.push(a2)
      } else {
        answers.push(2)
      }
    }

    console.log(answers)

    for (var i=0 ; i<config.length ; i++){
      if (config[i] === 1){
        this.addOnePipe(1000, i * 60 + 10);
      }
      else if(config[i] !== 0){
        config[i] = answers.pop()
        this.spawnAnswer(1005, i*60+15, config[i], config[i]===a1, config[i]===a2 );
      }
    }
  }
};

var game = new Phaser.Game(1000,910, Phaser.AUTO, 'flappy-bird');

game.state.add('main', mainState);

game.state.start('main');
<|endoftext|>


<commit_before>import { EventEmitter } from 'events';
import superagent from 'superagent';
import url from 'url';

import activities from './apis/activities';
import hidden from './apis/hidden';
import saves from './apis/saves';
import search from './apis/search';
import stylesheets from './apis/stylesheets';
import subreddits from './apis/subreddits';
import subscriptions from './apis/subscriptions';
import trophies from './apis/trophies';
import accounts from './apis/accounts';
import votes from './apis/votes';
import links from './apis/links';
import comments from './apis/comments';
import captcha from './apis/captcha';
import reports from './apis/reports';
import messages from './apis/messages';
import modListing from './apis/modListing';
import subredditRelationships from './apis/subredditRelationships';
import rules from './apis/rules';
import wiki from './apis/wiki';
import multis from './apis/multis';
import multiSubscriptions from './apis/multiSubscriptions';

export const APIs = {
  activities,
  captcha,
  hidden,
  saves,
  search,
  stylesheets,
  subreddits,
  subscriptions,
  trophies,
  accounts,
  votes,
  links,
  comments,
  reports,
  messages,
  modListing,
  subredditRelationships,
  rules,
  wiki,
  multis,
  multiSubscriptions,
};

import NoModelError from './errors/noModelError';
import ResponseError from './errors/responseError';
import { DisconnectedError } from './errors/responseError';
import ValidationError from './errors/validationError';
import NotImplementedError from './errors/notImplementedError';

export const errors = {
  NoModelError,
  ValidationError,
  ResponseError,
  DisconnectedError,
  NotImplementedError,
};

import Account from './models/account';
import Award from './models/award';
import Base from './models/base';
import Block from './models/block';
import BlockedUser from './models/BlockedUser';
import Comment from './models/comment';
import Link from './models/link';
import Message from './models/message';
import PromoCampaign from './models/promocampaign';
import Preferences from './models/preferences';
import Subreddit from './models/subreddit';
import Subscription from './models/subscription';
import Vote from './models/vote';
import Report from './models/report';
import WikiPage from './models/wikiPage';
import WikiRevision from './models/wikiRevision';
import WikiPageListing from './models/wikiPageListing';
import WikiPageSettings from './models/wikiPageSettings';

export const models = {
  Account,
  Award,
  Base,
  Block,
  BlockedUser,
  Comment,
  Link,
  Message,
  PromoCampaign,
  Preferences,
  Subreddit,
  Subscription,
  Vote,
  Report,
  WikiPage,
  WikiRevision,
  WikiPageListing,
  WikiPageSettings,
};

const DEFAULT_API_ORIGIN = 'https://www.reddit.com';
const AUTHED_API_ORIGIN = 'https://oauth.reddit.com';

const SCOPES = 'history,identity,mysubreddits,read,subscribe,vote,submit,' +
               'save,edit,account,creddits,flair,livemanage,modconfig,' +
               'modcontributors,modflair,modlog,modothers,modposts,modself,' +
               'modwiki,privatemessages,report,wikiedit,wikiread';

class Snoode {
  constructor(config={}) {
    this.config = {
      origin: DEFAULT_API_ORIGIN,
      event: new EventEmitter(),
      userAgent: 'snoodev2',
      ...config,
    };

    this.event = this.config.event;

    for (let a in APIs) {
      this[a] = new APIs[a](this);
    }
  }

  withAuth (token, changeOrigin=true) {
    return new Snoode({
      ...this.config,
      token,
      origin: changeOrigin ? AUTHED_API_ORIGIN : this.config.origin,
    });
  }

  withConfig (config) {
    // Merge the new config onto the old and return a new instance
    return new Snoode({...this.config, ...config});
  }
}

export default Snoode;
<commit_msg>Expose API interface<commit_after>import { EventEmitter } from 'events';
import superagent from 'superagent';
import url from 'url';

import activities from './apis/activities';
import hidden from './apis/hidden';
import saves from './apis/saves';
import search from './apis/search';
import stylesheets from './apis/stylesheets';
import subreddits from './apis/subreddits';
import subscriptions from './apis/subscriptions';
import trophies from './apis/trophies';
import accounts from './apis/accounts';
import votes from './apis/votes';
import links from './apis/links';
import comments from './apis/comments';
import captcha from './apis/captcha';
import reports from './apis/reports';
import messages from './apis/messages';
import modListing from './apis/modListing';
import subredditRelationships from './apis/subredditRelationships';
import rules from './apis/rules';
import wiki from './apis/wiki';
import multis from './apis/multis';
import multiSubscriptions from './apis/multiSubscriptions';

export const APIs = {
  activities,
  captcha,
  hidden,
  saves,
  search,
  stylesheets,
  subreddits,
  subscriptions,
  trophies,
  accounts,
  votes,
  links,
  comments,
  reports,
  messages,
  modListing,
  subredditRelationships,
  rules,
  wiki,
  multis,
  multiSubscriptions,
};

import NoModelError from './errors/noModelError';
import ResponseError from './errors/responseError';
import { DisconnectedError } from './errors/responseError';
import ValidationError from './errors/validationError';
import NotImplementedError from './errors/notImplementedError';

export const errors = {
  NoModelError,
  ValidationError,
  ResponseError,
  DisconnectedError,
  NotImplementedError,
};

import Account from './models/account';
import Award from './models/award';
import Base from './models/base';
import Block from './models/block';
import BlockedUser from './models/BlockedUser';
import Comment from './models/comment';
import Link from './models/link';
import Message from './models/message';
import PromoCampaign from './models/promocampaign';
import Preferences from './models/preferences';
import Subreddit from './models/subreddit';
import Subscription from './models/subscription';
import Vote from './models/vote';
import Report from './models/report';
import WikiPage from './models/wikiPage';
import WikiRevision from './models/wikiRevision';
import WikiPageListing from './models/wikiPageListing';
import WikiPageSettings from './models/wikiPageSettings';

export const models = {
  Account,
  Award,
  Base,
  Block,
  BlockedUser,
  Comment,
  Link,
  Message,
  PromoCampaign,
  Preferences,
  Subreddit,
  Subscription,
  Vote,
  Report,
  WikiPage,
  WikiRevision,
  WikiPageListing,
  WikiPageSettings,
};

const DEFAULT_API_ORIGIN = 'https://www.reddit.com';
const AUTHED_API_ORIGIN = 'https://oauth.reddit.com';

const SCOPES = 'history,identity,mysubreddits,read,subscribe,vote,submit,' +
               'save,edit,account,creddits,flair,livemanage,modconfig,' +
               'modcontributors,modflair,modlog,modothers,modposts,modself,' +
               'modwiki,privatemessages,report,wikiedit,wikiread';

class Snoode {
  static APIs = Object.keys(APIs);

  constructor(config={}) {
    this.config = {
      origin: DEFAULT_API_ORIGIN,
      event: new EventEmitter(),
      userAgent: 'snoodev2',
      ...config,
    };

    this.event = this.config.event;

    for (let a in APIs) {
      this[a] = new APIs[a](this);
    }
  }

  withAuth (token, changeOrigin=true) {
    return new Snoode({
      ...this.config,
      token,
      origin: changeOrigin ? AUTHED_API_ORIGIN : this.config.origin,
    });
  }

  withConfig (config) {
    // Merge the new config onto the old and return a new instance
    return new Snoode({...this.config, ...config});
  }
}

export default Snoode;
<|endoftext|>


<commit_before>var core = module.exports = require('./core');

// add core plugins.
core.utils          = require('./utils');

// use default pixi loader
core.loader = PIXI.loader;

// mixin the deprecation features.
//Object.assign(core, require('./deprecation'));

// export GOWN globally.
global.GOWN = core;<commit_msg>Added trap for pixi.js<commit_after>if (typeof PIXI === 'undefined') {
  console.warn('pixi.js has to be loaded before loading gown.js');
  return;
}

var core = module.exports = require('./core');

// add core plugins.
core.utils          = require('./utils');

// use default pixi loader
core.loader = PIXI.loader;

// mixin the deprecation features.
//Object.assign(core, require('./deprecation'));

// export GOWN globally.
global.GOWN = core;
<|endoftext|>


<commit_before>/* Author:

*/

<commit_msg>Using script.js as a dummy interface to persistant storage.<commit_after>/* Author:

*/

var recipes = [{
	"title": 		"Pizza",
	"ingredients": "1tsp salt\n1dl flour",
	"instructions": "1. Make a delicious pizza.\n2. ???\n3. Profit.",
	"tags": ["Pizza", "Meat", "Baking"]
}]

var tags = ["Pizza", "Meat", "Baking", "Chicken", "Cow"]
<|endoftext|>


<commit_before>$.googleMapAdapter = {
	map: undefined,
	searchBox: undefined,
	searchMarker: undefined,
	searchMarkerOnCLickAction: undefined,
	infoWindow: undefined,

	directions: false,

	//Adapter Functions
	createMap: function(selector, center, zoom, searchMarkerOnCLickAction) {
		this.map = new google.maps.Map($(selector)[0], {
			center: this.createLatLng(center),
			zoom: zoom,
			disableDefaultUI: true
		});
		this.directions = {
			renderer: new google.maps.DirectionsRenderer(),
			service: new google.maps.DirectionsService()
		};
		this.directions.renderer.setMap(this.map);
		this.fixInfoWindow();

		this.searchMarkerOnCLickAction = searchMarkerOnCLickAction;
		this.createSearchIcon();
	},

	addOnLoadEvent: function(onLoad) {
		google.maps.event.addListenerOnce(this.map, "idle", onLoad);
	},

	addOnChangeEvent: function(onChange) {
		this.addEventListener(this.map, "idle", onChange);
	},

	getZoom: function() {
		return this.map.getZoom();
	},

	setZoom: function(zoomLevel) {
		if((zoomLevel >= $.settings.minZoom) && (zoomLevel <= $.settings.maxZoom)) {
			$.googleMapAdapter.map.setZoom(zoomLevel);
			$.googleMapAdapter.adjustBounds();
		}
	},

	addTopLeftElement: function(element) {
		this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(element);
	},

	addTopRightElement: function(element) {
		this.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(element);
	},

	addBottomLeftElement: function(element) {
		this.map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(element);
	},

	addBottomRightElement: function(element) {
		this.map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(element);
	},

	addSearch: function(searchBox) {
		this.searchBox = new google.maps.places.SearchBox(searchBox);
		this.addEventListener(this.searchBox, 'places_changed', function() {$.googleMapAdapter.searchPlace()});
  		this.addEventListener(this.map, 'bounds_changed', function() {$.googleMapAdapter.adjustBounds()});
	},

	createMarker: function(position, visible, icon, description, label, infoWindowClass, onClickAction) {
		var markerOptions = {};
		markerOptions.map = this.map;
		markerOptions.position = this.createLatLng(position);

		if (icon !== undefined) {markerOptions.icon = this.createMarkerIcon(icon);}
		var marker = this.createLabeledOrNonLabeledMarker(label, markerOptions);
		marker.setVisible(visible);

		if (onClickAction !== undefined) {this.addEventListener(marker, "click", onClickAction);}
		else {this.addDefaultOnCLickActionToMarker(marker, description, position, infoWindowClass);}

		return marker;
	},

	updateMarkerLabel: function(marker, label) {
		marker.set("label", label);
	},

	deleteMarker: function(marker) {
		marker.setMap(null);
	},

	createPoint: function(position, radius, color, visible, description, infoWindowClass) {
		var circleOptions = {};
		circleOptions.map = this.map;
		circleOptions.center = this.createLatLng(position);
		circleOptions.fillColor = color;
		circleOptions.fillOpacity = 1;
		circleOptions.radius = radius;
		circleOptions.strokeOpacity = 0;
		var circle = new google.maps.Circle(circleOptions);
		circle.setVisible(visible);
		circle.position = circleOptions.center;
		if (description !== undefined) {
			this.addEventListener(circle, "click", function() {$.googleMapAdapter.createInfoWindow(description, circle, infoWindowClass);});
		}
		return circle;
	},

	createLine: function(path, color, visible, icon, description, label) {
		var instance = {};
		var lineOptions = {};
		lineOptions.path = [];
		for (var i=0; i<path.length; i++) {
			lineOptions.path.push(new google.maps.LatLng(path[i].latitude, path[i].longitude));
		}
		lineOptions.map = this.map;
		lineOptions.strokeColor = color;
		lineOptions.visible = visible;
		instance.line = new google.maps.Polyline(lineOptions);
		if (icon !== undefined && path.length == 2) {
			instance.marker = this.createMarker({latitude: (path[0].latitude + path[1].latitude)/2, longitude: (path[0].longitude + path[1].longitude)/2}, visible, icon, description, label);
		}
		return instance;
	},

	setMarkerVisible: function(marker, visible) {
		marker.setVisible(visible);
	},

	setPointVisible: function(point, visible) {
		point.setVisible(visible);
	},

	setLineVisible: function(line, visible) {
		line.line.setVisible(visible);
		if (line.marker)
			line.marker.setVisible(visible);
	},

	getBounds: function() {
		var bounds = this.map.getBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		return {
			min: {
				latitude: sw.lat(),
				longitude: sw.lng()
			},
			max: {
				latitude: ne.lat(),
				longitude: ne.lng()
			}
		};
	},

	//Helper Functions
	createLatLng: function(point) {
		return new google.maps.LatLng(point.latitude, point.longitude);
	},

	createInfoWindow: function(description, object, infoWindowClass) {
		if (this.infoWindow !== undefined)
			this.infoWindow.close();

		this.infoWindow = new InfoBox({pixelOffset: new google.maps.Size(-133, -121)});
		this.infoWindow.noSupress=true; // Stop info window from being hidden by the fixInfoWindow function
		this.infoWindow.setContent("
"+description+"
");
		this.infoWindow.open(this.map, object);
		this.setCenter(object.getPosition());
		this.addEventListener(this.infoWindow, 'domready', function() {
			$(".infoBox").addClass(infoWindowClass);
		});
	},

	searchPlace: function() {
		var places = this.searchBox.getPlaces();

		this.updateSearchMarker(places[0].name, places[0].geometry.location);

		this.map.setCenter(places[0].geometry.location);
		this.map.setZoom(18);
  		this.adjustBounds();
	},

	adjustBounds: function(){
		var bounds = this.map.getBounds();
    		this.searchBox.setBounds(bounds);
	},

	isWithinBounds: function(object){
		if(object.hasOwnProperty('path')){ //For lines check if at least one end point is within bounds
			var lineIsWithinBounds = this.map.getBounds().contains(this.createLatLng(object.path[0]));
			lineIsWithinBounds = lineIsWithinBounds || this.map.getBounds().contains(this.createLatLng(object.path[1]));
			return lineIsWithinBounds;
		}
		return this.map.getBounds().contains(this.createLatLng(object.position));
	},

	getDirectionsTo: function(location) {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var from = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				var to = new google.maps.LatLng(location.latitude, location.longitude);
				$.googleMapAdapter.makeDirectionRequest(from, to);
			}, function() {
				$.googleMapAdapter.getDirectionsToNoGeolocation(location);
			});
		}
		else {
			$.googleMapAdapter.getDirectionsToNoGeolocation(location);
		}
	},

	getDirectionsToNoGeolocation: function(location) {
		var from = this.map.getCenter();
		var to = new google.maps.LatLng(location.latitude, location.longitude);
		$.googleMapAdapter.makeDirectionRequest(from, to);
	},

	makeDirectionRequest: function(from, to) {
		var request = {
			origin: from,
			destination: to,
			travelMode: google.maps.TravelMode.DRIVING
		};
		$.googleMapAdapter.directions.service.route(request, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				$.googleMapAdapter.directions.renderer.setDirections(result);
			}
		});
	},

	//Hides google maps own info windows
	fixInfoWindow: function() {
	    	var set = google.maps.InfoWindow.prototype.set;
	    	google.maps.InfoWindow.prototype.set = function (key, val) {
			if (key === 'map') {
			    if (!this.get('noSupress')) {
				console.log('This InfoWindow is supressed. To enable it, set "noSupress" option to true');
				return;
			    }
			}
			set.apply(this, arguments);
	    	}
	},

	setCenter: function(center) {
		this.map.setCenter(new google.maps.LatLng(center.latitude, center.longitude));
	},

	addEventListener: function(object, event, action) {
		google.maps.event.addListener(object, event, action);
	},

	clearEventListener: function(object, event) {
		google.maps.event.clearListeners(object, event);
	},

	createMarkerIcon: function(iconData) {
		var iconPath = iconData.url;
		var iconOffset = null;
		if (iconData.offset) {iconOffset = new google.maps.Point(iconData.offset.x, iconData.offset.y);}
		var iconSize = null;
		if (iconData.size) {iconSize = new google.maps.Size(iconData.size.x, iconData.size.y);}

		return new google.maps.MarkerImage(iconPath, null, null, iconOffset, iconSize);
	},

	createLabeledOrNonLabeledMarker: function(label, markerOptions) {
		if (label !== undefined) {
			markerOptions.labelContent = label;
			markerOptions.labelAnchor = new google.maps.Point(4, 30);
			return new MarkerWithLabel(markerOptions);
		}

		return new google.maps.Marker(markerOptions);
	},

	addDefaultOnCLickActionToMarker: function(marker, description, position, windowClass) {
		if (description !== undefined)
			this.addEventListener(marker, "click", function() {$.googleMapAdapter.createInfoWindow(description, marker, windowClass);});
		else {
			this.addEventListener(marker, "click", function() {
				$.googleMapAdapter.setCenter(position);
				$.googleMapAdapter.setZoom($.googleMapAdapter.getZoom() + 1);
			});
		}
	},

	createLocationMarker: function(position) {
		var iconProperties = $.settings.assets.current_location;
		var locationMarker = this.createMarker(position, true, iconProperties.icon, "", undefined, iconProperties.type);
	},

	createSearchIcon: function() {
		var iconProperties = $.settings.assets.search_result;
		var position = {latitude:0,longitude:0};
		this.searchMarker = this.createMarker(position, false, iconProperties.icon, "", undefined, iconProperties.type);
		this.clearEventListener(this.searchMarker, "click");
	},

	updateSearchMarker: function(title, position) {
		this.setMarkerVisible(this.searchMarker,false);
		this.searchMarker.setTitle(title);
		this.searchMarker.setPosition(position);

		if(this.searchMarkerOnCLickAction !== undefined) {
			this.clearEventListener(this.searchMarker, "click");
			this.addEventListener(this.searchMarker, "click", searchMarkerOnCLickAction(title, position));
		}

		this.setMarkerVisible(this.searchMarker,true);
	}
};
<commit_msg>Throw exception if createLatLng is used on wrong format<commit_after>$.googleMapAdapter = {
	map: undefined,
	searchBox: undefined,
	searchMarker: undefined,
	searchMarkerOnCLickAction: undefined,
	infoWindow: undefined,

	directions: false,

	//Adapter Functions
	createMap: function(selector, center, zoom, searchMarkerOnCLickAction) {
		this.map = new google.maps.Map($(selector)[0], {
			center: this.createLatLng(center),
			zoom: zoom,
			disableDefaultUI: true
		});
		this.directions = {
			renderer: new google.maps.DirectionsRenderer(),
			service: new google.maps.DirectionsService()
		};
		this.directions.renderer.setMap(this.map);
		this.fixInfoWindow();

		this.searchMarkerOnCLickAction = searchMarkerOnCLickAction;
		this.createSearchIcon();
	},

	addOnLoadEvent: function(onLoad) {
		google.maps.event.addListenerOnce(this.map, "idle", onLoad);
	},

	addOnChangeEvent: function(onChange) {
		this.addEventListener(this.map, "idle", onChange);
	},

	getZoom: function() {
		return this.map.getZoom();
	},

	setZoom: function(zoomLevel) {
		if((zoomLevel >= $.settings.minZoom) && (zoomLevel <= $.settings.maxZoom)) {
			$.googleMapAdapter.map.setZoom(zoomLevel);
			$.googleMapAdapter.adjustBounds();
		}
	},

	addTopLeftElement: function(element) {
		this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(element);
	},

	addTopRightElement: function(element) {
		this.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(element);
	},

	addBottomLeftElement: function(element) {
		this.map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(element);
	},

	addBottomRightElement: function(element) {
		this.map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(element);
	},

	addSearch: function(searchBox) {
		this.searchBox = new google.maps.places.SearchBox(searchBox);
		this.addEventListener(this.searchBox, 'places_changed', function() {$.googleMapAdapter.searchPlace()});
  		this.addEventListener(this.map, 'bounds_changed', function() {$.googleMapAdapter.adjustBounds()});
	},

	createMarker: function(position, visible, icon, description, label, infoWindowClass, onClickAction) {
		var markerOptions = {};
		markerOptions.map = this.map;
		markerOptions.position = this.createLatLng(position);

		if (icon !== undefined) {markerOptions.icon = this.createMarkerIcon(icon);}
		var marker = this.createLabeledOrNonLabeledMarker(label, markerOptions);
		marker.setVisible(visible);

		if (onClickAction !== undefined) {this.addEventListener(marker, "click", onClickAction);}
		else {this.addDefaultOnCLickActionToMarker(marker, description, position, infoWindowClass);}

		return marker;
	},

	updateMarkerLabel: function(marker, label) {
		marker.set("label", label);
	},

	deleteMarker: function(marker) {
		marker.setMap(null);
	},

	createPoint: function(position, radius, color, visible, description, infoWindowClass) {
		var circleOptions = {};
		circleOptions.map = this.map;
		circleOptions.center = this.createLatLng(position);
		circleOptions.fillColor = color;
		circleOptions.fillOpacity = 1;
		circleOptions.radius = radius;
		circleOptions.strokeOpacity = 0;
		var circle = new google.maps.Circle(circleOptions);
		circle.setVisible(visible);
		circle.position = circleOptions.center;
		if (description !== undefined) {
			this.addEventListener(circle, "click", function() {$.googleMapAdapter.createInfoWindow(description, circle, infoWindowClass);});
		}
		return circle;
	},

	createLine: function(path, color, visible, icon, description, label) {
		var instance = {};
		var lineOptions = {};
		lineOptions.path = [];
		for (var i=0; i<path.length; i++) {
			lineOptions.path.push(new google.maps.LatLng(path[i].latitude, path[i].longitude));
		}
		lineOptions.map = this.map;
		lineOptions.strokeColor = color;
		lineOptions.visible = visible;
		instance.line = new google.maps.Polyline(lineOptions);
		if (icon !== undefined && path.length == 2) {
			instance.marker = this.createMarker({latitude: (path[0].latitude + path[1].latitude)/2, longitude: (path[0].longitude + path[1].longitude)/2}, visible, icon, description, label);
		}
		return instance;
	},

	setMarkerVisible: function(marker, visible) {
		marker.setVisible(visible);
	},

	setPointVisible: function(point, visible) {
		point.setVisible(visible);
	},

	setLineVisible: function(line, visible) {
		line.line.setVisible(visible);
		if (line.marker)
			line.marker.setVisible(visible);
	},

	getBounds: function() {
		var bounds = this.map.getBounds();
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
		return {
			min: {
				latitude: sw.lat(),
				longitude: sw.lng()
			},
			max: {
				latitude: ne.lat(),
				longitude: ne.lng()
			}
		};
	},

	//Helper Functions
	createLatLng: function(point) {
		if(!point.hasOwnProperty('latitude')){
			throw "Exception: Expected a point with a latitude and longitude defined";
		}
		return new google.maps.LatLng(point.latitude, point.longitude);
	},

	createInfoWindow: function(description, object, infoWindowClass) {
		if (this.infoWindow !== undefined)
			this.infoWindow.close();

		this.infoWindow = new InfoBox({pixelOffset: new google.maps.Size(-133, -121)});
		this.infoWindow.noSupress=true; // Stop info window from being hidden by the fixInfoWindow function
		this.infoWindow.setContent("
"+description+"
");
		this.infoWindow.open(this.map, object);
		this.setCenter(object.getPosition());
		this.addEventListener(this.infoWindow, 'domready', function() {
			$(".infoBox").addClass(infoWindowClass);
		});
	},

	searchPlace: function() {
		var places = this.searchBox.getPlaces();

		this.updateSearchMarker(places[0].name, places[0].geometry.location);

		this.map.setCenter(places[0].geometry.location);
		this.map.setZoom(18);
  		this.adjustBounds();
	},

	adjustBounds: function(){
		var bounds = this.map.getBounds();
    		this.searchBox.setBounds(bounds);
	},

	isWithinBounds: function(object){
		if(object.hasOwnProperty('path')){ //For lines check if at least one end point is within bounds
			var lineIsWithinBounds = this.map.getBounds().contains(this.createLatLng(object.path[0]));
			lineIsWithinBounds = lineIsWithinBounds || this.map.getBounds().contains(this.createLatLng(object.path[1]));
			return lineIsWithinBounds;
		}
		return this.map.getBounds().contains(this.createLatLng(object.position));
	},

	getDirectionsTo: function(location) {
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var from = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				var to = new google.maps.LatLng(location.latitude, location.longitude);
				$.googleMapAdapter.makeDirectionRequest(from, to);
			}, function() {
				$.googleMapAdapter.getDirectionsToNoGeolocation(location);
			});
		}
		else {
			$.googleMapAdapter.getDirectionsToNoGeolocation(location);
		}
	},

	getDirectionsToNoGeolocation: function(location) {
		var from = this.map.getCenter();
		var to = new google.maps.LatLng(location.latitude, location.longitude);
		$.googleMapAdapter.makeDirectionRequest(from, to);
	},

	makeDirectionRequest: function(from, to) {
		var request = {
			origin: from,
			destination: to,
			travelMode: google.maps.TravelMode.DRIVING
		};
		$.googleMapAdapter.directions.service.route(request, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				$.googleMapAdapter.directions.renderer.setDirections(result);
			}
		});
	},

	//Hides google maps own info windows
	fixInfoWindow: function() {
	    	var set = google.maps.InfoWindow.prototype.set;
	    	google.maps.InfoWindow.prototype.set = function (key, val) {
			if (key === 'map') {
			    if (!this.get('noSupress')) {
				console.log('This InfoWindow is supressed. To enable it, set "noSupress" option to true');
				return;
			    }
			}
			set.apply(this, arguments);
	    	}
	},

	setCenter: function(center) {
		this.map.setCenter(new google.maps.LatLng(center.latitude, center.longitude));
	},

	addEventListener: function(object, event, action) {
		google.maps.event.addListener(object, event, action);
	},

	clearEventListener: function(object, event) {
		google.maps.event.clearListeners(object, event);
	},

	createMarkerIcon: function(iconData) {
		var iconPath = iconData.url;
		var iconOffset = null;
		if (iconData.offset) {iconOffset = new google.maps.Point(iconData.offset.x, iconData.offset.y);}
		var iconSize = null;
		if (iconData.size) {iconSize = new google.maps.Size(iconData.size.x, iconData.size.y);}

		return new google.maps.MarkerImage(iconPath, null, null, iconOffset, iconSize);
	},

	createLabeledOrNonLabeledMarker: function(label, markerOptions) {
		if (label !== undefined) {
			markerOptions.labelContent = label;
			markerOptions.labelAnchor = new google.maps.Point(4, 30);
			return new MarkerWithLabel(markerOptions);
		}

		return new google.maps.Marker(markerOptions);
	},

	addDefaultOnCLickActionToMarker: function(marker, description, position, windowClass) {
		if (description !== undefined)
			this.addEventListener(marker, "click", function() {$.googleMapAdapter.createInfoWindow(description, marker, windowClass);});
		else {
			this.addEventListener(marker, "click", function() {
				$.googleMapAdapter.setCenter(position);
				$.googleMapAdapter.setZoom($.googleMapAdapter.getZoom() + 1);
			});
		}
	},

	createLocationMarker: function(position) {
		var iconProperties = $.settings.assets.current_location;
		var locationMarker = this.createMarker(position, true, iconProperties.icon, "", undefined, iconProperties.type);
	},

	createSearchIcon: function() {
		var iconProperties = $.settings.assets.search_result;
		var position = {latitude:0,longitude:0};
		this.searchMarker = this.createMarker(position, false, iconProperties.icon, "", undefined, iconProperties.type);
		this.clearEventListener(this.searchMarker, "click");
	},

	updateSearchMarker: function(title, position) {
		this.setMarkerVisible(this.searchMarker,false);
		this.searchMarker.setTitle(title);
		this.searchMarker.setPosition(position);

		if(this.searchMarkerOnCLickAction !== undefined) {
			this.clearEventListener(this.searchMarker, "click");
			this.addEventListener(this.searchMarker, "click", searchMarkerOnCLickAction(title, position));
		}

		this.setMarkerVisible(this.searchMarker,true);
	}
};
<|endoftext|>