<commit_before>/* jshint maxparams: 5 */

(function(W, D, E, H, U) {
	'use strict';

	var support = H && H.pushState,
		entries = [],
		settings = {},
		root = '',
		path = '',

		/**
		 * Return current path
		 *
		 * @private
		 * @param {object} [loc]
		 * @returns {string}
		 */
		_path = function(loc) {
			loc = loc || location;
			return loc.pathname + loc.search + loc.hash;
		},

		/**
		 * Determine if path is valid for history navigation
		 *
		 * @private
		 * @param {HTMLElement} el
		 */
		_isValid = function(el) {
			var host = el.hostname,
				path = el.pathname,
				loc = location;

			if (! el.href ||
				(host && host != loc.hostname) ||
				(el.hash && path == loc.pathname)) {
				return false;
			}

			var exts = settings.extensions,
				segs = path.split('.'),
				ext;

			if (segs.length > 1) {
				ext = segs.pop().split(/#|\?/)[0];
			}

			return ! ext || (exts && exts.indexOf(ext) > -1);
		},

		/**
		 * Reset references and variables for a given selector
		 *
		 * @private
		 * @param sel
		 */
		_reset = function(sel) {
			W.$setRef(sel);
			W.$setVar(sel);

			W.history.bind();
		},

		/**
		 * Process the history state of the request
		 *
		 * @private
		 * @param {object} conf
		 */
		_process = function(conf) {
			var request = conf.request,
				method = request.method;

			if (! method || method == 'get') {
				conf.path = D._getUrl(request);
			}

			var key = conf.path.replace(/^\//g, ''),
				obj = {
					args: [
						{
							dir: conf.push ? 1 : -1,
							path: conf.path,
							prev: path
						}
					]
				};
			entries[key] = conf;

			// Add entry to HTML5 history
			if (conf.push && support) {
				H.pushState(0, '', conf.path);
			}

			// Update document title
			if (conf.title) {
				W._doc.title = conf.title;
			}

			if (W.routes) {
				// Update current path
				W.routes.uri(conf.path);
				W.routes.uri({
					history: true
				});

				// Evaluate routes against updated path
				if (conf.run) {
					W.routes.run({
						event: 'pop',
						path: path
					});

					W.routes.run({
						path: conf.path
					});
				}

				path = conf.path;
			}

			if (conf.push && conf.pushstate) {
				W.$exec(conf.pushstate, obj);
			}

			if (conf.pop && conf.popstate) {
				W.$exec(conf.popstate, obj);
			}

			if (conf.end) {
				W.$exec(conf.end, obj);
			}
		};

	W.history = {
		/**
		 * Set the initial state and popstate event, and bind global actions
		 *
		 * @param {object} [options]
		 * @param {($|HTMLElement|string)} [options.bind]
		 * @param {Array} [options.extensions]
		 * @param {string} [options.partials='title,main']
		 * @param {boolean} [options.push=true]
		 * @param {object} [options.request]
		 * @param {boolean} [options.run=true]
		 */
		init: function(options) {
			if (! this.request) {
				path = _path();
				settings = W.$extend({
					partials: 'title,main',
					push: true,
					request: {},
					run: true,
					scrollTop: 0
				}, options);
				root = settings.request.root || '';

				this.request = settings.request;
				delete settings.request;

				if (support) {
					H.scrollRestoration = 'manual';

					// Set current state
					H.replaceState(0, '');

					// Listen for browser navigation
					E.on(W._win, 'popstate.history', function(e) {
						if (e.state !== null) {
							var url = _path(),
								prevConf = entries[path.replace(/^\//g, '')],
								conf = W.$extend(
									entries[url.replace(/^\//g, '')] || {
										request: {
											root: ''
										}
									}, {
										path: url,
										push: false,
										pop: true
									}
								);
							conf.partials = prevConf.partials;

							// Restore previous scroll position
							if (e.state.top) {
								conf.scrollTop = e.state.top;
							}

							W.history.go(conf);
						}
					});
				}

				// Bind PJAX actions
				this.bind();
			}
		},

		/**
		 * Bind element events and form submit events to PJAX
		 *
		 * @param {(boolean|object)} [events]
		 * @param {($|HTMLElement|Object|string)} [a] - settings or context
		 * @param {($|HTMLElement|string)} [context=document]
		 */
		bind: function(events, a, context) {
			events = events || settings.bind;

			if (events === true) {
				events = {
					click: 'a',
					submit: 'form'
				};
			}

			if (support && typeof events == 'object') {
				var keys = Object.keys(events),
					i = 0;

				if (typeof a !== 'object') {
					context = a;
					a = {};
				}

				for (; i < keys.length; i++) {
					var event = keys[i],
						sel = events[event];

					$(sel).each(function(el) {
						var evt = event.split(' ').map(function(val) {
								return val + '.history';
							}).join(' '),
							loc = el.getAttribute('data-url'),
							l = el;

						if (loc || el.action) {
							l = W._doc.createElement('a');
							l.href = loc || el.action;
						}

						// Ensure the path exists and is local
						if (evt && _isValid(l)) {
							var options = W.$extend(true, {}, a);

							// Remove existing history events
							E.off(el, evt);

							E.on(el, evt, function(e, el) {
								if (! e.metaKey && ! el.hasAttribute('data-static')) {
									options.path = _path(l);

									W.history.go(options);
									e.preventDefault();
								}
							});
						}
					}, {
						context: context
					});
				}
			}
		},

		/**
		 * Navigate to a new path or within the browser history
		 *
		 * @param {object} options
		 * @param {string} [options.action='replace']
		 * @param {Array} [options.extensions]
		 * @param {string} [options.partials='title,main']
		 * @param {string} [options.path=current path]
		 * @param {boolean} [options.push=true]
		 * @param {object} [options.request]
		 * @param {boolean} [options.run=true]
		 * @param {($|HTMLElement|number|string)} [options.scrollTop]
		 * @param {string} [options.title]
		 */
		go: function(options) {
			var scope = this;

			if (! scope.request) {
				scope.init();
			}

			var globalRequest = scope.request,
				conf = W.$extend(
					{},
					settings,
					options
				),
				request = conf.request || {};

			request.root = request.root !== U ? request.root : root;
			request.url = request.url !== U ? request.url : conf.path;

			// Navigate to external URL or if history isn't supported
			var a = W._doc.createElement('a');
			a.href = request.root + request.url;

			if (! support || ! _isValid(a)) {
				W._win.location = request.url;
				return false;
			}

			if (conf.begin && W.$exec(conf.begin, {
					args: [conf]
				}) === false) {
				return;
			}

			// Set current scroll position
			H.replaceState({
				top: W._body.scrollTop
			}, '');

			// Reset URL to exclude root
			a.href = request.url;

			request.url = _path(a);
			conf.request = request;

			// Request partial Ajax
			if (request.url) {
				var sendEvents = [],
					successEvents = [],
					errorEvents = [],
					completeEvents = [],
					partials = conf.partials,
					targets = W.$(partials);

				// Set Pjax header
				request.headers = request.headers || {};
				request.headers['X-PJAX'] = 'true';

				// Process send events
				if (request.send) {
					sendEvents.push(request.send);
				}

				if (globalRequest.send) {
					sendEvents.push(globalRequest.send);
				}

				request.send = sendEvents;

				// Compile success events
				successEvents.push(function(html) {
					if (conf.replace) {
						html = W.$exec(conf.replace, {
							args: [html]
						}) || html;
					}

					// Evaluate unload routes against updated path
					if (W.routes && conf.run) {
						W.routes.run({
							event: 'unload',
							path: path
						});
					}

					if (partials) {
						html = W.$parseHTML('' + html + '').firstChild;

						// Make partial replacements from response
						W.$each(partials.split(','), function(sel) {
							W.$each(sel, function(el) {
								var target = W.$(sel)[0];

								if (target) {
									var parent = target.parentNode;

									conf.action == 'append' ?
										parent.appendChild(el) :
										parent.replaceChild(el, target);

									_reset(parent);
								}
							}, {
								context: html
							});
						});
					} else {
						targets.innerHTML = html;

						_reset(targets);
					}
				});

				if (request.success) {
					successEvents.push(request.success);
				}

				if (globalRequest.success) {
					successEvents.push(globalRequest.success);
				}

				successEvents.push(function() {
					var st = conf.scrollTop;

					// Scroll vertically to target
					if (st !== false) {
						var top = a.hash ? W.$offset(a.hash).top : 0,
							anim = W.animate;

						if (! top) {
							top = typeof st == 'number' ?
								st :
								W.$(st)[0].getBoundingClientRect().top +
									W._win.pageYOffset;
						}

						if (anim) {
							anim.tween(W._body, {
								scrollTop: top
							});
						} else {
							W._body.scrollTop = top;
						}
					}
				});

				request.success = successEvents;

				// Compile error events
				if (request.error) {
					errorEvents.push(request.error);
				}

				if (globalRequest.error) {
					errorEvents.push(globalRequest.error);
				}

				request.error = errorEvents;

				// Compile complete events
				if (request.complete) {
					completeEvents.push(request.complete);
				}

				if (globalRequest.complete) {
					completeEvents.push(globalRequest.complete);
				}

				completeEvents.push(function(xhr) {
					if (xhr.status == 200) {
						_process(conf);
					}
				});

				request.complete = completeEvents;

				// Make Ajax request
				request.args = request.args || [];
				request.args.unshift(targets);

				D.request(request);
			} else {
				_process(conf);
			}
		}
	};
})(Wee, Wee.data, Wee.events, history, undefined);<commit_msg>Account for missing hash tagets when calculating scroll offset<commit_after>/* jshint maxparams: 5 */

(function(W, D, E, H, U) {
	'use strict';

	var support = H && H.pushState,
		entries = [],
		settings = {},
		root = '',
		path = '',

		/**
		 * Return current path
		 *
		 * @private
		 * @param {object} [loc]
		 * @returns {string}
		 */
		_path = function(loc) {
			loc = loc || location;
			return loc.pathname + loc.search + loc.hash;
		},

		/**
		 * Determine if path is valid for history navigation
		 *
		 * @private
		 * @param {HTMLElement} el
		 */
		_isValid = function(el) {
			var host = el.hostname,
				path = el.pathname,
				loc = location;

			if (! el.href ||
				(host && host != loc.hostname) ||
				(el.hash && path == loc.pathname)) {
				return false;
			}

			var exts = settings.extensions,
				segs = path.split('.'),
				ext;

			if (segs.length > 1) {
				ext = segs.pop().split(/#|\?/)[0];
			}

			return ! ext || (exts && exts.indexOf(ext) > -1);
		},

		/**
		 * Reset references and variables for a given selector
		 *
		 * @private
		 * @param sel
		 */
		_reset = function(sel) {
			W.$setRef(sel);
			W.$setVar(sel);

			W.history.bind();
		},

		/**
		 * Process the history state of the request
		 *
		 * @private
		 * @param {object} conf
		 */
		_process = function(conf) {
			var request = conf.request,
				method = request.method;

			if (! method || method == 'get') {
				conf.path = D._getUrl(request);
			}

			var key = conf.path.replace(/^\//g, ''),
				obj = {
					args: [
						{
							dir: conf.push ? 1 : -1,
							path: conf.path,
							prev: path
						}
					]
				};
			entries[key] = conf;

			// Add entry to HTML5 history
			if (conf.push && support) {
				H.pushState(0, '', conf.path);
			}

			// Update document title
			if (conf.title) {
				W._doc.title = conf.title;
			}

			if (W.routes) {
				// Update current path
				W.routes.uri(conf.path);
				W.routes.uri({
					history: true
				});

				// Evaluate routes against updated path
				if (conf.run) {
					W.routes.run({
						event: 'pop',
						path: path
					});

					W.routes.run({
						path: conf.path
					});
				}

				path = conf.path;
			}

			if (conf.push && conf.pushstate) {
				W.$exec(conf.pushstate, obj);
			}

			if (conf.pop && conf.popstate) {
				W.$exec(conf.popstate, obj);
			}

			if (conf.end) {
				W.$exec(conf.end, obj);
			}
		};

	W.history = {
		/**
		 * Set the initial state and popstate event, and bind global actions
		 *
		 * @param {object} [options]
		 * @param {($|HTMLElement|string)} [options.bind]
		 * @param {Array} [options.extensions]
		 * @param {string} [options.partials='title,main']
		 * @param {boolean} [options.push=true]
		 * @param {object} [options.request]
		 * @param {boolean} [options.run=true]
		 */
		init: function(options) {
			if (! this.request) {
				path = _path();
				settings = W.$extend({
					partials: 'title,main',
					push: true,
					request: {},
					run: true,
					scrollTop: 0
				}, options);
				root = settings.request.root || '';

				this.request = settings.request;
				delete settings.request;

				if (support) {
					H.scrollRestoration = 'manual';

					// Set current state
					H.replaceState(0, '');

					// Listen for browser navigation
					E.on(W._win, 'popstate.history', function(e) {
						if (e.state !== null) {
							var url = _path(),
								prevConf = entries[path.replace(/^\//g, '')],
								conf = W.$extend(
									entries[url.replace(/^\//g, '')] || {
										request: {
											root: ''
										}
									}, {
										path: url,
										push: false,
										pop: true
									}
								);
							conf.partials = prevConf.partials;

							// Restore previous scroll position
							if (e.state.top) {
								conf.scrollTop = e.state.top;
							}

							W.history.go(conf);
						}
					});
				}

				// Bind PJAX actions
				this.bind();
			}
		},

		/**
		 * Bind element events and form submit events to PJAX
		 *
		 * @param {(boolean|object)} [events]
		 * @param {($|HTMLElement|Object|string)} [a] - settings or context
		 * @param {($|HTMLElement|string)} [context=document]
		 */
		bind: function(events, a, context) {
			events = events || settings.bind;

			if (events === true) {
				events = {
					click: 'a',
					submit: 'form'
				};
			}

			if (support && typeof events == 'object') {
				var keys = Object.keys(events),
					i = 0;

				if (typeof a !== 'object') {
					context = a;
					a = {};
				}

				for (; i < keys.length; i++) {
					var event = keys[i],
						sel = events[event];

					$(sel).each(function(el) {
						var evt = event.split(' ').map(function(val) {
								return val + '.history';
							}).join(' '),
							loc = el.getAttribute('data-url'),
							l = el;

						if (loc || el.action) {
							l = W._doc.createElement('a');
							l.href = loc || el.action;
						}

						// Ensure the path exists and is local
						if (evt && _isValid(l)) {
							var options = W.$extend(true, {}, a);

							// Remove existing history events
							E.off(el, evt);

							E.on(el, evt, function(e, el) {
								if (! e.metaKey && ! el.hasAttribute('data-static')) {
									options.path = _path(l);

									W.history.go(options);
									e.preventDefault();
								}
							});
						}
					}, {
						context: context
					});
				}
			}
		},

		/**
		 * Navigate to a new path or within the browser history
		 *
		 * @param {object} options
		 * @param {string} [options.action='replace']
		 * @param {Array} [options.extensions]
		 * @param {string} [options.partials='title,main']
		 * @param {string} [options.path=current path]
		 * @param {boolean} [options.push=true]
		 * @param {object} [options.request]
		 * @param {boolean} [options.run=true]
		 * @param {($|HTMLElement|number|string)} [options.scrollTop]
		 * @param {string} [options.title]
		 */
		go: function(options) {
			var scope = this;

			if (! scope.request) {
				scope.init();
			}

			var globalRequest = scope.request,
				conf = W.$extend(
					{},
					settings,
					options
				),
				request = conf.request || {};

			request.root = request.root !== U ? request.root : root;
			request.url = request.url !== U ? request.url : conf.path;

			// Navigate to external URL or if history isn't supported
			var a = W._doc.createElement('a');
			a.href = request.root + request.url;

			if (! support || ! _isValid(a)) {
				W._win.location = request.url;
				return false;
			}

			if (conf.begin && W.$exec(conf.begin, {
					args: [conf]
				}) === false) {
				return;
			}

			// Set current scroll position
			H.replaceState({
				top: W._body.scrollTop
			}, '');

			// Reset URL to exclude root
			a.href = request.url;

			request.url = _path(a);
			conf.request = request;

			// Request partial Ajax
			if (request.url) {
				var sendEvents = [],
					successEvents = [],
					errorEvents = [],
					completeEvents = [],
					partials = conf.partials,
					targets = W.$(partials);

				// Set Pjax header
				request.headers = request.headers || {};
				request.headers['X-PJAX'] = 'true';

				// Process send events
				if (request.send) {
					sendEvents.push(request.send);
				}

				if (globalRequest.send) {
					sendEvents.push(globalRequest.send);
				}

				request.send = sendEvents;

				// Compile success events
				successEvents.push(function(html) {
					if (conf.replace) {
						html = W.$exec(conf.replace, {
							args: [html]
						}) || html;
					}

					// Evaluate unload routes against updated path
					if (W.routes && conf.run) {
						W.routes.run({
							event: 'unload',
							path: path
						});
					}

					if (partials) {
						html = W.$parseHTML('' + html + '').firstChild;

						// Make partial replacements from response
						W.$each(partials.split(','), function(sel) {
							W.$each(sel, function(el) {
								var target = W.$(sel)[0];

								if (target) {
									var parent = target.parentNode;

									conf.action == 'append' ?
										parent.appendChild(el) :
										parent.replaceChild(el, target);

									_reset(parent);
								}
							}, {
								context: html
							});
						});
					} else {
						targets.innerHTML = html;

						_reset(targets);
					}
				});

				if (request.success) {
					successEvents.push(request.success);
				}

				if (globalRequest.success) {
					successEvents.push(globalRequest.success);
				}

				successEvents.push(function() {
					var st = conf.scrollTop;

					// Scroll vertically to target
					if (st !== false) {
						var top = 0,
							anim = W.animate;

						if (a.hash) {
							st = a.hash;
						}

						if (typeof st == 'number') {
							top = st;
						} else {
							var el = W.$(st)[0];

							if (el) {
								top = el.getBoundingClientRect().top +
									W._win.pageYOffset;
							}
						}

						if (anim) {
							anim.tween(W._body, {
								scrollTop: top
							});
						} else {
							W._body.scrollTop = top;
						}
					}
				});

				request.success = successEvents;

				// Compile error events
				if (request.error) {
					errorEvents.push(request.error);
				}

				if (globalRequest.error) {
					errorEvents.push(globalRequest.error);
				}

				request.error = errorEvents;

				// Compile complete events
				if (request.complete) {
					completeEvents.push(request.complete);
				}

				if (globalRequest.complete) {
					completeEvents.push(globalRequest.complete);
				}

				completeEvents.push(function(xhr) {
					if (xhr.status == 200) {
						_process(conf);
					}
				});

				request.complete = completeEvents;

				// Make Ajax request
				request.args = request.args || [];
				request.args.unshift(targets);

				D.request(request);
			} else {
				_process(conf);
			}
		}
	};
})(Wee, Wee.data, Wee.events, history, undefined);<|endoftext|>


<commit_before>angular.module("angular-growl").service("growlMessages", ['$sce', '$timeout', function ($sce, $timeout) {
  "use strict";

  this.directives = {};
  this.initDirective = function(referenceId, limitMessages) {
    this.directives[referenceId] = {
      messages: [],
      limitMessages: limitMessages
    };
  };

  this.getAllMessages = function(referenceId) {
    referenceId = referenceId || 0;
    if (this.directives[referenceId]) {
      return this.directives[referenceId].messages;
    } else {
      return [];
    }
  };

  this.destroyAllMessages = function(referenceId) {
    var messages = this.getAllMessages(referenceId);
    for (var i = messages.length - 1; i >= 0; i--) {
      message.destroy();
    }
    if (this.directives[referenceId]) {
      this.directives[referenceId].messages = [];
    }
  };

  this.addMessage = function(message) {
    var directive = this.directives[message.referenceId];
    var messages = directive.messages;
    var found;
    var msgText;

    if (this.onlyUnique) {
      angular.forEach(messages, function(msg) {
        msgText = $sce.getTrustedHtml(msg.text);
        if (message.text === msgText &&
              message.severity === msg.severity &&
                msg.title === msg.title) {
          found = true;
        }
      });

      if (found) {
        return;
      }
    }

    message.text = $sce.trustAsHtml(String(message.text));

    /**If message closes on timeout, add's promises array for
      timeouts to stop close. Also sets message.closeoutTimer to ttl / 1000
    **/
    if(message.ttl && message.ttl !== -1) {
      message.countdown = message.ttl / 1000;
      message.promises = [];
      message.close = false;
      message.countdownFunction = function() {
        if(message.countdown > 1){
          message.countdown--;
          message.promises.push($timeout(message.countdownFunction, 1000));
        } else {
          message.countdown--;
        }
      };
    }

    /** Limit the amount of messages in the container **/
    if (angular.isDefined(directive.limitMessages)) {
      var diff = messages.length - (directive.limitMessages - 1);
      if (diff > 0) {
        messages.splice(directive.limitMessages - 1, diff);
      }
    }

    /** abillity to reverse order (newest first ) **/
    if (this.reverseOrder) {
      messages.unshift(message);
    } else {
      messages.push(message);
    }

    if(typeof(message.onopen) === 'function') {
      message.onopen();
    }

    if (message.ttl && message.ttl !== -1) {
      //adds message timeout to promises and starts messages countdown function.
      message.promises.push($timeout(angular.bind(this, function() {
        this.deleteMessage(message);
      }), message.ttl));
      message.promises.push($timeout(message.countdownFunction, 1000));
    }

    return message;
  };

  this.deleteMessage = function(message) {
    var messages = this.directives[message.referenceId].messages;
    var index = messages.indexOf(message);
    if (index > -1) {
      messages[index].close = true;
      messages.splice(index, 1);
    }

    if(typeof(message.onclose) === 'function') {
      message.onclose();
    }
  };
}]);
<commit_msg>destroy all messages with splice<commit_after>angular.module("angular-growl").service("growlMessages", ['$sce', '$timeout', function ($sce, $timeout) {
  "use strict";

  this.directives = {};
  this.initDirective = function(referenceId, limitMessages) {
    this.directives[referenceId] = {
      messages: [],
      limitMessages: limitMessages
    };
  };

  this.getAllMessages = function(referenceId) {
    referenceId = referenceId || 0;
    if (this.directives[referenceId]) {
      return this.directives[referenceId].messages;
    } else {
      return [];
    }
  };

  this.destroyAllMessages = function(referenceId) {
    var messages = this.getAllMessages(referenceId);
    for (var i = messages.length - 1; i >= 0; i--) {
      messages[i].destroy();
    }
    if (this.directives[referenceId]) {
      this.directives[referenceId].messages = [];
    }
  };

  this.addMessage = function(message) {
    var directive = this.directives[message.referenceId];
    var messages = directive.messages;
    var found;
    var msgText;

    if (this.onlyUnique) {
      angular.forEach(messages, function(msg) {
        msgText = $sce.getTrustedHtml(msg.text);
        if (message.text === msgText &&
              message.severity === msg.severity &&
                msg.title === msg.title) {
          found = true;
        }
      });

      if (found) {
        return;
      }
    }

    message.text = $sce.trustAsHtml(String(message.text));

    /**If message closes on timeout, add's promises array for
      timeouts to stop close. Also sets message.closeoutTimer to ttl / 1000
    **/
    if(message.ttl && message.ttl !== -1) {
      message.countdown = message.ttl / 1000;
      message.promises = [];
      message.close = false;
      message.countdownFunction = function() {
        if(message.countdown > 1){
          message.countdown--;
          message.promises.push($timeout(message.countdownFunction, 1000));
        } else {
          message.countdown--;
        }
      };
    }

    /** Limit the amount of messages in the container **/
    if (angular.isDefined(directive.limitMessages)) {
      var diff = messages.length - (directive.limitMessages - 1);
      if (diff > 0) {
        messages.splice(directive.limitMessages - 1, diff);
      }
    }

    /** abillity to reverse order (newest first ) **/
    if (this.reverseOrder) {
      messages.unshift(message);
    } else {
      messages.push(message);
    }

    if(typeof(message.onopen) === 'function') {
      message.onopen();
    }

    if (message.ttl && message.ttl !== -1) {
      //adds message timeout to promises and starts messages countdown function.
      message.promises.push($timeout(angular.bind(this, function() {
        this.deleteMessage(message);
      }), message.ttl));
      message.promises.push($timeout(message.countdownFunction, 1000));
    }

    return message;
  };

  this.deleteMessage = function(message) {
    var messages = this.directives[message.referenceId].messages;
    var index = messages.indexOf(message);
    if (index > -1) {
      messages[index].close = true;
      messages.splice(index, 1);
    }

    if(typeof(message.onclose) === 'function') {
      message.onclose();
    }
  };
}]);
<|endoftext|>


<commit_before>/** Developer settings and other provisions.
 *
 * An empty copy of this file should be used for production releases.
 */

/* Copyright 2012 SpiderOak, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

/** SO_DEBUGGING has string parameters for debugging operation.
 *
 * Only the "basic" setting should be checked in.
 *
 * Include any non-empty string for general debugging messages.
 * ":verbose:" - additonal, UI-visible messages status messages
 * ":test_keychain_trivial:" - elementary keychain plugin test
 */
SO_DEBUGGING = ":basic: :content_urls: -test_keychain_trivial -verbose";
<commit_msg>Provide an invaluable javascript read/eval/print loop, for poking and prodding in the device context.<commit_after>/** Developer settings and other provisions.
 *
 * An empty copy of this file should be used for production releases.
 */

/* Copyright 2012 SpiderOak, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

/** SO_DEBUGGING has string parameters for debugging operation.
 *
 * Only the "basic" setting should be checked in.
 *
 * Include any non-empty string for general debugging messages.
 * ":verbose:" - additonal, UI-visible messages status messages
 * ":repl:" - pop up a read/eval/print loop, when repl activation entered (see
 *            "repl_key", below)
 * ":content_urls:" - log content urls as they're traversed
 * ":test_keychain_trivial:" - elementary keychain plugin test
 */
SO_DEBUGGING = ":basic: :content_urls: :repl: -test_keychain_trivial- -verbose-";

if (SO_DEBUGGING.match(/:repl:/)) {
    /** Simple javascript read/eval/print loop, for poking and prodding.
     *
     * Runs in a javascript prompt().
     */
    function repl() {
        var repl_expr = "", repl_result = "", repl_error;
        while (repl_expr = prompt(repl_result + "" || "", "")) {
            try {
                repl_result = eval(repl_expr);
            } catch(e) {
                repl_result = "! " + e;
            }
        }
    }

    /** Launch repl when cue is noticed
     *
     * See cue variable for the cue phrase.
     *
     * We retain only the last character of input.
     */
    replSentinel = function () {
        // Only upcase alphabetics - they map to lower case on the device!
        var cue = "REPLPLEASE",
            cue_at = 0;
        return {
            poll: function(repl_poll_event) {
                var currkey = repl_poll_event.keyCode;
                if (cue.charCodeAt(cue_at) === currkey) {
                    cue_at += 1;
                    if (cue.length === cue_at) {
                        //console.log("repl cue satisfied");
                        repl();
                    } else {
                        //console.log("repl sentinel increment to: " + cue_at);
                        ;
                    }
                } else {
                    cue_at = 0;
                }
            },
        }
    }()
    $(document).bind("keydown", replSentinel.poll);
}
<|endoftext|>


<commit_before>/**
 * Created by Nitai J. Perez
 * nitai.perez@ironsrc.com
 * 02/07/2015.
 */

function setBadge(text, title, color, nText) {
    if (text.toString()) chrome.browserAction.setBadgeText({text: text.toString()});
    if (title.toString()) chrome.browserAction.setTitle({title: title.toString()});
    if (color)chrome.browserAction.setBadgeBackgroundColor({color: color});
    if (nText) chrome.notifications.create(Date.now() + "", {
        type: "basic",
        iconUrl: "icon/clock.png",
        title: "Snel",
        eventTime: Date.now(),
        message: nText
    });
}

function clearBadge() {
    chrome.browserAction.setBadgeText({text: ""});
}

function errHandle(err) {
    setBadge("ERR", err, "#000000");
}

function loginErr(errText) {
    errHandle(errText || "Login error, check credentials and connection.");
}<commit_msg>Minor bugfix in handling of nulls with badgeHelper.<commit_after>/**
 * Created by Nitai J. Perez
 * nitai.perez@ironsrc.com
 * 02/07/2015.
 */

function setBadge(text, title, color, nText) {
    if (text && text.toString()) chrome.browserAction.setBadgeText({text: text.toString()});
    if (title && title.toString()) chrome.browserAction.setTitle({title: title.toString()});
    if (color)chrome.browserAction.setBadgeBackgroundColor({color: color});
    if (nText) chrome.notifications.create(Date.now() + "", {
        type: "basic",
        iconUrl: "icon/clock.png",
        title: "Snel",
        eventTime: Date.now(),
        message: nText
    });
}

function clearBadge() {
    chrome.browserAction.setBadgeText({text: ""});
}

function errHandle(err) {
    setBadge("ERR", err, "#000000");
}

function loginErr(errText) {
    errHandle(errText || "Login error, check credentials and connection.");
}<|endoftext|>


<commit_before>'use strict';

angular.module('mgcrea.ngStrap.helpers.dateParser', [])

.provider('$dateParser', function ($localeProvider) {

  // define a custom ParseDate object to use instead of native Date
  // to avoid date values wrapping when setting date component values
  function ParseDate () {
    this.year = 1970;
    this.month = 0;
    this.day = 1;
    this.hours = 0;
    this.minutes = 0;
    this.seconds = 0;
    this.milliseconds = 0;
  }

  ParseDate.prototype.setMilliseconds = function (value) { this.milliseconds = value; };
  ParseDate.prototype.setSeconds = function (value) { this.seconds = value; };
  ParseDate.prototype.setMinutes = function (value) { this.minutes = value; };
  ParseDate.prototype.setHours = function (value) { this.hours = value; };
  ParseDate.prototype.getHours = function () { return this.hours; };
  ParseDate.prototype.setDate = function (value) { this.day = value; };
  ParseDate.prototype.setMonth = function (value) { this.month = value; };
  ParseDate.prototype.setFullYear = function (value) { this.year = value; };
  ParseDate.prototype.fromDate = function (value) {
    this.year = value.getFullYear();
    this.month = value.getMonth();
    this.day = value.getDate();
    this.hours = value.getHours();
    this.minutes = value.getMinutes();
    this.seconds = value.getSeconds();
    this.milliseconds = value.getMilliseconds();
    return this;
  };

  ParseDate.prototype.toDate = function () {
    return new Date(this.year, this.month, this.day, this.hours, this.minutes, this.seconds, this.milliseconds);
  };

  var proto = ParseDate.prototype;

  function noop () {
  }

  function isNumeric (n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }

  function indexOfCaseInsensitive (array, value) {
    var len = array.length;
    var str = value.toString().toLowerCase();
    for (var i = 0; i < len; i++) {
      if (array[i].toLowerCase() === str) { return i; }
    }
    return -1; // Return -1 per the "Array.indexOf()" method.
  }

  var defaults = this.defaults = {
    format: 'shortDate',
    strict: false
  };

  this.$get = function ($locale, dateFilter) {

    var DateParserFactory = function (config) {

      var options = angular.extend({}, defaults, config);

      var $dateParser = {};

      /* eslint-disable key-spacing, quote-props */
      var regExpMap = {
        'sss'   : '[0-9]{3}',
        'ss'    : '[0-5][0-9]',
        's'     : options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]',
        'mm'    : '[0-5][0-9]',
        'm'     : options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]',
        'HH'    : '[01][0-9]|2[0-3]',
        'H'     : options.strict ? '1?[0-9]|2[0-3]' : '[01]?[0-9]|2[0-3]',
        'hh'    : '[0][1-9]|[1][012]',
        'h'     : options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]',
        'a'     : 'AM|PM',
        'EEEE'  : $locale.DATETIME_FORMATS.DAY.join('|'),
        'EEE'   : $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
        'dd'    : '0[1-9]|[12][0-9]|3[01]',
        'd'     : options.strict ? '[1-9]|[1-2][0-9]|3[01]' : '0?[1-9]|[1-2][0-9]|3[01]',
        'MMMM'  : $locale.DATETIME_FORMATS.MONTH.join('|'),
        'MMM'   : $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
        'MM'    : '0[1-9]|1[012]',
        'M'     : options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]',
        'yyyy'  : '[1]{1}[0-9]{3}|[2]{1}[0-9]{3}',
        'yy'    : '[0-9]{2}',
        'y'     : options.strict ? '-?(0|[1-9][0-9]{0,3})' : '-?0*[0-9]{1,4}'
      };

      var setFnMap = {
        'sss'   : proto.setMilliseconds,
        'ss'    : proto.setSeconds,
        's'     : proto.setSeconds,
        'mm'    : proto.setMinutes,
        'm'     : proto.setMinutes,
        'HH'    : proto.setHours,
        'H'     : proto.setHours,
        'hh'    : proto.setHours,
        'h'     : proto.setHours,
        'EEEE'  : noop,
        'EEE'   : noop,
        'dd'    : proto.setDate,
        'd'     : proto.setDate,
        'a'     : function (value) { var hours = this.getHours() % 12; return this.setHours(value.match(/pm/i) ? hours + 12 : hours); },
        'MMMM'  : function (value) { return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.MONTH, value)); },
        'MMM'   : function (value) { return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.SHORTMONTH, value)); },
        'MM'    : function (value) { return this.setMonth(1 * value - 1); },
        'M'     : function (value) { return this.setMonth(1 * value - 1); },
        'yyyy'  : proto.setFullYear,
        'yy'    : function (value) { return this.setFullYear(2000 + 1 * value); },
        'y'     : function (value) { return (1 * value <= 50 && value.length === 2) ? this.setFullYear(2000 + 1 * value) : this.setFullYear(1 * value); }
      };
      /* eslint-enable key-spacing, quote-props */

      var regex;
      var setMap;

      $dateParser.init = function () {
        $dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format;
        regex = regExpForFormat($dateParser.$format);
        setMap = setMapForFormat($dateParser.$format);
      };

      $dateParser.isValid = function (date) {
        if (angular.isDate(date)) return !isNaN(date.getTime());
        return regex.test(date);
      };

      $dateParser.parse = function (value, baseDate, format, timezone) {
        // check for date format special names
        if (format) format = $locale.DATETIME_FORMATS[format] || format;
        if (angular.isDate(value)) value = dateFilter(value, format || $dateParser.$format, timezone);
        var formatRegex = format ? regExpForFormat(format) : regex;
        var formatSetMap = format ? setMapForFormat(format) : setMap;
        var matches = formatRegex.exec(value);
        if (!matches) return false;
        // use custom ParseDate object to set parsed values
        var date = baseDate && !isNaN(baseDate.getTime()) ? new ParseDate().fromDate(baseDate) : new ParseDate().fromDate(new Date(1970, 0, 1, 0));
        for (var i = 0; i < matches.length - 1; i++) {
          if (formatSetMap[i]) formatSetMap[i].call(date, matches[i + 1]);
        }
        // convert back to native Date object
        var newDate = date.toDate();

        // check new native Date object for day values overflow
        if (parseInt(date.day, 10) !== newDate.getDate()) {
          return false;
        }

        return newDate;
      };

      $dateParser.getDateForAttribute = function (key, value) {
        var date;

        if (value === 'today') {
          var today = new Date();
          date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + (key === 'maxDate' ? 1 : 0), 0, 0, 0, (key === 'minDate' ? 0 : -1));
        } else if (angular.isString(value) && value.match(/^".+"$/)) { // Support {{ dateObj }}
          date = new Date(value.substr(1, value.length - 2));
        } else if (isNumeric(value)) {
          date = new Date(parseInt(value, 10));
        } else if (angular.isString(value) && value.length === 0) { // Reset date
          date = key === 'minDate' ? -Infinity : +Infinity;
        } else {
          date = new Date(value);
        }

        return date;
      };

      $dateParser.getTimeForAttribute = function (key, value) {
        var time;

        if (value === 'now') {
          time = new Date().setFullYear(1970, 0, 1);
        } else if (angular.isString(value) && value.match(/^".+"$/)) {
          time = new Date(value.substr(1, value.length - 2)).setFullYear(1970, 0, 1);
        } else if (isNumeric(value)) {
          time = new Date(parseInt(value, 10)).setFullYear(1970, 0, 1);
        } else if (angular.isString(value) && value.length === 0) { // Reset time
          time = key === 'minTime' ? -Infinity : +Infinity;
        } else {
          time = $dateParser.parse(value, new Date(1970, 0, 1, 0));
        }

        return time;
      };

      /* Handle switch to/from daylight saving.
      * Hours may be non-zero on daylight saving cut-over:
      * > 12 when midnight changeover, but then cannot generate
      * midnight datetime, so jump to 1AM, otherwise reset.
      * @param  date  (Date) the date to check
      * @return  (Date) the corrected date
      *
      * __ copied from jquery ui datepicker __
      */
      $dateParser.daylightSavingAdjust = function (date) {
        if (!date) {
          return null;
        }
        date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
        return date;
      };

      /* Correct the date for timezone offset.
      * @param  date  (Date) the date to adjust
      * @param  timezone  (string) the timezone to adjust for
      * @param  undo  (boolean) to add or subtract timezone offset
      * @return  (Date) the corrected date
      */
      $dateParser.timezoneOffsetAdjust = function (date, timezone, undo) {
        if (!date) {
          return null;
        }
        // Right now, only 'UTC' is supported.
        if (timezone && timezone === 'UTC') {
          date = new Date(date.getTime());
          date.setMinutes(date.getMinutes() + (undo ? -1 : 1) * date.getTimezoneOffset());
        }
        return date;
      };

      // Private functions

      function regExpForFormat (format) {
        // `format` string can contain literal values.
        // These need to be escaped by surrounding with
        // single quotes (e.g. `"h 'in the morning'"`).
        // In order to output a single quote, escape it - i.e.,
        // two single quotes in a sequence (e.g. `"h 'o''clock'"`).

        var re = buildDateAbstractRegex(format);
        return buildDateParseRegex(re);
      }

      function buildDateAbstractRegex (format) {
        var escapedFormat = escapeReservedSymbols(format);
        var escapedLiteralFormat = escapedFormat.replace(/''/g, '\\\'');
        var literalRegex = /('(?:\\'|.)*?')/;
        var formatParts = escapedLiteralFormat.split(literalRegex);
        var dateElements = Object.keys(regExpMap);
        var dateRegexParts = [];

        angular.forEach(formatParts, function (part) {
          if (isFormatStringLiteral(part)) {
            part = trimLiteralEscapeChars(part);
          } else {
            // Abstract replaces to avoid collisions
            for (var i = 0; i < dateElements.length; i++) {
              part = part.split(dateElements[i]).join('${' + i + '}');
            }
          }
          dateRegexParts.push(part);
        });

        return dateRegexParts.join('');
      }

      function escapeReservedSymbols (text) {
        return text.replace(/\\/g, '[\\\\]')
                   .replace(/-/g, '[-]')
                   .replace(/\./g, '[.]')
                   .replace(/\*/g, '[*]')
                   .replace(/\+/g, '[+]')
                   .replace(/\?/g, '[?]')
                   .replace(/\$/g, '[$]')
                   .replace(/\^/g, '[^]')
                   .replace(/\//g, '[/]')
                   .replace(/\\s/g, '[\\s]');
      }

      function isFormatStringLiteral (text) {
        return /^'.*'$/.test(text);
      }

      function trimLiteralEscapeChars (text) {
        return text.replace(/^'(.*)'$/, '$1');
      }

      function buildDateParseRegex (abstractRegex) {
        var dateElements = Object.keys(regExpMap);
        var re = abstractRegex;

        // Replace abstracted values
        for (var i = 0; i < dateElements.length; i++) {
          re = re.split('${' + i + '}').join('(' + regExpMap[dateElements[i]] + ')');
        }

        return new RegExp('^' + re + '$', ['i']);
      }

      function setMapForFormat (format) {
        var re = buildDateAbstractRegex(format);
        return buildDateParseValuesMap(re);
      }

      function buildDateParseValuesMap (abstractRegex) {
        var dateElements = Object.keys(regExpMap);
        var valuesRegex = new RegExp('\\${(\\d+)}', 'g');
        var valuesMatch;
        var keyIndex;
        var valueKey;
        var valueFunction;
        var valuesFunctionMap = [];

        /* eslint-disable no-cond-assign */
        while ((valuesMatch = valuesRegex.exec(abstractRegex)) !== null) {
          keyIndex = valuesMatch[1];
          valueKey = dateElements[keyIndex];
          valueFunction = setFnMap[valueKey];

          valuesFunctionMap.push(valueFunction);
        }

        return valuesFunctionMap;
      }

      $dateParser.init();
      return $dateParser;

    };

    return DateParserFactory;

  };

});
<commit_msg>fix(datepicker): unable to select the same date as minDate (#2266)<commit_after>'use strict';

angular.module('mgcrea.ngStrap.helpers.dateParser', [])

.provider('$dateParser', function ($localeProvider) {

  // define a custom ParseDate object to use instead of native Date
  // to avoid date values wrapping when setting date component values
  function ParseDate () {
    this.year = 1970;
    this.month = 0;
    this.day = 1;
    this.hours = 0;
    this.minutes = 0;
    this.seconds = 0;
    this.milliseconds = 0;
  }

  ParseDate.prototype.setMilliseconds = function (value) { this.milliseconds = value; };
  ParseDate.prototype.setSeconds = function (value) { this.seconds = value; };
  ParseDate.prototype.setMinutes = function (value) { this.minutes = value; };
  ParseDate.prototype.setHours = function (value) { this.hours = value; };
  ParseDate.prototype.getHours = function () { return this.hours; };
  ParseDate.prototype.setDate = function (value) { this.day = value; };
  ParseDate.prototype.setMonth = function (value) { this.month = value; };
  ParseDate.prototype.setFullYear = function (value) { this.year = value; };
  ParseDate.prototype.fromDate = function (value) {
    this.year = value.getFullYear();
    this.month = value.getMonth();
    this.day = value.getDate();
    this.hours = value.getHours();
    this.minutes = value.getMinutes();
    this.seconds = value.getSeconds();
    this.milliseconds = value.getMilliseconds();
    return this;
  };

  ParseDate.prototype.toDate = function () {
    return new Date(this.year, this.month, this.day, this.hours, this.minutes, this.seconds, this.milliseconds);
  };

  var proto = ParseDate.prototype;

  function noop () {
  }

  function isNumeric (n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }

  function indexOfCaseInsensitive (array, value) {
    var len = array.length;
    var str = value.toString().toLowerCase();
    for (var i = 0; i < len; i++) {
      if (array[i].toLowerCase() === str) { return i; }
    }
    return -1; // Return -1 per the "Array.indexOf()" method.
  }

  var defaults = this.defaults = {
    format: 'shortDate',
    strict: false
  };

  this.$get = function ($locale, dateFilter) {

    var DateParserFactory = function (config) {

      var options = angular.extend({}, defaults, config);

      var $dateParser = {};

      /* eslint-disable key-spacing, quote-props */
      var regExpMap = {
        'sss'   : '[0-9]{3}',
        'ss'    : '[0-5][0-9]',
        's'     : options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]',
        'mm'    : '[0-5][0-9]',
        'm'     : options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]',
        'HH'    : '[01][0-9]|2[0-3]',
        'H'     : options.strict ? '1?[0-9]|2[0-3]' : '[01]?[0-9]|2[0-3]',
        'hh'    : '[0][1-9]|[1][012]',
        'h'     : options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]',
        'a'     : 'AM|PM',
        'EEEE'  : $locale.DATETIME_FORMATS.DAY.join('|'),
        'EEE'   : $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
        'dd'    : '0[1-9]|[12][0-9]|3[01]',
        'd'     : options.strict ? '[1-9]|[1-2][0-9]|3[01]' : '0?[1-9]|[1-2][0-9]|3[01]',
        'MMMM'  : $locale.DATETIME_FORMATS.MONTH.join('|'),
        'MMM'   : $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
        'MM'    : '0[1-9]|1[012]',
        'M'     : options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]',
        'yyyy'  : '[1]{1}[0-9]{3}|[2]{1}[0-9]{3}',
        'yy'    : '[0-9]{2}',
        'y'     : options.strict ? '-?(0|[1-9][0-9]{0,3})' : '-?0*[0-9]{1,4}'
      };

      var setFnMap = {
        'sss'   : proto.setMilliseconds,
        'ss'    : proto.setSeconds,
        's'     : proto.setSeconds,
        'mm'    : proto.setMinutes,
        'm'     : proto.setMinutes,
        'HH'    : proto.setHours,
        'H'     : proto.setHours,
        'hh'    : proto.setHours,
        'h'     : proto.setHours,
        'EEEE'  : noop,
        'EEE'   : noop,
        'dd'    : proto.setDate,
        'd'     : proto.setDate,
        'a'     : function (value) { var hours = this.getHours() % 12; return this.setHours(value.match(/pm/i) ? hours + 12 : hours); },
        'MMMM'  : function (value) { return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.MONTH, value)); },
        'MMM'   : function (value) { return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.SHORTMONTH, value)); },
        'MM'    : function (value) { return this.setMonth(1 * value - 1); },
        'M'     : function (value) { return this.setMonth(1 * value - 1); },
        'yyyy'  : proto.setFullYear,
        'yy'    : function (value) { return this.setFullYear(2000 + 1 * value); },
        'y'     : function (value) { return (1 * value <= 50 && value.length === 2) ? this.setFullYear(2000 + 1 * value) : this.setFullYear(1 * value); }
      };
      /* eslint-enable key-spacing, quote-props */

      var regex;
      var setMap;

      $dateParser.init = function () {
        $dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format;
        regex = regExpForFormat($dateParser.$format);
        setMap = setMapForFormat($dateParser.$format);
      };

      $dateParser.isValid = function (date) {
        if (angular.isDate(date)) return !isNaN(date.getTime());
        return regex.test(date);
      };

      $dateParser.parse = function (value, baseDate, format, timezone) {
        // check for date format special names
        if (format) format = $locale.DATETIME_FORMATS[format] || format;
        if (angular.isDate(value)) value = dateFilter(value, format || $dateParser.$format, timezone);
        var formatRegex = format ? regExpForFormat(format) : regex;
        var formatSetMap = format ? setMapForFormat(format) : setMap;
        var matches = formatRegex.exec(value);
        if (!matches) return false;
        // use custom ParseDate object to set parsed values
        var date = baseDate && !isNaN(baseDate.getTime()) ? new ParseDate().fromDate(baseDate) : new ParseDate().fromDate(new Date(1970, 0, 1, 0));
        for (var i = 0; i < matches.length - 1; i++) {
          if (formatSetMap[i]) formatSetMap[i].call(date, matches[i + 1]);
        }
        // convert back to native Date object
        var newDate = date.toDate();

        // check new native Date object for day values overflow
        if (parseInt(date.day, 10) !== newDate.getDate()) {
          return false;
        }

        return newDate;
      };

      $dateParser.getDateForAttribute = function (key, value) {
        var date;

        if (value === 'today') {
          var today = new Date();
          date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + (key === 'maxDate' ? 1 : 0), 0, 0, 0, (key === 'minDate' ? 0 : -1));
        } else if (angular.isString(value) && value.match(/^".+"$/)) { // Support {{ dateObj }}
          if (value.match(/Z/)) {
            date = new Date(value.substr(1, value.length - 3));
          } else {
            date = new Date(value.substr(1, value.length - 2));
          }
        } else if (isNumeric(value)) {
          date = new Date(parseInt(value, 10));
        } else if (angular.isString(value) && value.length === 0) { // Reset date
          date = key === 'minDate' ? -Infinity : +Infinity;
        } else {
          date = new Date(value);
        }

        return date;
      };

      $dateParser.getTimeForAttribute = function (key, value) {
        var time;

        if (value === 'now') {
          time = new Date().setFullYear(1970, 0, 1);
        } else if (angular.isString(value) && value.match(/^".+"$/)) {
          time = new Date(value.substr(1, value.length - 2)).setFullYear(1970, 0, 1);
        } else if (isNumeric(value)) {
          time = new Date(parseInt(value, 10)).setFullYear(1970, 0, 1);
        } else if (angular.isString(value) && value.length === 0) { // Reset time
          time = key === 'minTime' ? -Infinity : +Infinity;
        } else {
          time = $dateParser.parse(value, new Date(1970, 0, 1, 0));
        }

        return time;
      };

      /* Handle switch to/from daylight saving.
      * Hours may be non-zero on daylight saving cut-over:
      * > 12 when midnight changeover, but then cannot generate
      * midnight datetime, so jump to 1AM, otherwise reset.
      * @param  date  (Date) the date to check
      * @return  (Date) the corrected date
      *
      * __ copied from jquery ui datepicker __
      */
      $dateParser.daylightSavingAdjust = function (date) {
        if (!date) {
          return null;
        }
        date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
        return date;
      };

      /* Correct the date for timezone offset.
      * @param  date  (Date) the date to adjust
      * @param  timezone  (string) the timezone to adjust for
      * @param  undo  (boolean) to add or subtract timezone offset
      * @return  (Date) the corrected date
      */
      $dateParser.timezoneOffsetAdjust = function (date, timezone, undo) {
        if (!date) {
          return null;
        }
        // Right now, only 'UTC' is supported.
        if (timezone && timezone === 'UTC') {
          date = new Date(date.getTime());
          date.setMinutes(date.getMinutes() + (undo ? -1 : 1) * date.getTimezoneOffset());
        }
        return date;
      };

      // Private functions

      function regExpForFormat (format) {
        // `format` string can contain literal values.
        // These need to be escaped by surrounding with
        // single quotes (e.g. `"h 'in the morning'"`).
        // In order to output a single quote, escape it - i.e.,
        // two single quotes in a sequence (e.g. `"h 'o''clock'"`).

        var re = buildDateAbstractRegex(format);
        return buildDateParseRegex(re);
      }

      function buildDateAbstractRegex (format) {
        var escapedFormat = escapeReservedSymbols(format);
        var escapedLiteralFormat = escapedFormat.replace(/''/g, '\\\'');
        var literalRegex = /('(?:\\'|.)*?')/;
        var formatParts = escapedLiteralFormat.split(literalRegex);
        var dateElements = Object.keys(regExpMap);
        var dateRegexParts = [];

        angular.forEach(formatParts, function (part) {
          if (isFormatStringLiteral(part)) {
            part = trimLiteralEscapeChars(part);
          } else {
            // Abstract replaces to avoid collisions
            for (var i = 0; i < dateElements.length; i++) {
              part = part.split(dateElements[i]).join('${' + i + '}');
            }
          }
          dateRegexParts.push(part);
        });

        return dateRegexParts.join('');
      }

      function escapeReservedSymbols (text) {
        return text.replace(/\\/g, '[\\\\]')
                   .replace(/-/g, '[-]')
                   .replace(/\./g, '[.]')
                   .replace(/\*/g, '[*]')
                   .replace(/\+/g, '[+]')
                   .replace(/\?/g, '[?]')
                   .replace(/\$/g, '[$]')
                   .replace(/\^/g, '[^]')
                   .replace(/\//g, '[/]')
                   .replace(/\\s/g, '[\\s]');
      }

      function isFormatStringLiteral (text) {
        return /^'.*'$/.test(text);
      }

      function trimLiteralEscapeChars (text) {
        return text.replace(/^'(.*)'$/, '$1');
      }

      function buildDateParseRegex (abstractRegex) {
        var dateElements = Object.keys(regExpMap);
        var re = abstractRegex;

        // Replace abstracted values
        for (var i = 0; i < dateElements.length; i++) {
          re = re.split('${' + i + '}').join('(' + regExpMap[dateElements[i]] + ')');
        }

        return new RegExp('^' + re + '$', ['i']);
      }

      function setMapForFormat (format) {
        var re = buildDateAbstractRegex(format);
        return buildDateParseValuesMap(re);
      }

      function buildDateParseValuesMap (abstractRegex) {
        var dateElements = Object.keys(regExpMap);
        var valuesRegex = new RegExp('\\${(\\d+)}', 'g');
        var valuesMatch;
        var keyIndex;
        var valueKey;
        var valueFunction;
        var valuesFunctionMap = [];

        /* eslint-disable no-cond-assign */
        while ((valuesMatch = valuesRegex.exec(abstractRegex)) !== null) {
          keyIndex = valuesMatch[1];
          valueKey = dateElements[keyIndex];
          valueFunction = setFnMap[valueKey];

          valuesFunctionMap.push(valueFunction);
        }

        return valuesFunctionMap;
      }

      $dateParser.init();
      return $dateParser;

    };

    return DateParserFactory;

  };

});
<|endoftext|>


