<commit_before>(function($window, $ember, $jQuery) {

    "use strict";

    /**
     * @module App
     * @class EmberDropletController
     * @type Ember.Mixin
     * @extends Ember.Mixin
     */
    $window.DropletController = $ember.Mixin.create({

        /**
         * @property mimeTypes
         * @type {Array}
         */
        mimeTypes: ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'text/plain'],

        /**
         * @property extensions
         * @type {Array}
         */
        extensions: ['jpeg', 'jpg', 'gif', 'png'],

        /**
         * Contains a list of headers to be included in the request made by
         * uploadAllFiles()
         *
         * @property requestHeaders
         * @type {Object}
         */
        requestHeaders: {},

        /**
         * Contains a dictionary of extra POST data to be included in the
         * request made by uploadAllFiles()
         *
         * @property postData
         * @type {Object}
         */
        postData: {},

        /**
         * Contains a list of files, both valid, deleted, and invalid.
         *
         * @property files
         * @type {Array}
         * @default []
         */
        files: [],

        /**
         * @property uploadStatus
         * @type {Object}
         */
        uploadStatus: $ember.computed(function() {
          return { uploading: false, percentComplete: 0, error: false };
        }),

        /**
         * Clears the file array for each instantiation.
         *
         * @constructor
         * @method init
         * @return {void}
         */
        init: function() {
            $ember.set(this, 'files', []);
            this._super();
        },

        /**
         * @property actions
         * @type {Object}
         */
        actions: {

            /**
             * Adds a valid file to the collection.
             *
             * @method addValidFile
             * @param file {File}
             * @return {Object}
             */
            addValidFile: function(file) {
                return this._addFile(file, true);
            },

            /**
             * Adds an invalid file to the collection.
             *
             * @method addInvalidFile
             * @param file {File}
             * @return {Object}
             */
            addInvalidFile: function(file) {
                return this._addFile(file, false);
            },

            /**
             * Deletes a file from the collection.
             *
             * @method deleteFile
             * @param file
             * @return {Object}
             */
            deleteFile: function(file) {
                $ember.set(file, 'deleted', true);
                return file;
            },

            /**
             * Clears all of the files from the collection.
             *
             * @method clearAllFiles
             * @return {void}
             */
            clearAllFiles: function() {
                $ember.set(this, 'files', []);
            },

            /**
             * Aborts the current upload
             *
             * @method abortUpload
             * @return {Boolean} returns true if it aborted successfully, return false if there are no files to upload.
             */
            abortUpload: function() {
              var jqXhr = $ember.get(this, 'lastJqXhr');

              if (jqXhr && $ember.get(this, 'uploadStatus.uploading')) {
                jqXhr.abort();
                $ember.set(this, 'uploadStatus.uploading', false);
              }
            },

            /**
             * Uploads all of the files that haven't been uploaded yet, but are valid files.
             *
             * @method uploadAllFiles
             * @return {Object|Boolean} jQuery promise, or false if there are no files to upload.
             */
            uploadAllFiles: function() {

                /**
                 * @property defaultOptions
                 * @type {Object}
                 */
                var defaultOptions = {
                    fileSizeHeader: true,
                    useArray: true
                };

                if ($ember.get(this, 'validFiles').length === 0) {
                    // Determine if there are even files to upload.
                    return false;
                }

                // Find the URL, set the uploading status, and create our promise.
                var url             = $ember.get(this, 'dropletUrl'),
                    options         = $ember.get(this, 'dropletOptions') || defaultOptions,
                    postData        = this.get('postData'),
                    requestHeaders  = this.get('requestHeaders');

                $ember.set(this, 'uploadStatus.uploading', true);
                $ember.set(this, 'uploadStatus.error', false);

                // Assert that we have the URL specified in the controller that implements the mixin.
                $ember.assert('You must specify the `dropletUrl` parameter in order to upload files.', !!url);

                // Create a new form data instance.
                var formData = new $window.FormData();

                // Node.js is clever enough to deduce an array of images, whereas Ruby/PHP require the
                // specifying of an array-like name.
                var fieldName = options.useArray ? 'file[]' : 'file';

                // Iterate over each file, and append it to the form data.
                $ember.EnumerableUtils.forEach($ember.get(this, 'validFiles'), function(file) {
                    formData.append(fieldName, file.file);
                }, this);

                // Add any extra POST data specified in the controller
                for (var index in postData) {
                    if (postData.hasOwnProperty(index)) {
                        formData.append(index, postData[index]);
                    }
                }

                var headers = {};

                if (options.fileSizeHeader) {

                    // Set the request size, and then we can upload the files!
                    headers['X-File-Size'] = this._getSize();

                }

                // Assign any request headers specified in the controller.
                for (index in requestHeaders) {
                    if ((requestHeaders.hasOwnProperty(index)) || (index in requestHeaders)) {
                        headers[index] = requestHeaders[index];
                    }
                }

                var jqXhr = $jQuery.ajax({
                    url: url,
                    method: 'post',
                    data: formData,
                    headers: headers,
                    processData: false,
                    contentType: false,

                    xhr: function() {
                        var xhr = $jQuery.ajaxSettings.xhr();
                        // Add all of the event listeners.
                        this._addProgressListener(xhr.upload);
                        this._addSuccessListener(xhr.upload);
                        this._addErrorListener(xhr.upload);
                        $ember.set(this, 'lastRequest', xhr);
                        return xhr;
                    }.bind(this)
                });

                $ember.set(this, 'lastJqXhr', jqXhr);

                // Return the promise.
                return new Ember.RSVP.Promise(function(resolve, reject) {
                  jqXhr.done(resolve).fail(reject);
                })
                .then($ember.run.bind(this, function(response) {
                    // Invoke the `didUploadFiles` callback if it exists.
                    $ember.tryInvoke(this, 'didUploadFiles', [response]);

                    return response;
                }));
            }

        },

        /**
         * Clears the request event handlers and cancels the upload
         *
         * @property willDestroy
         * @return {void}
         */
        willDestroy: function() {
          this._super.apply(this, arguments);

          var lastRequest = this.get('lastRequest');

          if (lastRequest) {
            lastRequest.upload.onprogress = undefined;
            lastRequest.upload.onload = undefined;
            lastRequest.upload.onerror = undefined;
            this.send('abortUpload');
          }
        },

        /**
         * Finds a list of files that aren't deleted, and are of a valid MIME type.
         *
         * @property validFiles
         * @return {Array}
         */
        validFiles: $ember.computed(function() {
            return this._filesByProperties({ valid: true, deleted: false, uploaded: false });
        }).property('files.length', 'files.@each.deleted', 'files.@each.uploaded'),

        /**
         * Finds a list of files that have an unsupported MIME type.
         *
         * @property invalidFiles
         * @return {Array}
         */
        invalidFiles: $ember.computed(function() {
            return this._filesByProperties({ valid: false });
        }).property('files.length', 'files.@each.deleted'),

        /**
         * Finds a list of files that have been successfully uploaded.
         *
         * @property uploadedFiles
         * @return {Array}
         */
        uploadedFiles: $ember.computed(function() {
            return this._filesByProperties({ uploaded: true });
        }).property('files.length', 'files.@each.uploaded'),

        /**
         * Finds a list of files that have been deleted by the user.
         *
         * @property deletedFiles
         * @return {Array}
         */
        deletedFiles: $ember.computed(function() {
            return this._filesByProperties({ deleted: true });
        }).property('files.length', 'files.@each.deleted'),

        /**
         * Accepts a map of properties that each file must have.
         *
         * @method _filesByProperties
         * @param maps {Object}
         * @return {Array}
         * @private
         */
        _filesByProperties: function(maps) {

            // Iterate over each of the files.
            return $ember.get(this, 'files').filter(function(file) {

                for (var property in maps) {

                    if ((maps.hasOwnProperty(property)) || (property in maps)) {

                        // If the current property doesn't match what we're after from the map,
                        // then the file is invalid.
                        if (file[property] !== maps[property]) {
                            return false;
                        }

                    }

                }

                // Voila! We have a good file that matches our criteria.
                return true;

            });

        },

        /**
         * Determine the size of the request.
         *
         * @method _getSize
         * @return {Number}
         * @private
         */
        _getSize: function() {

            var size = 0;

            // Iterate over all of the files to determine the size of all valid files.
            $ember.EnumerableUtils.forEach($ember.get(this, 'validFiles'), function(file) {
                size += file.file.size;
            });

            return size;

        },

        /**
         * @method _addSuccessListener
         * @param request
         * @private
         */
        _addSuccessListener: function(request) {

            // Once the files have been successfully uploaded.
            request.onload = $ember.run.bind(this, function() {
                // Set the `uploaded` parameter to true once we've successfully // uploaded the files.
                $ember.EnumerableUtils.forEach($ember.get(this, 'validFiles'), function(file) {
                    $ember.set(file, 'uploaded', true);
                });

                // We want to revert the upload status.
                $ember.set(this, 'uploadStatus.uploading', false);
            });

        },

        /**
         * @method _addErrorListener
         * @param request
         * @return {void}
         * @private
         */
        _addErrorListener: function(request) {

            request.onerror = $ember.run.bind(this, function() {
                // As an error occurred, we need to revert everything.
                $ember.set(this, 'uploadStatus.uploading', false);
                $ember.set(this, 'uploadStatus.error', true);
            });

        },

        /**
         * @method _addProgressListener
         * @param request
         * @return {void}
         * @private
         */
        _addProgressListener: function(request) {

            request.onprogress = $ember.run.bind(this, function(event) {
                if (!event.lengthComputable) {
                    // There's not much we can do if the request is not computable.
                    return;
                }

                // Calculate the percentage remaining.
                var percentageLoaded = (event.loaded / this._getSize()) * 100;
                $ember.set(this, 'uploadStatus.percentComplete', Math.round(percentageLoaded));
            });

        },

        /**
         * Adds a file based on whether it's valid or invalid.
         *
         * @method _addFile
         * @param file {File}
         * @param valid {Boolean}
         * @return {Object}
         * @private
         */
        _addFile: function(file, valid) {

            // Extract the file's extension which allows us to style accordingly.
            var fileExt = file.name.substr((~-file.name.lastIndexOf(".") >>> 0) + 2);
            var className = 'extension-%@'.fmt(fileExt).toLowerCase();

            // Create the record with its default parameters, and then add it to the collection.
            var record = { file: file, valid: valid, uploaded: false, deleted: false, className: className };
            $ember.get(this, 'files').pushObject(record);

            // Voila!
            return record;

        }

    });

})(window, window.Ember, window.jQuery);
<commit_msg>Cleaned up code<commit_after>(function($window, $ember, $jQuery) {

    "use strict";

    /**
     * @module App
     * @class EmberDropletController
     * @type Ember.Mixin
     * @extends Ember.Mixin
     */
    $window.DropletController = $ember.Mixin.create({

        /**
         * @property mimeTypes
         * @type {Array}
         */
        mimeTypes: ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'text/plain'],

        /**
         * @property extensions
         * @type {Array}
         */
        extensions: ['jpeg', 'jpg', 'gif', 'png'],

        /**
         * Contains a list of headers to be included in the request made by
         * uploadAllFiles()
         *
         * @property requestHeaders
         * @type {Object}
         */
        requestHeaders: {},

        /**
         * Contains a dictionary of extra POST data to be included in the
         * request made by uploadAllFiles()
         *
         * @property postData
         * @type {Object}
         */
        postData: {},

        /**
         * Contains a list of files, both valid, deleted, and invalid.
         *
         * @property files
         * @type {Array}
         * @default []
         */
        files: [],

        /**
         * @property uploadStatus
         * @type {Object}
         */
        uploadStatus: $ember.computed(function() {
            return { uploading: false, percentComplete: 0, error: false };
        }),

        /**
         * Clears the file array for each instantiation.
         *
         * @constructor
         * @method init
         * @return {void}
         */
        init: function() {
            $ember.set(this, 'files', []);
            this._super();
        },

        /**
         * @property actions
         * @type {Object}
         */
        actions: {

            /**
             * Adds a valid file to the collection.
             *
             * @method addValidFile
             * @param file {File}
             * @return {Object}
             */
            addValidFile: function(file) {
                return this._addFile(file, true);
            },

            /**
             * Adds an invalid file to the collection.
             *
             * @method addInvalidFile
             * @param file {File}
             * @return {Object}
             */
            addInvalidFile: function(file) {
                return this._addFile(file, false);
            },

            /**
             * Deletes a file from the collection.
             *
             * @method deleteFile
             * @param file
             * @return {Object}
             */
            deleteFile: function(file) {
                $ember.set(file, 'deleted', true);
                return file;
            },

            /**
             * Clears all of the files from the collection.
             *
             * @method clearAllFiles
             * @return {void}
             */
            clearAllFiles: function() {
                $ember.set(this, 'files', []);
            },

            /**
             * Aborts the current upload
             *
             * @method abortUpload
             * @return {Boolean} returns true if it aborted successfully, return false if there are no files to upload.
             */
            abortUpload: function() {
              var jqXhr = $ember.get(this, 'lastJqXhr');

              if (jqXhr && $ember.get(this, 'uploadStatus.uploading')) {
                jqXhr.abort();
                $ember.set(this, 'uploadStatus.uploading', false);
              }
            },

            /**
             * Uploads all of the files that haven't been uploaded yet, but are valid files.
             *
             * @method uploadAllFiles
             * @return {Object|Boolean} jQuery promise, or false if there are no files to upload.
             */
            uploadAllFiles: function() {

                /**
                 * @property defaultOptions
                 * @type {Object}
                 */
                var defaultOptions = {
                    fileSizeHeader: true,
                    useArray: true
                };

                if ($ember.get(this, 'validFiles').length === 0) {
                    // Determine if there are even files to upload.
                    return false;
                }

                // Find the URL, set the uploading status, and create our promise.
                var url             = $ember.get(this, 'dropletUrl'),
                    options         = $ember.get(this, 'dropletOptions') || defaultOptions,
                    postData        = this.get('postData'),
                    requestHeaders  = this.get('requestHeaders');

                $ember.set(this, 'uploadStatus.uploading', true);
                $ember.set(this, 'uploadStatus.error', false);

                // Assert that we have the URL specified in the controller that implements the mixin.
                $ember.assert('You must specify the `dropletUrl` parameter in order to upload files.', !!url);

                // Create a new form data instance.
                var formData = new $window.FormData();

                // Node.js is clever enough to deduce an array of images, whereas Ruby/PHP require the
                // specifying of an array-like name.
                var fieldName = options.useArray ? 'file[]' : 'file';

                // Iterate over each file, and append it to the form data.
                $ember.EnumerableUtils.forEach($ember.get(this, 'validFiles'), function(file) {
                    formData.append(fieldName, file.file);
                }, this);

                // Add any extra POST data specified in the controller
                for (var index in postData) {
                    if (postData.hasOwnProperty(index)) {
                        formData.append(index, postData[index]);
                    }
                }

                var headers = {};

                if (options.fileSizeHeader) {

                    // Set the request size, and then we can upload the files!
                    headers['X-File-Size'] = this._getSize();

                }

                // Assign any request headers specified in the controller.
                for (index in requestHeaders) {

                    if ((requestHeaders.hasOwnProperty(index)) || (index in requestHeaders)) {
                        headers[index] = requestHeaders[index];
                    }

                }

                var jqXhr = $jQuery.ajax({
                    url: url,
                    method: 'post',
                    data: formData,
                    headers: headers,
                    processData: false,
                    contentType: false,

                    xhr: function xhr() {

                        var xhr = $jQuery.ajaxSettings.xhr();

                        // Add all of the event listeners.
                        this._addProgressListener(xhr.upload);
                        this._addSuccessListener(xhr.upload);
                        this._addErrorListener(xhr.upload);
                        $ember.set(this, 'lastRequest', xhr);

                        return xhr;

                    }.bind(this)
                });

                $ember.set(this, 'lastJqXhr', jqXhr);

                // Return the promise.
                return new $ember.RSVP.Promise(function(resolve, reject) {

                  jqXhr.done(resolve).fail(reject);

                }).then($ember.run.bind(this, function(response) {

                    // Invoke the `didUploadFiles` callback if it exists.
                    $ember.tryInvoke(this, 'didUploadFiles', [response]);
                    return response;

                }));
            }

        },

        /**
         * Clears the request event handlers and cancels the upload
         *
         * @property willDestroy
         * @return {void}
         */
        willDestroy: function willDestroy() {

            this._super.apply(this, arguments);
            var lastRequest = this.get('lastRequest');

            if (lastRequest) {
                lastRequest.upload.onprogress = undefined;
                lastRequest.upload.onload = undefined;
                lastRequest.upload.onerror = undefined;
                this.send('abortUpload');
            }

        },

        /**
         * Finds a list of files that aren't deleted, and are of a valid MIME type.
         *
         * @property validFiles
         * @return {Array}
         */
        validFiles: $ember.computed(function() {
            return this._filesByProperties({ valid: true, deleted: false, uploaded: false });
        }).property('files.length', 'files.@each.deleted', 'files.@each.uploaded'),

        /**
         * Finds a list of files that have an unsupported MIME type.
         *
         * @property invalidFiles
         * @return {Array}
         */
        invalidFiles: $ember.computed(function() {
            return this._filesByProperties({ valid: false });
        }).property('files.length', 'files.@each.deleted'),

        /**
         * Finds a list of files that have been successfully uploaded.
         *
         * @property uploadedFiles
         * @return {Array}
         */
        uploadedFiles: $ember.computed(function() {
            return this._filesByProperties({ uploaded: true });
        }).property('files.length', 'files.@each.uploaded'),

        /**
         * Finds a list of files that have been deleted by the user.
         *
         * @property deletedFiles
         * @return {Array}
         */
        deletedFiles: $ember.computed(function() {
            return this._filesByProperties({ deleted: true });
        }).property('files.length', 'files.@each.deleted'),

        /**
         * Accepts a map of properties that each file must have.
         *
         * @method _filesByProperties
         * @param maps {Object}
         * @return {Array}
         * @private
         */
        _filesByProperties: function(maps) {

            // Iterate over each of the files.
            return $ember.get(this, 'files').filter(function(file) {

                for (var property in maps) {

                    if ((maps.hasOwnProperty(property)) || (property in maps)) {

                        // If the current property doesn't match what we're after from the map,
                        // then the file is invalid.
                        if (file[property] !== maps[property]) {
                            return false;
                        }

                    }

                }

                // Voila! We have a good file that matches our criteria.
                return true;

            });

        },

        /**
         * Determine the size of the request.
         *
         * @method _getSize
         * @return {Number}
         * @private
         */
        _getSize: function() {

            var size = 0;

            // Iterate over all of the files to determine the size of all valid files.
            $ember.EnumerableUtils.forEach($ember.get(this, 'validFiles'), function(file) {
                size += file.file.size;
            });

            return size;

        },

        /**
         * @method _addSuccessListener
         * @param request
         * @private
         */
        _addSuccessListener: function(request) {

            // Once the files have been successfully uploaded.
            request.onload = $ember.run.bind(this, function() {
                // Set the `uploaded` parameter to true once we've successfully // uploaded the files.
                $ember.EnumerableUtils.forEach($ember.get(this, 'validFiles'), function(file) {
                    $ember.set(file, 'uploaded', true);
                });

                // We want to revert the upload status.
                $ember.set(this, 'uploadStatus.uploading', false);
            });

        },

        /**
         * @method _addErrorListener
         * @param request
         * @return {void}
         * @private
         */
        _addErrorListener: function(request) {

            request.onerror = $ember.run.bind(this, function() {
                // As an error occurred, we need to revert everything.
                $ember.set(this, 'uploadStatus.uploading', false);
                $ember.set(this, 'uploadStatus.error', true);
            });

        },

        /**
         * @method _addProgressListener
         * @param request
         * @return {void}
         * @private
         */
        _addProgressListener: function(request) {

            request.onprogress = $ember.run.bind(this, function(event) {
                if (!event.lengthComputable) {
                    // There's not much we can do if the request is not computable.
                    return;
                }

                // Calculate the percentage remaining.
                var percentageLoaded = (event.loaded / this._getSize()) * 100;
                $ember.set(this, 'uploadStatus.percentComplete', Math.round(percentageLoaded));
            });

        },

        /**
         * Adds a file based on whether it's valid or invalid.
         *
         * @method _addFile
         * @param file {File}
         * @param valid {Boolean}
         * @return {Object}
         * @private
         */
        _addFile: function(file, valid) {

            // Extract the file's extension which allows us to style accordingly.
            var fileExt   = file.name.substr((~-file.name.lastIndexOf(".") >>> 0) + 2),
                className = 'extension-%@'.fmt(fileExt).toLowerCase();

            // Create the record with its default parameters, and then add it to the collection.
            var record = { file: file, valid: valid, uploaded: false, deleted: false, className: className };
            $ember.get(this, 'files').pushObject(record);

            // Voila!
            return record;

        }

    });

})(window, window.Ember, window.jQuery);
<|endoftext|>