<commit_before>/*
 *  jQuery Image Upload
 *
 *  A jQuery plugin that adds controls to the selected jQuery
 *  elements with a simple call.
 *
 *  Example:
 *
 *      $("img").imageUpload();
 *
 *  Copyright (c) jillix GmbH
 *  License: MIT License
 *
 * */
(function ($) {

    // defaults
    var defaults = {
        wrapContent: "
",

        inputFileName: "inputFile",
        inputFileClass: "inputFile",

        uploadButtonValue: "Upload",
        uploadButtonClass: "uploadButton",

        browseButtonValue: "Browse",
        browseButtonClass: "browseButton",

        deleteButtonValue: "Delete image",
        deleteButtonClass: "deleteButton",

        automaticUpload: false,

        formClass: "controlForm",

        hideFileInput: true,
        hideDeleteButton: false,

        hover: true,

        addClass: "jQuery-image-upload"
    };

   /*
    * $("[jQuery selector]").imageUpload({...});
    * */
    $.fn.imageUpload = function (options) {

        // selected jQuery objects
        var $self = this;

        // return if no elements
        if (!$self.length) { return $self; }

        // defaults
        var settings = $.extend(defaults, options);

        // call image upload for each element
        if ($self.length > 1) {
            $self.each(function () {
                $(this).imageUpload(settings);
            });
            return $self;
        }

        // reload imageUpload if it was already created
        if ($self.data("imageUpload")) {
            $self.trigger("imageUpload.reload");
            return $self;
        }

        // add class
        $self.addClass(settings.addClass);

        // set imageUpload data
        $self.data("imageUpload", options);

        // form action not provided
        if (!settings.formAction) {
            throw new Error ("Form action was not provided. Please provide it: $(...).imageUpload({formAction: '...'})");
        }

        // wrap
        if (!settings.hover) {
            $self.wrap(settings.wrapContent)
        }

        // create the control div
        var $controls = $("
").addClass("controls");

        // create the file input element
        var $fileInput = $("<input>")
                            .attr({
                                "type": "file",
                                "name": settings.inputFileName
                            })
                            .addClass(settings.inputFileClass)

        // create the upload button
        var $uploadButton = $("<button>")
                                .attr("type", "submit")
                                .addClass(settings.uploadButtonClass)
                                .html(settings.uploadButtonValue);

        // create the browse button
        var $browseButton = $("<button>")
                                .addClass(settings.browseButtonClass)
                                .html(settings.browseButtonValue)
                                .on("click", function () {

                                    // click the file input
                                    $fileInput.click();

                                    // prevent browser's default behavior
                                    return false;
                                });

        // create the delete button
        var $deleteButton = $("<button>")
                                .addClass(settings.deleteButtonClass)
                                .html(settings.deleteButtonValue)
                                .on("click", function () {
                                    // destroy the image upload
                                    $self.trigger("imageUpload.destroy");

                                    // trigger remove event
                                    $self.trigger("imageUpload.imageRemoved");

                                    // and remove the image from dom
                                    $self.remove();

                                    // prevent browser's default behavior
                                    return false;
                                });

        // generate the iframe id
        var iframeId =  "uploadIframe-" + Math
                                            .random()
                                            .toString(36)
                                            .substring(5, 20)
                                            .toLowerCase();

        // create the upload iframe
        var $uploadIframe   = $("")
                                .attr({
                                    "id": iframeId,
                                    "name": iframeId
                                })
                                .hide();

        // create the upload form
        var $uploadForm     = $("<form>")
                                .addClass(settings.formClass)
                                .attr({
                                    "target": $uploadIframe.attr("id"),
                                    "enctype": "multipart/form-data",
                                    "method": "post",
                                    "action": settings.formAction
                                });

        // append controls to form
        $uploadForm.append([$browseButton, $fileInput, $uploadButton, $deleteButton, $uploadIframe]);

        // hide delete button
        if (settings.hideDeleteButton) {

            // we just remove it
            $deleteButton.remove();
        }

        // if automatic upload
        if (settings.automaticUpload) {

            // hide the upload button
            $uploadButton.hide();

            // file input change
            $fileInput.on("change", function () {

                // no file selected, do nothing
                if (!$(this).val()) { return; }

                // start upload
                $uploadButton.click();
            });
        }

        // hide file input
        if (settings.hideFileInput) {
            $fileInput.hide();
        } else {
            // hide browse button
            $browseButton.hide();
        }

        // append $form to $controls
        $controls.append($uploadForm);

        // form on submit
        $uploadForm.on("submit", function () {

            // get submiited form
            var $form = $(this);

            // unset the load handler
            $uploadIframe.off("load");

            // save the old image source in case of error
            var oldSrc = $self.attr("src");

            // Waiter image
            if (typeof settings.waiter === "string") {
                $self.attr("src", settings.waiter);
            }

            $self.addClass("loading");
            $controls.hide();

            // set it again
            $uploadIframe.on("load", function () {

                // get text from the page
                var result = $(this.contentWindow.document).text();

                // the selected file was not a valid image and `result` is not a URL
                if (!/^https?|^\//.test(result)) {
                    loadImage($self, oldSrc);
                    $self.trigger("imageUpload.uploadFailed");
                    return;
                }

                // if no result, return
                if (!result) {
                    loadImage($self, oldSrc);
                    $self.trigger("imageUpload.uploadFailed");
                    return;
                }

                // reload the image upload controls only if the file input is hidden
                if (settings.hideFileInput) {
                    $self.trigger("imageUpload.reload");
                }

                // verify file input value
                if (!$fileInput.val()) {
                    loadImage($self, oldSrc);
                    return;
                }

                // set src of iframe
                $uploadIframe.attr("src", "");

                // update the image source
                loadImage($self, result, function () {
                    // trigger image changed event
                    $self.trigger("imageUpload.imageChanged");
                });

                // replace the file input
                $fileInput.replaceWith($fileInput.clone(true));
            });
        });

        // no hover
        if (!settings.hover) {

            // append controls to image wrapper
            $self.parent().append($controls);
        } else {

            // set absolute position to controls and set the offset
            $controls.css({ position: "absolute" });

            // add class to controls
            $controls.addClass("jQuery-image-upload-controls");

            // append controls to body
            $("body").append($controls.hide());

            // self on mouse enter
            $self.on("mouseenter", function () {

                if ($self.hasClass("loading")) {
                    return;
                }

                // get the self offset
                var offset = $self.offset();

                // set control possition
                $controls.css({
                    top: offset.top,
                    left: offset.left
                });

                // show controls
                $controls.show();
            });

            // on mouse leave
            $("body").on("mouseleave", "." + settings.addClass, function (e) {

                // get position, width and height
                var o = $self.offset();
                var w = $self.width();
                var h = $self.height();

                // hide controls
                if ((e.pageX < o.left || e.pageX > o.left + w) ||
                    (e.pageY < o.top || e.pageY > o.top + h)) {
                    $controls.hide();
                }
            });
        }

        // destroy
        $self.on("imageUpload.destroy", function () {

            // remove controls
            $controls.remove();

            // remove events
            $self.off("imageUpload.destroy");
            $self.off("imageUpload.reload");

            // remove data
            $self.data("imageUpload", null);
        });

        // reload
        $self.on("imageUpload.reload", function () {
            $self.trigger("imageUpload.destroy");
            $self.imageUpload(options);
        });

        // return selected element
        return $self;
    }

    /**
     * Load the image at the URL `newSource` in the `$imageElement` jQuery
     * element with a fade in/out animation, then call the `callback`.
     * @param {jQuery} $imageElement
     * @param {String} newSource
     * @param {Function} callback
     */
    function loadImage ($imageElement, newSource, callback) {
        $imageElement.fadeOut(function () {
            $imageElement.attr("src", newSource);
            imgLoad($imageElement, function () {
                $imageElement.removeClass("loading");
                $imageElement.fadeIn();
                if (typeof callback === "function") {
                    callback();
                }
            });
        });
    }

    /**
     * Trigger a callback when the selected images are loaded:
     * @param {String} selector
     * @param {Function} callback
     */
    function imgLoad (selector, callback) {
        $(selector).each(function () {
            if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
                callback.apply(this);
            }
            else {
                $(this).on('load', function () {
                    callback.apply(this);
                });
            }
        });
    };

    // defaults
    $.imageUpload = $.fn.imageUpload;
    $.imageUpload.defaults = defaults;
})($);
<commit_msg>Remove a check specific to IE 10- (it is a hack)<commit_after>/*
 *  jQuery Image Upload
 *
 *  A jQuery plugin that adds controls to the selected jQuery
 *  elements with a simple call.
 *
 *  Example:
 *
 *      $("img").imageUpload();
 *
 *  Copyright (c) jillix GmbH
 *  License: MIT License
 *
 * */