<commit_before>var applicationMock;
var ApplicationMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.registrations = [];
    this.injections = [];
  },
  register: function(name, factory, options) {
    this.registrations.push({
      name:    name,
      factory: factory,
      options: options
    });
  },
  inject: function(target, property, name) {
    var registration = Ember.$.grep(this.registrations, function(registration, i) {
      return registration.name === name;
    })[0];
    if (registration) {
      this.injections.push({
        target:   target,
        property: property,
        object:   registration.factory
      });
    }
  }
});

var applicationRouteMock;
var ApplicationRouteMock = Ember.Object.extend({
  send: function() {
  }
});

var containerMock;
var ContainerMock = Ember.Object.extend({
  lookup: function(name) {
    return applicationRouteMock;
  }
});

var XhrMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.requestHeaders = {};
  },
  setRequestHeader: function(name, value) {
    this.requestHeaders[name] = value;
  }
});

var registeredAjaxPrefilter;
var ajaxPrefilterMock = function(prefilter) {
  registeredAjaxPrefilter = prefilter;
};

module('Ember.SimpleAuth', {
  originalAjaxPrefilter: Ember.$.ajaxPrefilter,
  setup: function() {
    Ember.$.ajaxPrefilter   = ajaxPrefilterMock;
    registeredAjaxPrefilter = undefined;
    applicationMock         = ApplicationMock.create();
    applicationRouteMock    = ApplicationRouteMock.create();
    containerMock           = ContainerMock.create();
  },
  teardown: function() {
    Ember.$.ajaxPrefilter = this.originalAjaxPrefilter;
  }
});

test('saves serverSessionRoute if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { serverSessionRoute: '/route' });

  equal(Ember.SimpleAuth.serverSessionRoute, '/route', 'Ember.SimpleAuth saves serverSessionRoute when specified.');
});

test('saves routeAfterLogin if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogin: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogin, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogin when specified.');
});

test('saves routeAfterLogout if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogout: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogout, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogout when specified.');
});

test('saves loginRoute if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { loginRoute: 'somewhere' });

  equal(Ember.SimpleAuth.loginRoute, 'somewhere', 'Ember.SimpleAuth saves loginRoute when specified.');
});

test('saves logoutRoute if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { logoutRoute: 'somewhere' });

  equal(Ember.SimpleAuth.logoutRoute, 'somewhere', 'Ember.SimpleAuth saves logutRoute when specified.');
});

test('injects a session object in models, views, controllers and routes', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  Ember.$.each(['model', 'view', 'controller', 'view'], function(i, component) {
    var injection = Ember.$.grep(applicationMock.injections, function(injection) {
      return injection.target === component;
    })[0];

    equal(injection.property, 'session', 'Ember.SimpleAuth injects a session into ' + component + '.');
    equal(injection.object.constructor, Ember.SimpleAuth.Session, 'Ember.SimpleAuth injects a session into ' + component + '.');
  });
});

test('registers an AJAX prefilter that adds the authToken for non-crossdomain requests', function() {
  var xhrMock = XhrMock.create();
  var token = Math.random().toString(36);
  sessionStorage.authToken = token;
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], 'Token token="' + token + '"', 'Ember.SimpleAuth registers an AJAX prefilter that adds the authToken for non-crossdomain requests.');

  xhrMock = XhrMock.create();
  xhrMock.crossDomain = true;
  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], undefined, 'Ember.SimpleAuth registers an AJAX prefilter that does not add the authToken for crossdomain requests.');
});
<commit_msg>better test names<commit_after>var applicationMock;
var ApplicationMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.registrations = [];
    this.injections = [];
  },
  register: function(name, factory, options) {
    this.registrations.push({
      name:    name,
      factory: factory,
      options: options
    });
  },
  inject: function(target, property, name) {
    var registration = Ember.$.grep(this.registrations, function(registration, i) {
      return registration.name === name;
    })[0];
    if (registration) {
      this.injections.push({
        target:   target,
        property: property,
        object:   registration.factory
      });
    }
  }
});

var applicationRouteMock;
var ApplicationRouteMock = Ember.Object.extend({
  send: function() {
  }
});

var containerMock;
var ContainerMock = Ember.Object.extend({
  lookup: function(name) {
    return applicationRouteMock;
  }
});

var XhrMock = Ember.Object.extend({
  init: function() {
    this._super();
    this.requestHeaders = {};
  },
  setRequestHeader: function(name, value) {
    this.requestHeaders[name] = value;
  }
});

var registeredAjaxPrefilter;
var ajaxPrefilterMock = function(prefilter) {
  registeredAjaxPrefilter = prefilter;
};

module('Ember.SimpleAuth', {
  originalAjaxPrefilter: Ember.$.ajaxPrefilter,
  setup: function() {
    Ember.$.ajaxPrefilter   = ajaxPrefilterMock;
    registeredAjaxPrefilter = undefined;
    applicationMock         = ApplicationMock.create();
    applicationRouteMock    = ApplicationRouteMock.create();
    containerMock           = ContainerMock.create();
  },
  teardown: function() {
    Ember.$.ajaxPrefilter = this.originalAjaxPrefilter;
  }
});

test('.setup saves serverSessionRoute if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { serverSessionRoute: '/route' });

  equal(Ember.SimpleAuth.serverSessionRoute, '/route', 'Ember.SimpleAuth saves serverSessionRoute when specified.');
});

test('.setup saves routeAfterLogin if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogin: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogin, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogin when specified.');
});

test('.setup saves routeAfterLogout if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { routeAfterLogout: 'somewhere' });

  equal(Ember.SimpleAuth.routeAfterLogout, 'somewhere', 'Ember.SimpleAuth saves routeAfterLogout when specified.');
});

test('.setup saves loginRoute if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { loginRoute: 'somewhere' });

  equal(Ember.SimpleAuth.loginRoute, 'somewhere', 'Ember.SimpleAuth saves loginRoute when specified.');
});

test('.setup saves logoutRoute if specified', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock, { logoutRoute: 'somewhere' });

  equal(Ember.SimpleAuth.logoutRoute, 'somewhere', 'Ember.SimpleAuth saves logutRoute when specified.');
});

test('.setup injects a session object in models, views, controllers and routes', function() {
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  Ember.$.each(['model', 'view', 'controller', 'view'], function(i, component) {
    var injection = Ember.$.grep(applicationMock.injections, function(injection) {
      return injection.target === component;
    })[0];

    equal(injection.property, 'session', 'Ember.SimpleAuth injects a session into ' + component + '.');
    equal(injection.object.constructor, Ember.SimpleAuth.Session, 'Ember.SimpleAuth injects a session into ' + component + '.');
  });
});

test('.setup registers an AJAX prefilter that adds the authToken for non-crossdomain requests', function() {
  var xhrMock = XhrMock.create();
  var token = Math.random().toString(36);
  sessionStorage.authToken = token;
  Ember.SimpleAuth.setup(containerMock, applicationMock);

  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], 'Token token="' + token + '"', 'Ember.SimpleAuth registers an AJAX prefilter that adds the authToken for non-crossdomain requests.');

  xhrMock = XhrMock.create();
  xhrMock.crossDomain = true;
  registeredAjaxPrefilter({}, {}, xhrMock);
  equal(xhrMock.requestHeaders['Authorization'], undefined, 'Ember.SimpleAuth registers an AJAX prefilter that does not add the authToken for crossdomain requests.');
});
<|endoftext|>