(function ($) {

    // defaults
    var defaults = {
        wrapContent: "
",

        inputFileName: "inputFile",
        inputFileClass: "inputFile",

        uploadButtonValue: "Upload",
        uploadButtonClass: "uploadButton",

        browseButtonValue: "Browse",
        browseButtonClass: "browseButton",

        deleteButtonValue: "Delete image",
        deleteButtonClass: "deleteButton",

        automaticUpload: false,

        formClass: "controlForm",

        hideFileInput: true,
        hideDeleteButton: false,

        hover: true,

        addClass: "jQuery-image-upload"
    };

   /*
    * $("[jQuery selector]").imageUpload({...});
    * */
    $.fn.imageUpload = function (options) {

        // selected jQuery objects
        var $self = this;

        // return if no elements
        if (!$self.length) { return $self; }

        // defaults
        var settings = $.extend(defaults, options);

        // call image upload for each element
        if ($self.length > 1) {
            $self.each(function () {
                $(this).imageUpload(settings);
            });
            return $self;
        }

        // reload imageUpload if it was already created
        if ($self.data("imageUpload")) {
            $self.trigger("imageUpload.reload");
            return $self;
        }

        // add class
        $self.addClass(settings.addClass);

        // set imageUpload data
        $self.data("imageUpload", options);

        // form action not provided
        if (!settings.formAction) {
            throw new Error ("Form action was not provided. Please provide it: $(...).imageUpload({formAction: '...'})");
        }

        // wrap
        if (!settings.hover) {
            $self.wrap(settings.wrapContent)
        }

        // create the control div
        var $controls = $("
").addClass("controls");

        // create the file input element
        var $fileInput = $("<input>")
                            .attr({
                                "type": "file",
                                "name": settings.inputFileName
                            })
                            .addClass(settings.inputFileClass)

        // create the upload button
        var $uploadButton = $("<button>")
                                .attr("type", "submit")
                                .addClass(settings.uploadButtonClass)
                                .html(settings.uploadButtonValue);

        // create the browse button
        var $browseButton = $("<button>")
                                .addClass(settings.browseButtonClass)
                                .html(settings.browseButtonValue)
                                .on("click", function () {

                                    // click the file input
                                    $fileInput.click();

                                    // prevent browser's default behavior
                                    return false;
                                });

        // create the delete button
        var $deleteButton = $("<button>")
                                .addClass(settings.deleteButtonClass)
                                .html(settings.deleteButtonValue)
                                .on("click", function () {
                                    // destroy the image upload
                                    $self.trigger("imageUpload.destroy");

                                    // trigger remove event
                                    $self.trigger("imageUpload.imageRemoved");

                                    // and remove the image from dom
                                    $self.remove();

                                    // prevent browser's default behavior
                                    return false;
                                });

        // generate the iframe id
        var iframeId =  "uploadIframe-" + Math
                                            .random()
                                            .toString(36)
                                            .substring(5, 20)
                                            .toLowerCase();

        // create the upload iframe
        var $uploadIframe   = $("")
                                .attr({
                                    "id": iframeId,
                                    "name": iframeId
                                })
                                .hide();

        // create the upload form
        var $uploadForm     = $("<form>")
                                .addClass(settings.formClass)
                                .attr({
                                    "target": $uploadIframe.attr("id"),
                                    "enctype": "multipart/form-data",
                                    "method": "post",
                                    "action": settings.formAction
                                });

        // append controls to form
        $uploadForm.append([$browseButton, $fileInput, $uploadButton, $deleteButton, $uploadIframe]);

        // hide delete button
        if (settings.hideDeleteButton) {

            // we just remove it
            $deleteButton.remove();
        }

        // if automatic upload
        if (settings.automaticUpload) {

            // hide the upload button
            $uploadButton.hide();

            // file input change
            $fileInput.on("change", function () {

                // no file selected, do nothing
                if (!$(this).val()) { return; }

                // start upload
                $uploadButton.click();
            });
        }

        // hide file input
        if (settings.hideFileInput) {
            $fileInput.hide();
        } else {
            // hide browse button
            $browseButton.hide();
        }

        // append $form to $controls
        $controls.append($uploadForm);

        // form on submit
        $uploadForm.on("submit", function () {

            // get submiited form
            var $form = $(this);

            // unset the load handler
            $uploadIframe.off("load");

            // save the old image source in case of error
            var oldSrc = $self.attr("src");

            // Waiter image
            if (typeof settings.waiter === "string") {
                $self.attr("src", settings.waiter);
            }

            $self.addClass("loading");
            $controls.hide();

            // set it again
            $uploadIframe.on("load", function () {

                // get text from the page
                var result = $(this.contentWindow.document).text();

                // the selected file was not a valid image and `result` is not a URL
                if (!/^https?|^\//.test(result)) {
                    loadImage($self, oldSrc);
                    $self.trigger("imageUpload.uploadFailed");
                    return;
                }

                // if no result, return
                if (!result) {
                    loadImage($self, oldSrc);
                    $self.trigger("imageUpload.uploadFailed");
                    return;
                }

                // reload the image upload controls only if the file input is hidden
                if (settings.hideFileInput) {
                    $self.trigger("imageUpload.reload");
                }

                // verify file input value
                if (!$fileInput.val()) {
                    loadImage($self, oldSrc);
                    return;
                }

                // set src of iframe
                $uploadIframe.attr("src", "");

                // update the image source
                loadImage($self, result, function () {
                    // trigger image changed event
                    $self.trigger("imageUpload.imageChanged");
                });

                // replace the file input
                $fileInput.replaceWith($fileInput.clone(true));
            });
        });

        // no hover
        if (!settings.hover) {

            // append controls to image wrapper
            $self.parent().append($controls);
        } else {

            // set absolute position to controls and set the offset
            $controls.css({ position: "absolute" });

            // add class to controls
            $controls.addClass("jQuery-image-upload-controls");

            // append controls to body
            $("body").append($controls.hide());

            // self on mouse enter
            $self.on("mouseenter", function () {

                if ($self.hasClass("loading")) {
                    return;
                }

                // get the self offset
                var offset = $self.offset();

                // set control possition
                $controls.css({
                    top: offset.top,
                    left: offset.left
                });

                // show controls
                $controls.show();
            });

            // on mouse leave
            $("body").on("mouseleave", "." + settings.addClass, function (e) {

                // get position, width and height
                var o = $self.offset();
                var w = $self.width();
                var h = $self.height();

                // hide controls
                if ((e.pageX < o.left || e.pageX > o.left + w) ||
                    (e.pageY < o.top || e.pageY > o.top + h)) {
                    $controls.hide();
                }
            });
        }

        // destroy
        $self.on("imageUpload.destroy", function () {

            // remove controls
            $controls.remove();

            // remove events
            $self.off("imageUpload.destroy");
            $self.off("imageUpload.reload");

            // remove data
            $self.data("imageUpload", null);
        });

        // reload
        $self.on("imageUpload.reload", function () {
            $self.trigger("imageUpload.destroy");
            $self.imageUpload(options);
        });

        // return selected element
        return $self;
    }

    /**
     * Load the image at the URL `newSource` in the `$imageElement` jQuery
     * element with a fade in/out animation, then call the `callback`.
     * @param {jQuery} $imageElement
     * @param {String} newSource
     * @param {Function} callback
     */
    function loadImage ($imageElement, newSource, callback) {
        $imageElement.fadeOut(function () {
            $imageElement.attr("src", newSource);
            imgLoad($imageElement, function () {
                $imageElement.removeClass("loading");
                $imageElement.fadeIn();
                if (typeof callback === "function") {
                    callback();
                }
            });
        });
    }

    /**
     * Trigger a callback when the selected images are loaded:
     * @param {String} selector
     * @param {Function} callback
     */
    function imgLoad (selector, callback) {
        $(selector).each(function () {
            if (this.complete) {
                callback.apply(this);
            }
            else {
                $(this).on('load', function () {
                    callback.apply(this);
                });
            }
        });
    };

    // defaults
    $.imageUpload = $.fn.imageUpload;
    $.imageUpload.defaults = defaults;
})($);
<|endoftext|>


<commit_before>AUI().add(
	'sortable',
	function(A) {
		var Lang = A.Lang,

			getClassName = A.ClassNameManager.getClassName,

			NAME = 'sortable',

			DDM = A.DD.DDM,

			CSS_DRAGGING = getClassName(NAME, 'dragging'),
			CSS_HANDLE = getClassName(NAME, 'handle'),
			CSS_ITEM = getClassName(NAME, 'item'),
			CSS_NO_HANDLES = getClassName(NAME, 'no-handles'),
			CSS_PLACEHOLDER = getClassName(NAME, 'placeholder'),
			CSS_PROXY = getClassName(NAME, 'proxy'),
			CSS_SORTABLE = getClassName(NAME);

		var Sortable = function() {
			Sortable.superclass.constructor.apply(this, arguments);
		};

		Sortable.NAME = NAME;

		Sortable.ATTRS = {
			dd: {
				value: {}
			},

			constrain: {},

			container: {
				value: null
			},

			groups: {
				valueFn: function() {
					var instance = this;

					return [A.guid()];
				}
			},

			nodes: {
				value: null,
				setter: function(value) {
					var instance = this;

					var container = instance.get('container');

					if (!(value instanceof A.NodeList)) {
						if(Lang.isString(value)) {
							if (container) {
								value = container.queryAll(value);
							}
							else {
								value = A.all(value);
							}
						}
					}

					if (value instanceof A.NodeList) {
						instance.set('container', value.item(0).get('parentNode'));
					}
					else {
						value = A.Attribute.INVALID_VALUE;
					}

					return value;
				}
			},

			placeholder: {},

			proxy: {}
		};

		A.extend(
			Sortable,
			A.Base,
			{
				initializer: function() {
					var instance = this;

					var nodes = instance.get('nodes');

					var constrain = instance.get('constrain');

					instance._useConstrain = !!constrain;

					if (Lang.isObject(constrain)) {
						instance._constrainConfig = constrain;
					}

					var proxy = instance.get('proxy');

					instance._useProxy = !!proxy;

					if (Lang.isObject(proxy)) {
						instance._proxyConfig = proxy;
					}

					var ddConfig = instance.get('dd');

					instance._ddConfig = ddConfig;

					instance._ddConfig = A.mix(
						instance._ddConfig,
						{
							bubbles: instance,
							groups: instance.get('groups'),
							placeholder: instance.get('placeholder'),
							constrain: instance.get('constrain'),
							proxy: instance.get('proxy')
						}
					);
					nodes.each(instance.add, instance);

					instance.after('drag:drag', instance._onDrag);
					instance.after('drag:end', instance._onDragEnd);
					instance.after('drag:over', instance._onDragOver);
					instance.after('drag:start', instance._onDragStart);
				},

				add: function(item) {
					var instance = this;

					if (item) {
						var ddConfig = instance._ddConfig;

						if ((item instanceof A.Node) || Lang.isString(item) || item.nodeName) {
							item = A.get(item);

							ddConfig.node = item;
						}
						else if (Lang.isObject(item)) {
							A.mix(item, ddConfig);

							ddConfig = item;
						}

						var sortableItem = instance.getSortableItem();

						var dd = new sortableItem(ddConfig);
					}
				},

				getSortableItem: function() {
					var instance = this;

					return SortableItem;
				},

				_onDrag: function(event) {
					var instance = this;

					var drag = event.target;

					var lastXY = drag.lastXY;
					var x = lastXY[0];
					var y = lastXY[1];

					var lastX = instance._lastX;
					var lastY = instance._lastY;

					var xToleranceMet = Math.abs(x - lastX);
					var yToleranceMet = Math.abs(y - lastY);

					instance._goingUp = ((x < lastX) && xToleranceMet) || ((y < lastY) && yToleranceMet);

					instance._lastX = x;
					instance._lastY = y;

					A.later(50, DDM, DDM.syncActiveShims);
				},

				_onDragEnd: function(event) {
					var instance = this;

					var drag = event.target;
					var node = drag.get('node');

					node.removeClass(CSS_DRAGGING);
				},

				_onDragOver: function(event) {
					var instance = this;

					var sortDirection = 0;
					var midpoint = 0;
					var lastX = instance._lastX;
					var lastY = instance._lastY;

					var DDM = A.DD.DDM;
					var drag = event.drag;
					var drop = event.drop;

					var dropNode = drop.get('node');

					var action = 'placeBefore';

					if (!instance._goingUp) {
						action = 'placeAfter';
					}

					dropNode[action](drag.get('placeholder'));

					drop.sizeShim();
				},

				_onDragStart: function(event) {
					var instance = this;

					var drag = event.target;

					var node = drag.get('node');

					if (instance._useProxy) {
						drag.get('dragNode').addClass(CSS_PROXY);
					}

					node.addClass(CSS_DRAGGING);
				},

				_lastX: 0,
				_lastY: 0
			}
		);

		var SortableItem = function(config) {
			SortableItem.superclass.constructor.call(this, config.dd || config);
		};

		SortableItem.NAME = 'sortableitem';

		SortableItem.ATTRS = {
			constrain: {
				value: null
			},

			placeholder: {
				getter: function() {
					var instance = this;

					return instance.get('node');
				}
			},

			proxy: {
				value: {
					borderStyle: 0,
					moveOnEnd: false
				}
			},

			target: {
				value: true
			},

			syncPlaceholderSize: {
				value: true
			}
		};

		A.extend(
			SortableItem,
			A.DD.Drag,
			{
				initializer: function() {
					var instance = this;

					var node = instance.get('node');

					node.dd = instance;

					node.addClass(CSS_ITEM);

					instance._initHandles();
					instance._initConstrain();
					instance._initProxy();
				},

				_initHandles: function() {
					var instance = this;

					var handles = instance.get('handles');
					var node = instance.get('node');

					if (handles) {
						for (var i = handles.length - 1; i >= 0; i--) {
							var handle = handles[i];

							node.queryAll(handle).addClass(CSS_HANDLE);
						}
					}
					else {
						node.addClass(CSS_NO_HANDLES);
					}

					instance.removeInvalid('a');
				},

				_initConstrain: function() {
					var instance = this;

					var constrain = instance.get('constrain');

					if (!!constrain) {
						if (!Lang.isObject(constrain)) {
							constrain = null;
						}

						instance.plug(A.Plugin.DDConstrained, constrain);
					}
				},

				_initProxy: function() {
					var instance = this;

					var proxy = instance.get('proxy');

					if (!!proxy) {
						if (!Lang.isObject(proxy)) {
							proxy = null;
						}

						instance.plug(A.Plugin.DDProxy, proxy);

						instance.get('dragNode').addClass(CSS_PROXY);
					}
				}
			}
		);

		A.Sortable = Sortable;
		A.SortableItem = SortableItem;
	},
	'@VERSION',
	{
		requires: ['base', 'dd'],
		use: []
	}
);<commit_msg>Bugfix for Sortable, allow to be initialized without nodes<commit_after>AUI().add(
	'sortable',
	function(A) {
		var Lang = A.Lang,

			getClassName = A.ClassNameManager.getClassName,

			NAME = 'sortable',

			DDM = A.DD.DDM,

			CSS_DRAGGING = getClassName(NAME, 'dragging'),
			CSS_HANDLE = getClassName(NAME, 'handle'),
			CSS_ITEM = getClassName(NAME, 'item'),
			CSS_NO_HANDLES = getClassName(NAME, 'no-handles'),
			CSS_PLACEHOLDER = getClassName(NAME, 'placeholder'),
			CSS_PROXY = getClassName(NAME, 'proxy'),
			CSS_SORTABLE = getClassName(NAME);

		var Sortable = function() {
			Sortable.superclass.constructor.apply(this, arguments);
		};

		Sortable.NAME = NAME;

		Sortable.ATTRS = {
			dd: {
				value: {}
			},

			constrain: {},

			container: {
				value: null
			},

			groups: {
				valueFn: function() {
					var instance = this;

					return [A.guid()];
				}
			},

			nodes: {
				value: null,
				setter: function(value) {
					var instance = this;

					var container = instance.get('container');

					if (!(value instanceof A.NodeList)) {
						if(Lang.isString(value)) {
							if (container) {
								value = container.queryAll(value);
							}
							else {
								value = A.all(value);
							}
						}
					}

					if (value instanceof A.NodeList && value.size()) {
						instance.set('container', value.item(0).get('parentNode'));
					}
					else {
						value = A.Attribute.INVALID_VALUE;
					}

					return value;
				}
			},

			placeholder: {},

			proxy: {}
		};

		A.extend(
			Sortable,
			A.Base,
			{
				initializer: function() {
					var instance = this;

					var nodes = instance.get('nodes');

					var constrain = instance.get('constrain');

					instance._useConstrain = !!constrain;

					if (Lang.isObject(constrain)) {
						instance._constrainConfig = constrain;
					}

					var proxy = instance.get('proxy');

					instance._useProxy = !!proxy;

					if (Lang.isObject(proxy)) {
						instance._proxyConfig = proxy;
					}

					var ddConfig = instance.get('dd');

					instance._ddConfig = ddConfig;

					instance._ddConfig = A.mix(
						instance._ddConfig,
						{
							bubbles: instance,
							groups: instance.get('groups'),
							placeholder: instance.get('placeholder'),
							constrain: instance.get('constrain'),
							proxy: instance.get('proxy')
						}
					);

					if (nodes) {
						nodes.each(instance.add, instance);
					}

					instance.after('drag:drag', instance._onDrag);
					instance.after('drag:end', instance._onDragEnd);
					instance.after('drag:over', instance._onDragOver);
					instance.after('drag:start', instance._onDragStart);
				},

				add: function(item) {
					var instance = this;

					if (item) {
						var ddConfig = instance._ddConfig;

						if ((item instanceof A.Node) || Lang.isString(item) || item.nodeName) {
							item = A.get(item);

							ddConfig.node = item;
						}
						else if (Lang.isObject(item)) {
							A.mix(item, ddConfig);

							ddConfig = item;
						}

						var sortableItem = instance.getSortableItem();

						var dd = new sortableItem(ddConfig);
					}
				},

				getSortableItem: function() {
					var instance = this;

					return SortableItem;
				},

				_onDrag: function(event) {
					var instance = this;

					var drag = event.target;

					var lastXY = drag.lastXY;
					var x = lastXY[0];
					var y = lastXY[1];

					var lastX = instance._lastX;
					var lastY = instance._lastY;

					var xToleranceMet = Math.abs(x - lastX);
					var yToleranceMet = Math.abs(y - lastY);

					instance._goingUp = ((x < lastX) && xToleranceMet) || ((y < lastY) && yToleranceMet);

					instance._lastX = x;
					instance._lastY = y;

					A.later(50, DDM, DDM.syncActiveShims);
				},

				_onDragEnd: function(event) {
					var instance = this;

					var drag = event.target;
					var node = drag.get('node');

					node.removeClass(CSS_DRAGGING);
				},

				_onDragOver: function(event) {
					var instance = this;

					var sortDirection = 0;
					var midpoint = 0;
					var lastX = instance._lastX;
					var lastY = instance._lastY;

					var DDM = A.DD.DDM;
					var drag = event.drag;
					var drop = event.drop;

					var dropNode = drop.get('node');

					var action = 'placeBefore';

					if (!instance._goingUp) {
						action = 'placeAfter';
					}

					dropNode[action](drag.get('placeholder'));

					drop.sizeShim();
				},

				_onDragStart: function(event) {
					var instance = this;

					var drag = event.target;

					var node = drag.get('node');

					if (instance._useProxy) {
						drag.get('dragNode').addClass(CSS_PROXY);
					}

					node.addClass(CSS_DRAGGING);
				},

				_lastX: 0,
				_lastY: 0
			}
		);

		var SortableItem = function(config) {
			SortableItem.superclass.constructor.call(this, config.dd || config);
		};

		SortableItem.NAME = 'sortableitem';

		SortableItem.ATTRS = {
			constrain: {
				value: null
			},

			placeholder: {
				getter: function() {
					var instance = this;

					return instance.get('node');
				}
			},

			proxy: {
				value: {
					borderStyle: 0,
					moveOnEnd: false
				}
			},

			target: {
				value: true
			},

			syncPlaceholderSize: {
				value: true
			}
		};

		A.extend(
			SortableItem,
			A.DD.Drag,
			{
				initializer: function() {
					var instance = this;

					var node = instance.get('node');

					node.dd = instance;

					node.addClass(CSS_ITEM);

					instance._initHandles();
					instance._initConstrain();
					instance._initProxy();
				},

				_initHandles: function() {
					var instance = this;

					var handles = instance.get('handles');
					var node = instance.get('node');

					if (handles) {
						for (var i = handles.length - 1; i >= 0; i--) {
							var handle = handles[i];

							node.queryAll(handle).addClass(CSS_HANDLE);
						}
					}
					else {
						node.addClass(CSS_NO_HANDLES);
					}

					instance.removeInvalid('a');
				},

				_initConstrain: function() {
					var instance = this;

					var constrain = instance.get('constrain');

					if (!!constrain) {
						if (!Lang.isObject(constrain)) {
							constrain = null;
						}

						instance.plug(A.Plugin.DDConstrained, constrain);
					}
				},

				_initProxy: function() {
					var instance = this;

					var proxy = instance.get('proxy');

					if (!!proxy) {
						if (!Lang.isObject(proxy)) {
							proxy = null;
						}

						instance.plug(A.Plugin.DDProxy, proxy);

						instance.get('dragNode').addClass(CSS_PROXY);
					}
				}
			}
		);

		A.Sortable = Sortable;
		A.SortableItem = SortableItem;
	},
	'@VERSION',
	{
		requires: ['base', 'dd'],
		use: []
	}
);<|endoftext|>


<commit_before>import React from 'react';
const uuidV4 = require('uuid/v4');

export default class Media extends React.Component {

    render() {
        const {mediaItem, count} = this.props;
        let classVal = "mediaItem col-sm-2 col-lg-2 col-md-2";
        if(count == 5) {
            classVal = "mediaItem col-xs-15";
        } else if(count == 4) {
            classVal = "mediaItem col-sm-3 col-lg-3 col-md-3";
        }
        return (

{mediaItem.processedFileName}

{mediaItem.imdbRating}

                     {/*
Button Button

                        */}

        );
    }
}<commit_msg>show rating only if present<commit_after>import React from 'react';
const uuidV4 = require('uuid/v4');

export default class Media extends React.Component {

    render() {
        const {mediaItem, count} = this.props;
        let classVal = "mediaItem col-sm-2 col-lg-2 col-md-2";
        if(count == 5) {
            classVal = "mediaItem col-xs-15";
        } else if(count == 4) {
            classVal = "mediaItem col-sm-3 col-lg-3 col-md-3";
        }
        let rating = '';
        if(mediaItem.imdbRating) {
            rating =
{mediaItem.imdbRating}

        }
        return (

                    {rating}

{mediaItem.processedFileName}

                     {/*
Button Button

                        */}

        );
    }
}<|endoftext|>


<commit_before>var CAST_APP_ID = "938337b2-f581-41c4-b2c4-73e9cbe9e7ea",
    FEDR_NAMESPACE = 'cast.fedr.co';

var receiver = new cast.receiver.Receiver(CAST_APP_ID, [cast.receiver.RemoteMedia.NAMESPACE, FEDR_NAMESPACE], "", 5);

var remoteMedia = new cast.receiver.RemoteMedia();
remoteMedia.addChannelFactory(receiver.createChannelFactory(cast.receiver.RemoteMedia.NAMESPACE));

var channelHandler = new cast.receiver.ChannelHandler(FEDR_NAMESPACE);
channelHandler.addChannelFactory(receiver.createChannelFactory(FEDR_NAMESPACE));

define(function() {
    return ['$scope', '$timeout', function ($scope, $timeout) {
        var $localVideo = $('#localVideo'),
            $third = $('#third'),
            $flash = $('#flash'),
            $logo = $('#logo'),
            logoTimeout,
            quitTimeout;

        startQuit();

        $scope.video = {
            name: 'The Video Name'
        };

        remoteMedia.setMediaElement($localVideo[0]);

        $localVideo.on("loadedmetadata", function() {
            $scope.$apply(function() {
                $scope.video.name = remoteMedia.getTitle();
                $third.addClass('show');
                setTimeout(function() {
                    $third.removeClass('show');
                }, 5000);
            });
        });

        $localVideo.on('play', function() {
            flash('play');
            cancelQuit();
            hideLogo();
        });

        $localVideo.on('pause', function() {
            flash('pause');
            startQuit();
            showLogo();
        });

        function flash(type) {
            $scope.$apply(function() {
                $scope.flash = type;
                $flash.addClass('show');
                setTimeout(function() {
                    $flash.removeClass('show');
                }, 1000);
            });
        }

        channelHandler.addEventListener(cast.receiver.Channel.EventType.MESSAGE, function(e) {
            console.log(e);
        });

        receiver.start();

        function startQuit() {
            quitTimeout = $timeout(function() {
                window.close();
            }, 5 * 60 * 1000);
        }

        function cancelQuit() {
            $timeout.cancel(quitTimeout);
        }

        function showLogo() {
            logoTimeout = $timeout(function() {
                $logo.addClass('show');
            }, 10 * 1000);
        }

        function hideLogo() {
            $timeout.cancel(logoTimeout);
            $logo.removeClass('show');
        }
    }];
});
<commit_msg>remove unused channel<commit_after>var CAST_APP_ID = "938337b2-f581-41c4-b2c4-73e9cbe9e7ea";

var receiver = new cast.receiver.Receiver(CAST_APP_ID, [cast.receiver.RemoteMedia.NAMESPACE], "", 5);

var remoteMedia = new cast.receiver.RemoteMedia();
remoteMedia.addChannelFactory(receiver.createChannelFactory(cast.receiver.RemoteMedia.NAMESPACE));

define(function() {
    return ['$scope', '$timeout', function ($scope, $timeout) {
        var $localVideo = $('#localVideo'),
            $third = $('#third'),
            $flash = $('#flash'),
            $logo = $('#logo'),
            logoTimeout,
            quitTimeout;

        startQuit();

        $scope.video = {
            name: 'The Video Name'
        };

        remoteMedia.setMediaElement($localVideo[0]);

        $localVideo.on("loadedmetadata", function() {
            $scope.$apply(function() {
                $scope.video.name = remoteMedia.getTitle();
                $third.addClass('show');
                setTimeout(function() {
                    $third.removeClass('show');
                }, 5000);
            });
        });

        $localVideo.on('play', function() {
            flash('play');
            cancelQuit();
            hideLogo();
        });

        $localVideo.on('pause', function() {
            flash('pause');
            startQuit();
            showLogo();
        });

        function flash(type) {
            $scope.$apply(function() {
                $scope.flash = type;
                $flash.addClass('show');
                setTimeout(function() {
                    $flash.removeClass('show');
                }, 1000);
            });
        }

        receiver.start();

        function startQuit() {
            quitTimeout = $timeout(function() {
                window.close();
            }, 5 * 60 * 1000);
        }

        function cancelQuit() {
            $timeout.cancel(quitTimeout);
        }

        function showLogo() {
            logoTimeout = $timeout(function() {
                $logo.addClass('show');
            }, 10 * 1000);
        }

        function hideLogo() {
            $timeout.cancel(logoTimeout);
            $logo.removeClass('show');
        }
    }];
});
<|endoftext|>