<commit_before>Tickets = function(){
  this.calendar = function(month, year, data) {
    if ( typeof(month) === 'object' ) {
      data = month;
      month = null;
    }
    this.current_date = new Date();
    this.day_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    this.month_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    this.month = (isNaN(month) || month === null) ? this.current_date.getMonth() : month;
    this.year = (isNaN(year) || year === null) ? this.current_date.getFullYear() : year;
    this.draw = function(ele){
        // get dates
        var startingDay = new Date(this.year, this.month, 1).getDay(),
        endingDate = new Date(this.year, this.month + 1, 0),
        monthLength = endingDate.getDate(),
        inLastRow = 6 - endingDate.getDay();
        if (this.month > 11) {
          this.month -= 12;
          this.year += 1;
        } else if (this.month < 0) {
          this.month += 12;
          this.year -= 1;
        }

        // generate header
        this.table = document.createElement('table');
        this.head = document.createElement('thead');
        this.prev = document.createElement('th');
        this.next = document.createElement('th');
        this.title = document.createElement('th');
        this.days = document.createElement('tr');
        this.body = document.createElement('tbody');
        this.cells = '';
        this.table.setAttribute('class', 'calendar');
        this.table.appendChild(this.head);
        this.head.appendChild(this.prev);
        this.prev.innerHTML = "«";
        this.prev.id = 'prev';
        this.head.appendChild(this.title);
        this.head.appendChild(this.next);
        this.next.innerHTML = "»";
        this.next.id = 'next';
        this.table.appendChild(this.days);
        this.title.innerHTML = this.month_labels[this.month] + " " + this.year;
        this.title.setAttribute('colspan', '5');
        this.days.setAttribute('class', 'header');
        for (var i = 0; i <= 6; i++ ) this.cells += '' + this.day_labels[i] + '	';
        this.days.innerHTML = this.cells;

        //generate calendar
        var html = '
';
        if ( startingDay ) html += '	';
        for (var day = 1; day <= monthLength; day++) {
        html += '
' + day + '
';
        //if data argument present, append key value for current day
        if (data) {
          var today = (this.month+1)+'/'+day+'/'+this.year;
          if (data[today]) {
            html += '
'+Object.keys(data[today]).length+' '+data.type+'
';
            html += '
<button class="btn btn-primary" onclick="db.Tickets.showTickets(db.Tickets.sortTickets()[\''+today+'\']);">Show Tickets</button>
';
          }
        }
        html += '	';
        if ( (day + startingDay) % 7 === 0 && day != monthLength ) html += '

';
        }
        if ( inLastRow ) html += '	';
        html += '
';
        this.table.innerHTML += html;
        if (ele) {
          ele.innerHTML = this.table.outerHTML;
        } else {
          return this.table.outerHTML;
        }
        // save reference to dom node in object
        this.node = ele;
        // save reference to calendar object for enclosure scope
        var cal = this;
            (function(){
          // save calendar object reference for listeners
          var self = this;
          self.prev.addEventListener('click', function(){
            cal.month--;
            cal.draw(cal.node);
          });
          self.next.addEventListener('click', function(){
            cal.month++;
            cal.draw(cal.node);
          });
          document.onkeydown = function(e) {
            e = e || window.event;
              if (e.keyCode == '37') {
                // left arrow
                cal.month--;
                cal.draw(cal.node);
              } else if (e.keyCode == '39') {
                // right arrow
                cal.month++;
                cal.draw(cal.node);
              }
          };
        })();
      };
  };
  this.getTickets = function() {
    //get tickets
    if (self.app.contentViewModel() !== undefined){
      if (typeof(self.app.contentViewModel().myTickets) === "function"){
        self.Tickets.ticketArray = self.app.contentViewModel().myTickets();
      }
    } else if (localStorage.getItem('ticketCache') !== null){
      self.Tickets.ticketArray = JSON.parse(localStorage.getItem('ticketCache'));
    }
    //return results
    if (self.Tickets.ticketArray) {
      localStorage.setItem('ticketCache', JSON.stringify(self.Tickets.ticketArray));
      return self.Tickets.ticketArray;
    } else {
      alert('Unable to access tickets at this time!');
      return [];
    }
  };
  this.getCritical = function() {
    var tickets = this.getTickets(),
    critical = [];
    for (var i = 0; i < tickets.length; i++) {
      if (tickets[i].ScheduledEndDate < new Date()) {
        critical.push(tickets[i]);
      }
    }
    if (tickets.length > 0){
      return critical;
    } else {
      return false;
    }
  };
  this.countCritical = function() {
    var criticals = self.Tickets.getCritical();
    if (criticals) {
      return 'Critical Tickets: ' + criticals.length + '';
    } else {
      return 'Error loading tickets!';
    }
  };
  this.sortTickets = function(tickets){
    if (! tickets){
      tickets = this.getTickets();
    }
    var data = {type: 'Tickets'};
    for (var i=0;i<tickets.length;i++){
      var ticket = tickets[i],
      date = new Date(ticket.ScheduledEndDate),
      day = (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
      if (! data[day]){ data[day] = [];}
      data[day].push(ticket);
    }
    return data;
  };
  this.listTickets = function(tickets){
    var list = document.createElement('table'),
    head = list.appendChild(document.createElement('tr'));
    head.innerHTML = 'Business Name	Ticket Type	Due Date	';
    for (var i=0;i<tickets.length;i++){
      var ticket = tickets[i],
      listItem = document.createElement('tr'),
      content = ''+ticket.CompanyName+'	'+ticket.TicketTypeName+'	';
      content += ''+(ticket.ScheduledEndDate.getMonth()+1);
      content += '/'+ticket.ScheduledEndDate.getDate()+'/';
      content += ticket.ScheduledEndDate.getFullYear()+'	';
      listItem.innerHTML = content;
      listItem.setAttribute('data-client', ticket.CustomerId);
      listItem.onclick = function(){
        self.Tools.openClient(this.dataset.client);
        var modals = document.getElementsByClassName('bootbox-close-button');
        for (var i=0;i<modals.length;i++){modals[i].click();}
      };
      list.appendChild(listItem);
    }
    return list;
  };
  this.showTickets = function(tickets){
    bootbox.dialog({
      message: self.Tickets.listTickets(tickets),
      title: "Tickets (click row to open client)",
      className: "ticket-list",
      buttons: {},
    });
  };
  this.tryCache = function(){
    try {
      if (self.Tickets.ticketArray) {
        localStorage.setItem('ticketCache', JSON.stringify(self.Tickets.ticketArray));
      }
    } catch(err) {
      setTimeout(function(){self.Tickets.tryCache();}, 1000);
    }
  };
};
<commit_msg>Update tickets.js<commit_after>Tickets = function(){
  this.calendar = function(month, year, data) {
    if ( typeof(month) === 'object' ) {
      data = month;
      month = null;
    }
    this.current_date = new Date();
    this.day_labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    this.month_labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    this.month = (isNaN(month) || month === null) ? this.current_date.getMonth() : month;
    this.year = (isNaN(year) || year === null) ? this.current_date.getFullYear() : year;
    this.draw = function(ele){
        // get dates
        var startingDay = new Date(this.year, this.month, 1).getDay(),
        endingDate = new Date(this.year, this.month + 1, 0),
        monthLength = endingDate.getDate(),
        inLastRow = 6 - endingDate.getDay();
        if (this.month > 11) {
          this.month -= 12;
          this.year += 1;
        } else if (this.month < 0) {
          this.month += 12;
          this.year -= 1;
        }

        // generate header
        this.table = document.createElement('table');
        this.head = document.createElement('thead');
        this.prev = document.createElement('th');
        this.next = document.createElement('th');
        this.title = document.createElement('th');
        this.days = document.createElement('tr');
        this.body = document.createElement('tbody');
        this.cells = '';
        this.table.setAttribute('class', 'calendar');
        this.table.appendChild(this.head);
        this.head.appendChild(this.prev);
        this.prev.innerHTML = "«";
        this.prev.id = 'prev';
        this.head.appendChild(this.title);
        this.head.appendChild(this.next);
        this.next.innerHTML = "»";
        this.next.id = 'next';
        this.table.appendChild(this.days);
        this.title.innerHTML = this.month_labels[this.month] + " " + this.year;
        this.title.setAttribute('colspan', '5');
        this.days.setAttribute('class', 'header');
        for (var i = 0; i <= 6; i++ ) this.cells += '' + this.day_labels[i] + '	';
        this.days.innerHTML = this.cells;

        //generate calendar
        var html = '
';
        if ( startingDay ) html += '	';
        for (var day = 1; day <= monthLength; day++) {
        html += '
' + day + '
';
        //if data argument present, append key value for current day
        if (data) {
          var today = (this.month+1)+'/'+day+'/'+this.year;
          if (data[today]) {
            html += '
'+Object.keys(data[today]).length+' '+data.type+'
';
            html += '
<button class="btn btn-primary" onclick="db.Tickets.showTickets(db.Tickets.sortTickets()[\''+today+'\']);">Show Tickets</button>
';
          }
        }
        html += '	';
        if ( (day + startingDay) % 7 === 0 && day != monthLength ) html += '

';
        }
        if ( inLastRow ) html += '	';
        html += '
';
        this.table.innerHTML += html;
        if (ele) {
          ele.innerHTML = this.table.outerHTML;
        } else {
          return this.table.outerHTML;
        }
        // save reference to dom node in object
        this.node = ele;
        // save reference to calendar object for enclosure scope
        var cal = this;
            (function(){
          // save calendar object reference for listeners
          var self = this;
          self.prev.addEventListener('click', function(){
            cal.month--;
            cal.draw(cal.node);
          });
          self.next.addEventListener('click', function(){
            cal.month++;
            cal.draw(cal.node);
          });
          document.onkeydown = function(e) {
            e = e || window.event;
              if (e.keyCode == '37') {
                // left arrow
                cal.month--;
                cal.draw(cal.node);
              } else if (e.keyCode == '39') {
                // right arrow
                cal.month++;
                cal.draw(cal.node);
              }
          };
        })();
      };
  };
  this.getTickets = function() {
    //get tickets
    if (app.contentViewModel() !== undefined){
      if (typeof(app.contentViewModel().myTickets) === "function"){
        self.Tickets.ticketArray = app.contentViewModel().myTickets();
      }
    } else if (localStorage.getItem('ticketCache') !== null){
      self.Tickets.ticketArray = JSON.parse(localStorage.getItem('ticketCache'));
    }
    //return results
    if (self.Tickets.ticketArray) {
      localStorage.setItem('ticketCache', JSON.stringify(self.Tickets.ticketArray));
      return self.Tickets.ticketArray;
    } else {
      alert('Unable to access tickets at this time!');
      return [];
    }
  };
  this.getCritical = function() {
    var tickets = this.getTickets(),
    critical = [];
    for (var i = 0; i < tickets.length; i++) {
      if (tickets[i].ScheduledEndDate < new Date()) {
        critical.push(tickets[i]);
      }
    }
    if (tickets.length > 0){
      return critical;
    } else {
      return false;
    }
  };
  this.countCritical = function() {
    var criticals = self.Tickets.getCritical();
    if (criticals) {
      return 'Critical Tickets: ' + criticals.length + '';
    } else {
      return 'Error loading tickets!';
    }
  };
  this.sortTickets = function(tickets){
    if (! tickets){
      tickets = this.getTickets();
    }
    var data = {type: 'Tickets'};
    for (var i=0;i<tickets.length;i++){
      var ticket = tickets[i],
      date = new Date(ticket.ScheduledEndDate),
      day = (date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear();
      if (! data[day]){ data[day] = [];}
      data[day].push(ticket);
    }
    return data;
  };
  this.listTickets = function(tickets){
    var list = document.createElement('table'),
    head = list.appendChild(document.createElement('tr'));
    head.innerHTML = 'Business Name	Ticket Type	Due Date	';
    for (var i=0;i<tickets.length;i++){
      var ticket = tickets[i],
      listItem = document.createElement('tr'),
      content = ''+ticket.CompanyName+'	'+ticket.TicketTypeName+'	';
      content += ''+(ticket.ScheduledEndDate.getMonth()+1);
      content += '/'+ticket.ScheduledEndDate.getDate()+'/';
      content += ticket.ScheduledEndDate.getFullYear()+'	';
      listItem.innerHTML = content;
      listItem.setAttribute('data-client', ticket.CustomerId);
      listItem.onclick = function(){
        self.Tools.openClient(this.dataset.client);
        var modals = document.getElementsByClassName('bootbox-close-button');
        for (var i=0;i<modals.length;i++){modals[i].click();}
      };
      list.appendChild(listItem);
    }
    return list;
  };
  this.showTickets = function(tickets){
    bootbox.dialog({
      message: self.Tickets.listTickets(tickets),
      title: "Tickets (click row to open client)",
      className: "ticket-list",
      buttons: {},
    });
  };
  this.tryCache = function(){
    try {
      if (self.Tickets.ticketArray) {
        localStorage.setItem('ticketCache', JSON.stringify(self.Tickets.ticketArray));
      }
    } catch(err) {
      setTimeout(function(){self.Tickets.tryCache();}, 1000);
    }
  };
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Note = mongoose.model('Note'),
    Notifications = mongoose.model('Notification'),
    Comment = mongoose.model('Comment'),
    User = mongoose.model('User'),
    _ = require('lodash');

/**
 * List of notes
 */
exports.all = function(req, res) {
    var q = Comment.find({onNote : req.query.noteId});

    q.sort({ dateCreate : 'desc' }).populate('createBy', 'name username avatar').exec(function(err, comments) {
        if (err) {
            console.log(err);
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(comments);
        }
    });

};

// Get note by id
exports.comment = function(req, res, next, id) {
    Comment.load(id, function(err, comment) {
        if (err) return next(err);
        if (!comment) return next(new Error('Failed to load comment ' + id));
        req.comment = comment;
        next();
    });
};

/**
 * Create a ntoe
 */

 exports.create = function(req, res) {
    var comment = new Comment(req.body);
    comment.createBy = req.user;
    // todo: send to class and member
    comment.save(function(err) {
        if (err) {
            return res.send('users/signup', {
                errors: err.errors,
                comment: comment
            });
        } else {
            // update comment
            res.jsonp(comment);
            // find and pregmatch username from list
            var re = /(@\w+)/gi;
            var found = comment.content.match(re);
            console.log('find username in ' + comment.content);
            console.log(found);
            var userArr =[];
            if(found != undefined && (found instanceof Array))
            {
                for (var i = 0; i < found.length; i++) {
                    userArr[i] = found[i].replace('@','');
                };
                User.find({ username : {'$in': userArr} },'id name username',function(err,users){
                    if (err) {
                        console.error(err)
                    }
                    else
                        for (var i = 0; i < users.length; i++) {
                            userid = users[i]._id;
                            var notify = new Notifications();
                            notify.source = comment;
                            notify.from = req.user;
                            notify.to = userid;
                            notify.type = 'comment';
                            notify.content =  req.user.name + ' has mentioned you on comment.' ;
                            notify.save();
                        };
                })
            }

            Note.load(comment.onNote , function(err, note) {
                if (err) return next(err);
                if (!note) return next(new Error('Failed to load note ' + id));
                var query = Comment.find( {onNote : comment.onNote } );
                    query.count(function(err,totals){
                        if (err) {
                            console.error(err);
                        }
                        else
                        {
                            note.totalComments = totals;

                            // notify to member and owner of note
                            for (var i = 0; i < note.sendToMembers.length; i++) {
                                var userid = note.sendToMembers[i];
                                var notify = new Notifications();
                                notify.source = comment;
                                notify.from = req.user;
                                notify.to = userid;
                                notify.type = 'comment';
                                notify.content =  req.user.name + ' has commented on note "' + note.title + '"' ;
                                notify.save();
                            };

                            note.save();
                        }
                    });
            });

        }
    });
};

exports.show = function(req, res) {
    res.jsonp(req.comment);
};<commit_msg>Debug - comment on note<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Note = mongoose.model('Note'),
    Notifications = mongoose.model('Notification'),
    Comment = mongoose.model('Comment'),
    User = mongoose.model('User'),
    _ = require('lodash');

/**
 * List of notes
 */
exports.all = function(req, res) {
    var q = Comment.find({onNote : req.query.noteId});

    q.sort({ dateCreate : 'desc' }).populate('createBy', 'name username avatar').exec(function(err, comments) {
        if (err) {
            console.log(err);
            res.render('error', {
                status: 500
            });
        } else {
            res.jsonp(comments);
        }
    });

};

// Get note by id
exports.comment = function(req, res, next, id) {
    Comment.load(id, function(err, comment) {
        if (err) return next(err);
        if (!comment) return next(new Error('Failed to load comment ' + id));
        req.comment = comment;
        next();
    });
};

/**
 * Create a ntoe
 */

 exports.create = function(req, res) {
    var comment = new Comment(req.body);
    comment.createBy = req.user;
    // todo: send to class and member
    comment.save(function(err) {
        if (err) {
            return res.send('users/signup', {
                errors: err.errors,
                comment: comment
            });
        } else {
            // update comment
            res.jsonp(comment);
            // find and pregmatch username from list
            var re = /(@\w+)/gi;
            var found = comment.content.match(re);
            console.log('find username in ' + comment.content);
            console.log(found);
            var userArr =[];
            if(found != undefined && (found instanceof Array))
            {
                for (var i = 0; i < found.length; i++) {
                    userArr[i] = found[i].replace('@','');
                };
                User.find({ username : {'$in': userArr} },'id name username',function(err,users){
                    if (err) {
                        console.error(err)
                    }
                    else
                        for (var i = 0; i < users.length; i++) {
                            var userid = users[i]._id;
                            var notify = new Notifications();
                            notify.source = comment;
                            notify.from = req.user;
                            notify.to = userid;
                            notify.type = 'comment';
                            notify.content =  req.user.name + ' has mentioned you on comment.' ;
                            notify.save();
                        };
                })
            }

            Note.load(comment.onNote , function(err, note) {
                if (err) return next(err);
                if (!note) return next(new Error('Failed to load note ' + id));
                var query = Comment.find( {onNote : comment.onNote } );
                    query.count(function(err,totals){
                        if (err) {
                            console.error(err);
                        }
                        else
                        {
                            note.totalComments = totals;

                            // notify to member and owner of note
                            for (var i = 0; i < note.sendToMembers.length; i++) {
                                var userid = note.sendToMembers[i];
                                var notify = new Notifications();
                                notify.source = comment;
                                notify.from = req.user;
                                notify.to = userid;
                                notify.type = 'comment';
                                notify.content =  req.user.name + ' has commented on note "' + note.title + '"' ;
                                notify.save();
                            };

                            note.save();
                        }
                    });
            });

        }
    });
};

exports.show = function(req, res) {
    res.jsonp(req.comment);
};<|endoftext|>


<commit_before>import PublicationUtils from 'meteor/utilities:smart-publications';
import Posts from "meteor/nova:posts";
import Users from 'meteor/nova:users';
import Categories from "./collection.js";

// check if user can create a new post
const canInsert = user => Users.canDo(user, "posts.new");
// check if user can edit a post
const canEdit = Users.canEdit;

Posts.addField(
  {
    fieldName: 'categories',
    fieldSchema: {
      type: [String],
      control: "checkboxgroup",
      optional: true,
      insertableIf: canInsert,
      editableIf: canEdit,
      autoform: {
        noselect: true,
        type: "bootstrap-category",
        order: 50,
        options: function () {
          var categories = Categories.find().map(function (category) {
            return {
              value: category._id,
              label: category.name
            };
          });
          return categories;
        }
      },
      publish: true,
      join: {
        joinAs: "categoriesArray",
        collection: () => Categories
      }
    }
  }
);
Posts.addField({
  fieldName: 'End Date',
  fieldSchema: {
    type: Date,
    label: 'End Date',
    optional: true,
    publish: true,
    insertableIf: canInsert,
    editableIf: canEdit,
  }
});
Posts.addField({
    fieldName: 'Price',
    fieldSchema: {
      type: Number,
      optional: false,
      decimal: true,
      min: 0,
      publish: true,
      insertableIf: canInsert,
      editableIf: canEdit,

    }
  });
  Posts.addField({
      fieldName: 'Location',
      fieldSchema: {
        type: String,
        optional: false,
        decimal: true,
        min: 0,
        publish: true,
        insertableIf: canInsert,
        editableIf: canEdit,
      }
    });

PublicationUtils.addToFields(Posts.publishedFields.list, ["categories"]);
<commit_msg>Test 5.6.3<commit_after>import PublicationUtils from 'meteor/utilities:smart-publications';
import Posts from "meteor/nova:posts";
import Users from 'meteor/nova:users';
import Categories from "./collection.js";

// check if user can create a new post
const canInsert = user => Users.canDo(user, "posts.new");
// check if user can edit a post
const canEdit = Users.canEdit;

Posts.addField(
  {
    fieldName: 'categories',
    fieldSchema: {
      type: [String],
      control: "checkboxgroup",
      optional: true,
      insertableIf: canInsert,
      editableIf: canEdit,
      autoform: {
        noselect: true,
        type: "bootstrap-category",
        order: 50,
        options: function () {
          var categories = Categories.find().map(function (category) {
            return {
              value: category._id,
              label: category.name
            };
          });
          return categories;
        }
      },
      publish: true,
      join: {
        joinAs: "categoriesArray",
        collection: () => Categories
      }
    }
  }
);
Posts.addField({
  fieldName: 'End Date',
  fieldSchema: {
    type: Date,
    label: 'End Date',
    optional: true,
    publish: true,
    insertableIf: canInsert,
    editableIf: canEdit,
  }
});
Posts.addField({
    fieldName: 'Price',
    fieldSchema: {
      type: Number,
      optional: false,
      decimal: true,
      min: 0,
      publish: true,
      insertableIf: canInsert,
      editableIf: canEdit,
      joinAs: "Price",
    }
  });
  Posts.addField({
      fieldName: 'Location',
      fieldSchema: {
        type: String,
        optional: false,
        decimal: true,
        min: 0,
        publish: true,
        insertableIf: canInsert,
        editableIf: canEdit,
      }
    });

PublicationUtils.addToFields(Posts.publishedFields.list, ["categories"]);
<|endoftext|>


<commit_before>Accounts.onCreateUser(function(options, user){
  user = Telescope.callbacks.run("onCreateUser", user, options);
  return user;
});<commit_msg>comment the accounts.onCreateUser callback in order to let the app run<commit_after>/*
Accounts.onCreateUser(function(options, user){
  user = Telescope.callbacks.run("onCreateUser", user, options);
  return user;
});
*/<|endoftext|>


<commit_before>const crypto = require('crypto');
const IMAPConnection = require('../../imap-connection')
const {JSONType, JSONARRAYType} = require('../../database-types');

module.exports = (sequelize, Sequelize) => {
  const Message = sequelize.define('message', {
    accountId: { type: Sequelize.STRING, allowNull: false },
    version: Sequelize.INTEGER,
    headerMessageId: Sequelize.STRING,
    body: Sequelize.TEXT,
    headers: JSONType('headers'),
    subject: Sequelize.STRING(500),
    snippet: Sequelize.STRING(255),
    hash: Sequelize.STRING(65),
    date: Sequelize.DATE,
    unread: Sequelize.BOOLEAN,
    starred: Sequelize.BOOLEAN,
    processed: Sequelize.INTEGER,
    to: JSONARRAYType('to'),
    from: JSONARRAYType('from'),
    cc: JSONARRAYType('cc'),
    bcc: JSONARRAYType('bcc'),
    replyTo: JSONARRAYType('replyTo'),
    folderImapUID: { type: Sequelize.STRING, allowNull: true},
    folderImapXGMLabels: { type: Sequelize.TEXT, allowNull: true},
  }, {
    indexes: [
      {
        unique: true,
        fields: ['hash'],
      },
    ],
    classMethods: {
      associate: ({Folder, Label, File, Thread}) => {
        Message.belongsTo(Thread)
        Message.belongsTo(Folder)
        Message.belongsToMany(Label, {through: 'message_labels'})
        Message.hasMany(File)
      },
      hashForHeaders: (headers) => {
        return crypto.createHash('sha256').update(headers, 'utf8').digest('hex');
      },
    },
    instanceMethods: {
      setLabelsFromXGM(xGmLabels, {preloadedLabels} = {}) {
        if (!xGmLabels) {
          return Promise.resolve();
        }
        const labelNames = xGmLabels.filter(l => l[0] !== '\\')
        const labelRoles = xGmLabels.filter(l => l[0] === '\\').map(l => l.substr(1).toLowerCase())
        const Label = sequelize.models.label;

        let getLabels = null;
        if (preloadedLabels) {
          getLabels = Promise.resolve(preloadedLabels.filter(l => labelNames.includes(l.name) || labelRoles.includes(l.role)));
        } else {
          getLabels = Label.findAll({
            where: sequelize.or({name: labelNames}, {role: labelRoles}),
          })
        }

        this.folderImapXGMLabels = JSON.stringify(xGmLabels);

        return getLabels.then((labels) =>
          this.save().then(() =>
            this.setLabels(labels)
          )
        )
      },

      fetchRaw: function fetchRaw({account, db, logger}) {
        const settings = Object.assign({}, account.connectionSettings, account.decryptedCredentials())
        return Promise.props({
          folder: this.getFolder(),
          connection: IMAPConnection.connect({db, settings, logger}),
        })
        .then(({folder, connection}) => {
          return connection.openBox(folder.name)
          .then((imapBox) => imapBox.fetchMessage(this.folderImapUID))
          .then((message) => {
            if (message) {
              return Promise.resolve(`${message.headers}${message.body}`)
            }
            return Promise.reject(new Error(`Unable to fetch raw message for Message ${this.id}`))
          })
          .finally(() => connection.end())
        })
      },

      toJSON: function toJSON() {
        if (this.folder_id && !this.folder) {
          throw new Error("Message.toJSON called on a message where folder were not eagerly loaded.")
        }

        return {
          id: this.id,
          account_id: this.accountId,
          object: 'message',
          body: this.body,
          subject: this.subject,
          snippet: this.snippet,
          to: this.to,
          from: this.from,
          cc: this.cc,
          bcc: this.bcc,
          reply_to: this.replyTo,
          date: this.date.getTime() / 1000.0,
          unread: this.unread,
          starred: this.starred,
          folder: this.folder,
          thread_id: this.threadId,
        };
      },
    },
  });

  return Message;
};
<commit_msg>fixed json parsing of message<commit_after>const crypto = require('crypto');
const IMAPConnection = require('../../imap-connection')
const {JSONType, JSONARRAYType} = require('../../database-types');

module.exports = (sequelize, Sequelize) => {
  const Message = sequelize.define('message', {
    accountId: { type: Sequelize.STRING, allowNull: false },
    version: Sequelize.INTEGER,
    headerMessageId: Sequelize.STRING,
    body: Sequelize.TEXT,
    headers: JSONType('headers'),
    subject: Sequelize.STRING(500),
    snippet: Sequelize.STRING(255),
    hash: Sequelize.STRING(65),
    date: Sequelize.DATE,
    unread: Sequelize.BOOLEAN,
    starred: Sequelize.BOOLEAN,
    processed: Sequelize.INTEGER,
    to: JSONARRAYType('to'),
    from: JSONARRAYType('from'),
    cc: JSONARRAYType('cc'),
    bcc: JSONARRAYType('bcc'),
    replyTo: JSONARRAYType('replyTo'),
    folderImapUID: { type: Sequelize.STRING, allowNull: true},
    folderImapXGMLabels: { type: Sequelize.TEXT, allowNull: true},
  }, {
    indexes: [
      {
        unique: true,
        fields: ['hash'],
      },
    ],
    classMethods: {
      associate: ({Folder, Label, File, Thread}) => {
        Message.belongsTo(Thread)
        Message.belongsTo(Folder)
        Message.belongsToMany(Label, {through: 'message_labels'})
        Message.hasMany(File)
      },
      hashForHeaders: (headers) => {
        return crypto.createHash('sha256').update(headers, 'utf8').digest('hex');
      },
    },
    instanceMethods: {
      setLabelsFromXGM(xGmLabels, {preloadedLabels} = {}) {
        if (!xGmLabels) {
          return Promise.resolve();
        }
        const labelNames = xGmLabels.filter(l => l[0] !== '\\')
        const labelRoles = xGmLabels.filter(l => l[0] === '\\').map(l => l.substr(1).toLowerCase())
        const Label = sequelize.models.label;

        let getLabels = null;
        if (preloadedLabels) {
          getLabels = Promise.resolve(preloadedLabels.filter(l => labelNames.includes(l.name) || labelRoles.includes(l.role)));
        } else {
          getLabels = Label.findAll({
            where: sequelize.or({name: labelNames}, {role: labelRoles}),
          })
        }

        this.folderImapXGMLabels = JSON.stringify(xGmLabels);

        return getLabels.then((labels) =>
          this.save().then(() =>
            this.setLabels(labels)
          )
        )
      },

      fetchRaw: function fetchRaw({account, db, logger}) {
        const settings = Object.assign({}, account.connectionSettings, account.decryptedCredentials())
        return Promise.props({
          folder: this.getFolder(),
          connection: IMAPConnection.connect({db, settings, logger}),
        })
        .then(({folder, connection}) => {
          return connection.openBox(folder.name)
          .then((imapBox) => imapBox.fetchMessage(this.folderImapUID))
          .then((message) => {
            if (message) {
              return Promise.resolve(`${message.headers}${message.body}`)
            }
            return Promise.reject(new Error(`Unable to fetch raw message for Message ${this.id}`))
          })
          .finally(() => connection.end())
        })
      },

      toJSON: function toJSON() {
        if (this.folder_id && !this.folder) {
          throw new Error("Message.toJSON called on a message where folder were not eagerly loaded.")
        }
        const json = Object.assign({object: 'message'}, this.dataValues)
        if (json.date) {
          json.date = json.date.getTime() / 1000.0
        }
        return json
      },
    },
  });

  return Message;
};
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';

import {
  PictureCard,
  Carousel,
} from '@appearhere/bloom';

const StorySlide = ({ number }) => (
  <div key={`slide-${number}`}>
    <PictureCard
      src={`https://placekitten.com/g/287/4${number * 2 + 10}`}
      style={{
        height: '300px',
        verticalAlign: 'middle',
        textAlign: 'center',
        fontSize: '5rem',
        width: '200px'
      }}
      center
      href="#"
    >
      {number}
    </PictureCard>

);
const slides = [...Array(10).keys()].map(i => <StorySlide number={i} key={i} />);

storiesOf('Carousel', module)
.add('Default', () => (
  <Carousel slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
))
.add('With Title', () => (
  <Carousel title="Carousel Title" slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
))
.add('With small Title', () => (
  <Carousel titleSize="small" title="Carousel Title" slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
))
.add('With Center controls', () => (
  <Carousel title="Carousel Title" useCenterControls useTopRightControls={false} slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
));
<commit_msg>Adding story<commit_after>import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';

import {
  PictureCard,
  Carousel,
} from '@appearhere/bloom';

const StorySlide = ({ number }) => (
  <div key={`slide-${number}`}>
    <PictureCard
      src={`https://placekitten.com/g/287/4${number * 2 + 10}`}
      style={{
        height: '300px',
        verticalAlign: 'middle',
        textAlign: 'center',
        fontSize: '5rem',
        width: '200px'
      }}
      center
      href="#"
    >
      {number}
    </PictureCard>

);
const slides = [...Array(10).keys()].map(i => <StorySlide number={i} key={i} />);

storiesOf('Carousel', module)
.add('Default', () => (
  <Carousel slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
))
.add('With small Title', () => (
  <Carousel titleSize="small" title="Carousel Title" slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
))
.add('With medium Title', () => (
  <Carousel titleSize="medium" title="Carousel Title" slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
))
.add('With large Title', () => (
  <Carousel title="Carousel Title" slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
))
.add('With Center controls', () => (
  <Carousel title="Carousel Title" useCenterControls useTopRightControls={false} slidesToShow={4} onChange={action('Slide changed')}>{slides}</Carousel>
));
<|endoftext|>


<commit_before>var emberize = function (object) {
    for (var i in object) {
        if (object.hasOwnProperty(i)) {
            if (Ember.typeOf(object[i]) == 'object') {
                object[i] = emberize(object[i]);
            }
        }
    }
    return Em.Object.create(object);
};

Ember.Model.reopen({
    _requestedLoadableProps: function () {
        return [];
    }.property().readOnly()
});

Ember.Model.reopenClass({

    makeLoadableProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;
        return Ember.computed(fakePropName, {
            get: function(){
                if (typeof this.get(Em.get(this.constructor, 'primaryKey')) === "undefined") {
                    return undefined;
                }

                if (!this.get("_requestedLoadableProps").contains(propName)) {
                    var that = this;

                    this.get("_requestedLoadableProps").addObject(propName);
                    this.callRestOnObject(restFunc).then(function (res) {
                        if (transformFunc) {
                            res = transformFunc(res);
                        } else if (res && typeof res == 'object') {
                            res = emberize(res);
                        }
                        that.set(fakePropName, res);
                        //that.notifyPropertyChange(propName);
                    });
                }

                return this.get(fakePropName);
            },
            set: function(key, value){
                this.set(fakePropName, value);
                return value;
            }
        });
    },

    makeLoadableArrayProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;

        return Ember.computed(fakePropName + '.[]', {
            get: function(){
                if (!this.get("_requestedLoadableProps").contains(propName)) {
                    this.get("_requestedLoadableProps").addObject(propName);

                    this.set(fakePropName, []);
                    var that = this;
                    this.callRestOnObject(restFunc).then(function (data) {
                        var d = [];
                        if (transformFunc) {
                            data.forEach(function (item, i) {
                                d.push(transformFunc(i, item));
                            });
                        } else {
                            d = data;
                        }

                        that.get(fakePropName).addObjects(d.sort(function (a, b) {
                            return a.id - b.id;
                        }));
                    });
                }
                return this.get(fakePropName);
            },
            set: function (key, value) {
                this.set(fakePropName, value);
                return value;
            }
        });
    }
});

Ember.Model.reopen({
    reloadProp: function (propName) {
        this.get("_requestedLoadableProps").removeObject(propName);
        var that = this;
        var p = new Em.RSVP.Promise(function (resolve, reject) {
            var t = setTimeout(reject, 500);
            var f = function () {
                clearTimeout(t);
                that.removeObserver(propName, that, f);
                resolve(that.get(propName));
            };
            that.addObserver(propName, that, f);
        });

        that.notifyPropertyChange(propName);
        return p;
    }
});
<commit_msg>fix makeLoadableProp<commit_after>var emberize = function (object) {
    for (var i in object) {
        if (object.hasOwnProperty(i)) {
            if (Ember.typeOf(object[i]) == 'object') {
                object[i] = emberize(object[i]);
            }
        }
    }
    return Em.Object.create(object);
};

Ember.Model.reopen({
    _requestedLoadableProps: function () {
        return [];
    }.property().readOnly()
});

Ember.Model.reopenClass({

    makeLoadableProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;
        return Ember.computed(fakePropName, {
            get: function(){
                if (typeof this.get(Em.get(this.constructor, 'primaryKey')) === "undefined") {
                    return undefined;
                }

                if (!this.get("_requestedLoadableProps").contains(propName)) {
                    var that = this;

                    this.get("_requestedLoadableProps").addObject(propName);
                    this.callRestOnObject(restFunc).then(function (res) {
                        if (transformFunc) {
                            res = transformFunc(res);
                        } else if (res && typeof res == 'object') {
                            res = emberize(res);
                        }
                        that.set(fakePropName, res);
                        that.set(propName, res);
                    });
                }

                return this.get(fakePropName);
            },
            set: function(key, value){
                this.set(fakePropName, value);
                this.notifyPropertyChange(fakePropName);
                this.notifyPropertyChange(propName);
                return value;
            }
        });
    },

    makeLoadableArrayProp: function (propName, restFunc, transformFunc) {
        var fakePropName = '_' + propName;

        return Ember.computed(fakePropName + '.[]', {
            get: function(){
                if (!this.get("_requestedLoadableProps").contains(propName)) {
                    this.get("_requestedLoadableProps").addObject(propName);

                    this.set(fakePropName, []);
                    var that = this;
                    this.callRestOnObject(restFunc).then(function (data) {
                        var d = [];
                        if (transformFunc) {
                            data.forEach(function (item, i) {
                                d.push(transformFunc(i, item));
                            });
                        } else {
                            d = data;
                        }

                        that.get(fakePropName).addObjects(d.sort(function (a, b) {
                            return a.id - b.id;
                        }));
                    });
                }
                return this.get(fakePropName);
            },
            set: function (key, value) {
                this.set(fakePropName, value);
                return value;
            }
        });
    }
});

Ember.Model.reopen({
    reloadProp: function (propName) {
        this.get("_requestedLoadableProps").removeObject(propName);
        var that = this;
        var p = new Em.RSVP.Promise(function (resolve, reject) {
            var t = setTimeout(reject, 500);
            var f = function () {
                clearTimeout(t);
                that.removeObserver(propName, that, f);
                resolve(that.get(propName));
            };
            that.addObserver(propName, that, f);
        });

        that.notifyPropertyChange(propName);
        return p;
    }
});
<|endoftext|>


<commit_before>// @flow

import path from 'path'
import invariant from 'assert'
import flatten from 'lodash/flatten'
import browserResolve from 'browser-resolve'
import browserAliases from 'pundle-resolver-aliases-browser'
import { isCore } from 'resolve'
import { createFileResolver } from 'pundle-api'

import manifest from '../package.json'

function createComponent({
  formats,
  aliases = {},
  external = [],
}: {
  formats: { [string]: string },
  aliases: { [string]: string },
  external: Array<string>,
}) {
  invariant(formats && typeof formats === 'object', 'options.formats must be a valid object')
  invariant(aliases && typeof aliases === 'object', 'options.aliases must be a valid object')
  invariant(external && Array.isArray(external), 'options.external must be an Array')

  return createFileResolver({
    name: 'pundle-file-resolver',
    version: manifest.version,
    async callback({ request, requestFile, context }) {
      if (external.length && request[0] !== '.') {
        const requestModule = request.split('/')[0]
        if (external.includes(requestModule)) {
          return {
            format: null,
            filePath: false,
          }
        }
      }

      const response = await new Promise(function(resolve, reject) {
        browserResolve(
          request,
          {
            modules: {
              ...(context.config.target === 'browser' ? browserAliases : {}),
              ...aliases,
            },
            basedir: requestFile ? path.dirname(requestFile) : context.config.rootDirectory,
            extensions: flatten(Object.values(formats)),
            /* eslint-disable no-param-reassign */
            packageFilter(packageManifest) {
              if (typeof packageManifest['jsnext:main'] === 'string') {
                packageManifest.main = packageManifest['jsnext:main']
              }
              if (typeof packageManifest.module === 'string') {
                packageManifest.main = packageManifest.module
              }
              return packageManifest
            },
            /* eslint-enable no-param-reassign */
          },
          function(err, res) {
            if (err) reject(err)
            else resolve(res)
          },
        )
      })

      if (!response) return null

      if (process.env.PUNDLE_DEBUG_RESOLVER === '1') {
        console.log('From', requestFile, 'processed', request, 'to', response)
      }
      if (isCore(response)) {
        return {
          format: null,
          filePath: false,
        }
      }

      const ext = path.extname(response)
      const format = Object.keys(formats).find(entry => formats[entry].includes(ext))
      if (!format) {
        console.error(`File was resolved as '${response}' but extension '${ext}' is not recognized`)
        return null
      }

      return {
        format,
        filePath: response,
      }
    },
  })
}

module.exports = createComponent
<commit_msg>:new: Add options.mainFields to resolver-default<commit_after>// @flow

import path from 'path'
import invariant from 'assert'
import flatten from 'lodash/flatten'
import browserResolve from 'browser-resolve'
import browserAliases from 'pundle-resolver-aliases-browser'
import { isCore } from 'resolve'
import { createFileResolver } from 'pundle-api'

import manifest from '../package.json'

function createComponent({
  formats,
  aliases = {},
  external = [],
  mainFields = ['jsxnext:main', 'module'],
}: {
  formats: { [string]: string },
  aliases: { [string]: string },
  external: Array<string>,
  mainFields: Array<string>,
}) {
  invariant(formats && typeof formats === 'object', 'options.formats must be a valid object')
  invariant(aliases && typeof aliases === 'object', 'options.aliases must be a valid object')
  invariant(external && Array.isArray(external), 'options.external must be an Array')
  invariant(mainFields && Array.isArray(mainFields), 'options.mainFields must be an Array')

  if (mainFields.includes('browser')) {
    throw new Error("options.mainFields must not include 'browser'")
  }

  return createFileResolver({
    name: 'pundle-file-resolver',
    version: manifest.version,
    async callback({ request, requestFile, context }) {
      if (external.length && request[0] !== '.') {
        const requestModule = request.split('/')[0]
        if (external.includes(requestModule)) {
          return {
            format: null,
            filePath: false,
          }
        }
      }

      const response = await new Promise(function(resolve, reject) {
        browserResolve(
          request,
          {
            modules: {
              ...(context.config.target === 'browser' ? browserAliases : {}),
              ...aliases,
            },
            basedir: requestFile ? path.dirname(requestFile) : context.config.rootDirectory,
            extensions: flatten(Object.values(formats)),
            /* eslint-disable no-param-reassign */
            packageFilter(packageManifest) {
              mainFields.forEach(function(mainField) {
                if (typeof packageManifest[mainField] === 'string') {
                  packageManifest.main = packageManifest[mainField]
                }
              })
              return packageManifest
            },
            /* eslint-enable no-param-reassign */
          },
          function(err, res) {
            if (err) reject(err)
            else resolve(res)
          },
        )
      })

      if (!response) return null

      if (process.env.PUNDLE_DEBUG_RESOLVER === '1') {
        console.log('From', requestFile, 'processed', request, 'to', response)
      }
      if (isCore(response)) {
        return {
          format: null,
          filePath: false,
        }
      }

      const ext = path.extname(response)
      const format = Object.keys(formats).find(entry => formats[entry].includes(ext))
      if (!format) {
        console.error(`File was resolved as '${response}' but extension '${ext}' is not recognized`)
        return null
      }

      return {
        format,
        filePath: response,
      }
    },
  })
}

module.exports = createComponent
<|endoftext|>


<commit_before>angular.module('app.controllers', [])

.controller('searchAppCtrl', function($scope,LoginService, $ionicPopup, $state,$q,$cordovaOauth,$cordovaSplashscreen) {
    $scope.data = {};
    $scope.IsLogedIn= false;
    $scope.Submitted= false;
    $scope.IsFormValid=false;
    $scope.Message='';
    $scope.data={
        userName:'',
        pwd:''
    };

     $scope.$watch('form.$valid',function(newVal){
        $scope.IsFormValid=newVal;
    });

    $scope.login = function() {

        $scope.Submitted=true;
        $scope.IsFormValid=true;
        if($scope.IsFormValid){

            LoginService.isDuplicate($scope.data)
                .then(function (response) {
                    if (response.success) {
                         $cordovaSplashscreen.show();
                         $cordovaSplashscreen.hide();
                       $state.go('home');
                    }
                    else{
                        $scope.Message="Invalid Credentials";
                    }
                });
        }
    };

      $scope.facebookLogin = function() {
          console.log("Inside facebook login");
        $cordovaOauth.facebook("1112137608839690", ["email"]).then(function(result) {

            $state.go('home');
        }, function(error) {
            // error
            console.log(" error in facebook login"+error);
        });
    };

      $scope.goToRegisterPage = function() {
        console.log("Inside register");
        $state.go('register');

    };
})

.controller('registerCtrl', function($scope, $state,$filter,$q,LoginService) {

     $scope.registerData={
        un:'',
        pwd:''
    };

    $scope.cancel=function(){
        $state.go('login');
    }

     $scope.register = function() {
        console.log("Inside register"+ $scope.registerData.un+" "+$scope.registerData.pwd);
        $scope.RegSubmitted=true;
        $scope.IsRegLogedIn=true;
        LoginService.CreateUser($scope.registerData)
            .then(function (response) {
                if (response.success) {
                    $scope.status="Thank you "+$scope.registerData.name+" for Signing up with us";
                }
                else{
                    $scope.status="Username "+$scope.registerData.un+" already exists.Please try again";
                }
            });
      }
})

.controller('homeCtrl', function($scope, $state, $cordovaGeolocation,$ionicLoading,HomeService,Eventful,$document,$cordovaDatePicker,$cordovaDialogs) {

var map=null;

$scope.initialise = function() {

console.log("In Google.maps.event.addDomListener");
var myLatlng = new google.maps.LatLng(37.3000, -120.4833);
var mapOptions = {
center: myLatlng,
zoom: 16,
//mapTypeId: 'satellite'
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);

    console.log(mapOptions);

    navigator.geolocation.getCurrentPosition(function(pos) {
        console.log("position: "+pos);
        map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
        var myLocation = new google.maps.Marker({
            position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
            map: map,
            title: "My Location"
        });
    });
console.log("initializing");
    $scope.map = map;
};

google.maps.event.addDomListener(document.getElementById("map"), 'load', $scope.initialise());

$scope.showCalender=function(){

    console.log("alert-date");
     var options = {
    date: new Date(),
    mode: 'date', // or 'time'
    minDate: new Date() - 10000,
    allowOldDates: true,
    allowFutureDates: false,
    doneButtonLabel: 'DONE',
    doneButtonColor: '#F2F3F4',
    cancelButtonLabel: 'CANCEL',
    cancelButtonColor: '#000000'
  };

  //   $cordovaDialogs.confirm('Are you sure you want to search?', 'Proceed', ['Cancel','Search']);
   /*$cordovaDatePicker.show(options).then(function(date){
        alert(date);
    });*/

};

 $scope.search = function() {

    Eventful.findEvents($scope.data.location).then(function(response) {

      self.events = response;
      console.log(self.events);
      self.events.forEach(function(single_event) {
        addMarker(single_event);
      })
      $scope.map = map;
    });

 }

  addMarker = function(event) {
      map=$scope.map;
      var concert_center = new google.maps.LatLng(event.latitude, event.longitude);
      console.log(event.latitude + "   "+event.longitude);
      var marker = new google.maps.Marker({
      position: concert_center,
      title:"My location!",
      visible: true,
    }
                                         );
    marker.setMap(map);
    var infoWindowContent = "
"+event.title+"
"+"
"+"
"+event.venue_address+"
"+"<h8> description:"+event.description+"</h8>";
    addInfoWindow(marker, infoWindowContent, event);

  }

  function addInfoWindow(marker, message, event) {

      var infoWindow = new google.maps.InfoWindow({
          content: message
      });

      google.maps.event.addListener(marker, 'click', function () {
          infoWindow.open(map, marker);
      });

  }

})
<commit_msg>Update controllers.js<commit_after>angular.module('app.controllers', [])

.controller('searchAppCtrl', function($scope,LoginService, $ionicPopup, $state,$q,$cordovaOauth,$cordovaSplashscreen) {
    $scope.data = {};
    $scope.IsLogedIn= false;
    $scope.Submitted= false;
    $scope.IsFormValid=false;
    $scope.Message='';
    $scope.data={
        userName:'',
        pwd:''
    };

     $scope.$watch('form.$valid',function(newVal){
        $scope.IsFormValid=newVal;
    });

    $scope.login = function() {

        $scope.Submitted=true;
        $scope.IsFormValid=true;
        if($scope.IsFormValid){

            LoginService.isDuplicate($scope.data)
                .then(function (response) {
                    if (response.success) {
                         $cordovaSplashscreen.show();
                         $cordovaSplashscreen.hide();
                       $state.go('home');
                    }
                    else{
                        $scope.Message="Invalid Credentials";
                    }
                });
        }
    };

      $scope.facebookLogin = function() {
          console.log("Inside facebook login");
        $cordovaOauth.facebook("1112137608839690", ["email"]).then(function(result) {

            $state.go('home');
        }, function(error) {
            // error
            console.log(" error in facebook login"+error);
        });
    };

      $scope.goToRegisterPage = function() {
        console.log("Inside register");
        $state.go('register');

    };
})

.controller('registerCtrl', function($scope, $state,$filter,$q,LoginService) {

     $scope.registerData={
        un:'',
        pwd:''
    };

    $scope.cancel=function(){
        $state.go('login');
    }

     $scope.register = function() {
        console.log("Inside register"+ $scope.registerData.un+" "+$scope.registerData.pwd);
        $scope.RegSubmitted=true;
        $scope.IsRegLogedIn=true;
        LoginService.CreateUser($scope.registerData)
            .then(function (response) {
                if (response.success) {
                    $scope.status="Thank you "+$scope.registerData.name+" for Signing up with us";
                }
                else{
                    $scope.status="Username "+$scope.registerData.un+" already exists.Please try again";
                }
            });
      }
})

.controller('homeCtrl', function($scope, $state, $cordovaGeolocation,$ionicLoading,HomeService,Eventful,$document,$cordovaDatePicker,$cordovaDialogs) {

var map=null;

$scope.initialise = function() {

console.log("In Google.maps.event.addDomListener");
var myLatlng = new google.maps.LatLng(39.0345, -94.6647);
var mapOptions = {
center: myLatlng,
zoom: 16,
//mapTypeId: 'satellite'
mapTypeId: google.maps.MapTypeId.ROADMAP
};

    var lat  = 39.0345;
      var long =  -94.6647;

 var myLocation = new google.maps.Marker({
            position: new google.maps.LatLng(lat, long),
            map: map,
            title: "My Location"
        });

map = new google.maps.Map(document.getElementById("map"), mapOptions);

    console.log(mapOptions);

    var posOptions = {timeout: 10000, enableHighAccuracy: false};

    $cordovaGeolocation
    .getCurrentPosition(posOptions)
    .then(function (position) {
      var lat  = position.coords.latitude
      var long = position.coords.longitude
       map.setCenter(new google.maps.LatLng(lat, long));
        var myLocation = new google.maps.Marker({
            position: new google.maps.LatLng(lat, long),
            map: map,
            title: "My Location"
        });
    }, function(err) {
      // error
    });

    navigator.geolocation.getCurrentPosition(function(pos) {
        console.log("position: "+pos);
        map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
        var myLocation = new google.maps.Marker({
            position: new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude),
            map: map,
            title: "My Location"
        });
    });
console.log("initializing");
    $scope.map = map;
};

google.maps.event.addDomListener(document.getElementById("map"), 'load', $scope.initialise());

$scope.showCalender=function(){

    console.log("alert-date");
     var options = {
    date: new Date(),
    mode: 'date', // or 'time'
    minDate: new Date() - 10000,
    allowOldDates: true,
    allowFutureDates: false,
    doneButtonLabel: 'DONE',
    doneButtonColor: '#F2F3F4',
    cancelButtonLabel: 'CANCEL',
    cancelButtonColor: '#000000'
  };

  //   $cordovaDialogs.confirm('Are you sure you want to search?', 'Proceed', ['Cancel','Search']);
   /*$cordovaDatePicker.show(options).then(function(date){
        alert(date);
    });*/

};

 $scope.search = function() {

    Eventful.findEvents($scope.data.location).then(function(response) {

      self.events = response;
      console.log(self.events);
      self.events.forEach(function(single_event) {
        addMarker(single_event);
      })
      $scope.map = map;
    });

 }

  addMarker = function(event) {
      map=$scope.map;
      var concert_center = new google.maps.LatLng(event.latitude, event.longitude);
      console.log(event.latitude + "   "+event.longitude);
      var marker = new google.maps.Marker({
      position: concert_center,
      title:"My location!",
      visible: true,
    }
                                         );
    marker.setMap(map);
    var infoWindowContent = "
"+event.title+"
"+"
"+"
"+event.venue_address+"
"+"<h8> description:"+event.description+"</h8>";
    addInfoWindow(marker, infoWindowContent, event);

  }

  function addInfoWindow(marker, message, event) {

      var infoWindow = new google.maps.InfoWindow({
          content: message
      });

      google.maps.event.addListener(marker, 'click', function () {
          infoWindow.open(map, marker);
      });

  }

})
<|endoftext|>