<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you 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.
*
* jQuery Simple Websocket
* https://github.com/jbloemendal/jquery-simple-websocket
*/

(function (factory) {
  if ('object' === typeof module && typeof 'object' === module.exports) {
      module.exports = factory(jQuery);
  } else {
      factory(jQuery);
  }
}(function($) {

    var SimpleWebSocket = function(opt) {
        if (this._isEmpty(opt, 'url')) {
            throw new Error('Missing argument, example usage: $.simpleWebSocket({ url: "ws://127.0.0.1:3000" }); ');
        }
        this._opt = opt;

        this._ws = null;
        this._reConnectTries = 60;
        this._reConnectDeferred = null;
        this._dataType = this._prop(this._opt, 'dataType', 'json');

        this._listeners = [];

        var self = this;
        this._api = (function() {
            return {
                connect: function() {
                    return $.extend(self._api, self._reConnect.apply(self, []));
                },

                isConnected: function(callback) {
                    if (callback) {
                        callback.apply(this, [self._isConnected.apply(self, [])]);
                        return self._api;
                    } else {
                        return self._isConnected.apply(self, []);
                    }
                },

                send: function(data) {
                    return $.extend(self._api, self._send.apply(self, [data]));
                },

                listen: function(listener) {
                    return $.extend(self._api, self._listenReconnect.apply(self, [listener]));
                },

                remove: function(listener) {
                    self._remove.apply(self, [listener]);
                    return self._api;
                },

                removeAll: function() {
                    self._removeAll.apply(self, []);
                    return self._api;
                },

                close: function() {
                    self._close.apply(self, []);
                    self._reset.apply(self, []);
                    return self._api;
                }
            };
        })();

        return this._api;
    };

    SimpleWebSocket.prototype = {

        _createWebSocket: function(opt) {
            var ws = null;
            if (opt.protocols) {
                if ('undefined' === typeof window.MozWebSocket) {
                    ws = (window.WebSocket ? new WebSocket(opt.url, opt.protocols) : null);
                } else {
                    ws = new MozWebSocket(opt.url, opt.protocols);
                }
            } else {
                if ('undefined' === typeof window.MozWebSocket) {
                    if (window.WebSocket) {
                        ws =  new WebSocket(opt.url);
                    } else {
                        throw new Error('Error, websocket could not be initialized.');
                    }
                } else {
                    ws = new MozWebSocket(opt.url);
                }
            }
            return ws;
        },

        _bindSocketEvents: function(ws, opt) {
            var self = this;
            $(ws).bind('open', opt.open)
            .bind('close', opt.close)
            .bind('message', function(event) {
                try {
                    if ('function' === typeof opt.message) {
                        if (self._dataType && 'json' === self._dataType.toLowerCase()) {
                            var json = JSON.parse(event.originalEvent.data);
                            opt.message.call(this, json);
                        } else if (self._dataType && 'xml' === self._dataType.toLowerCase()) {
                            var domParser = new DOMParser();
                            var dom = domParser.parseFromString(event.originalEvent.data, 'text/xml');
                            opt.message.call(this, dom);
                        } else {
                            opt.message.call(this, event.originalEvent.data);
                        }
                    }
                } catch (exception) {
                    if ('function' === typeof opt.error) {
                      opt.error.call(this, exception);
                    }
                }
            }).bind('error', function(exception) {
                if ('function' === typeof opt.error) {
                    opt.error.call(this, exception);
                }
            });
        },

        _webSocket: function(opt) {
           var ws = this._createWebSocket(opt);
           this._bindSocketEvents(ws, opt);

           return ws;
        },

        _getSocketEventHandler: function(attempt) {
            var self = this;
            return {
                open: function(e) {
                    var sock = this;
                    if (attempt) {
                        attempt.resolve(sock);
                    }
                },
                close: function(e) {
                    if (attempt) {
                        attempt.rejectWith(e);
                    }
                },
                message: function(message) {
                    for (var i=0, len=self._listeners.length; i<len; i++) {
                        try {
                            self._listeners[i].deferred.notify.apply(self, [message]);
                        } catch (error) {
                        }
                    }
                },
                error: function(e) {
                    self._ws = null;
                    for (var i=0, len=self._listeners.length; i<len; i++) {
                        self._listeners[i].deferred.reject.apply(self, [e]);
                    }
                    if (attempt) {
                        attempt.rejectWith.apply(self, [e]);
                    }
                }
            };
        },

        _connect: function() {
            var attempt = $.Deferred();

            if (this._ws) {
                if (2 === this._ws.readyState) {
                    // close previous socket
                    this._ws.close();
                } else if (3 === this._ws.readyState) {
                    // close previous socket
                    this._ws.close();
                } else if (0 === this._ws.readyState) {
                    return attempt.promise();
                } else if (1 === this._ws.readyState) {
                    attempt.resolve(this._ws);
                    return attempt.promise();
                }
            }

            this._ws = this._webSocket($.extend(this._opt, this._getSocketEventHandler(attempt)));

            return attempt.promise();
        },

        _reset: function() {
            this._reConnectTries = this._prop(this._opt, 'attempts', 60); // default 10min
            this._reConnectDeferred = $.Deferred();
        },

        _close: function() {
            if (this._ws) {
                this._ws.close();
                this._ws = null;
            }
        },

        _isConnected: function() {
            if (null === this._ws) {
                return false;
            } else if (1 === this._ws.readyState) {
                return true;
            }
            return false;
        },

        _reConnectTry: function() {
            var self = this;
            this._connect().done(function() {
                self._reConnectDeferred.resolve.apply(self, [self._ws]);
            }).fail(function(e) {
                self._reConnectTries--;
                if (self._reConnectTries > 0) {
                    window.setTimeout(function() {
                        self._reConnect.apply(self, []);
                    }, self._prop.apply(self, [self._opt, 'timeout', 10000]));
                } else {
                    self._reConnectDeferred.rejectWith.apply(self, [e]);
                }
            });
        },

        _reConnect: function() {
            var self = this;
            if (null === this._reConnectDeferred) {
                this._reset();
            } else if ('resolved' === this._reConnectDeferred.state()) {
                this._reset();
            } else if ('rejected' === this._reConnectDeferred.state()) {
                this._reset();
            }

            if (this._ws && this._ws.readyState === 1) {
                this._reConnectDeferred.resolve(this._ws);
            } else {
                this._reConnectTry();
            }

            return self._reConnectDeferred.promise.apply(self, []);
        },

        _preparePayload: function(data) {
            var payload;
            if (this._opt.dataType && 'text' === this._opt.dataType.toLowerCase()) {
                payload = data;
            } else if (this._opt.dataType && 'xml' === this._opt.dataType.toLowerCase()) {
                payload = data;
            } else if (this._opt.dataType && 'json' === this._opt.dataType.toLowerCase()) {
                payload = JSON.stringify(data);
            } else {
                payload = JSON.stringify(data); // default
            }
            return payload;
        },

        _send: function(data) {
            var self = this;
            var attempt = $.Deferred();

            (function(json) {
                self._reConnect.apply(self, []).done(function(ws) {
                    ws.send(json);
                    attempt.resolve.apply(self, [self._api]);
                }).fail(function(e) {
                    attempt.rejectWith.apply(self, [e]);
                });
            })(this._preparePayload(data));

            return attempt.promise();
        },

        _indexOfListener: function(listener) {
            for (var i=0, len=this._listeners.length; i<len; i++) {
                if (this._listeners[i].listener === listener) {
                    return i;
                }
            }
            return -1;
        },

         _isEmpty: function(obj, property) {
            if (typeof 'undefined' === obj) {
                return true;
            } else if (null === obj) {
                return true;
            } else if ('undefined' === typeof property) {
                return true;
            } else if (null === property) {
                return true;
            } else if ('' === property) {
                return true;
            } else if ('undefined' === typeof obj[property]) {
                return true;
            } else if (null === obj[property]) {
                return true;
            }
            return false;
         },

        _prop: function(obj, property, defaultValue) {
            if (this._isEmpty(obj, property)) {
                return defaultValue;
            }
            return obj[property];
        },

        _listen: function(listener) {
            var self = this;
            var dInternal = $.Deferred();
             self._reConnect.apply(self, []).done(function() {
                 dInternal.progress(function() {
                     listener.apply(this, arguments);
                 });
                 self._remove.apply(self, [listener]);
                 self._listeners.push({ 'deferred': dInternal, 'listener': listener });
             }).fail(function(e) {
                 dInternal.reject(e);
             });
             return dInternal.promise();
        },

        _listenReconnect: function(listener) {
            var dExternal = $.Deferred();

            var self = this;
            this._listen(listener)
            .fail(function() {
                dExternal.notify(arguments);
                self._listenReconnect.apply(self, [listener]);
            }).done(function() {
                dExternal.resolve();
            });

            return dExternal.promise();
        },

        _remove: function(listener) {
            var index = this._indexOfListener(listener);
            if (0 <= index) {
                this._listeners[index].deferred.resolve();
                this._listeners.splice(index, 1);
            }
        },

        _removeAll: function() {
           for (var i=0, len=this._listeners.length; i<len; i++) {
               this._listeners[i].deferred.resolve();
           }
           this._listeners = [];
        }
     };

    $.extend({
        simpleWebSocket: function(opt) {
            return new SimpleWebSocket(opt);
        }
    });

    return $.simpleWebSocket;
}));
<commit_msg>refactoring<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you 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.
*
* jQuery Simple Websocket
* https://github.com/jbloemendal/jquery-simple-websocket
*/

(function (factory) {
  if ('object' === typeof module && typeof 'object' === module.exports) {
      module.exports = factory(jQuery);
  } else {
      factory(jQuery);
  }
}(function($) {

    var SimpleWebSocket = function(opt) {
        if (this._isEmpty(opt, 'url')) {
            throw new Error('Missing argument, example usage: $.simpleWebSocket({ url: "ws://127.0.0.1:3000" }); ');
        }
        this._opt = opt;

        this._ws = null;
        this._reConnectTries = 60;
        this._reConnectDeferred = null;
        this._dataType = this._prop(this._opt, 'dataType', 'json');

        this._listeners = [];

        var self = this;
        this._api = (function() {
            return {
                connect: function() {
                    return $.extend(self._api, self._reConnect.apply(self, []));
                },

                isConnected: function(callback) {
                    if (callback) {
                        callback.apply(this, [self._isConnected.apply(self, [])]);
                        return self._api;
                    } else {
                        return self._isConnected.apply(self, []);
                    }
                },

                send: function(data) {
                    return $.extend(self._api, self._send.apply(self, [data]));
                },

                listen: function(listener) {
                    return $.extend(self._api, self._listenReconnect.apply(self, [listener]));
                },

                remove: function(listener) {
                    self._remove.apply(self, [listener]);
                    return self._api;
                },

                removeAll: function() {
                    self._removeAll.apply(self, []);
                    return self._api;
                },

                close: function() {
                    self._close.apply(self, []);
                    self._reset.apply(self, []);
                    return self._api;
                }
            };
        })();

        return this._api;
    };

    SimpleWebSocket.prototype = {

        _createWebSocket: function(opt) {
            var ws = null;
            if (opt.protocols) {
                if ('undefined' === typeof window.MozWebSocket) {
                    if (window.WebSocket) {
                        ws = new WebSocket(opt.url, opt.protocols);
                    } else {
                        throw new Error('Error, websocket could not be initialized.');
                    }
                } else {
                    ws = new MozWebSocket(opt.url, opt.protocols);
                }
            } else {
                if ('undefined' === typeof window.MozWebSocket) {
                    if (window.WebSocket) {
                        ws =  new WebSocket(opt.url);
                    } else {
                        throw new Error('Error, websocket could not be initialized.');
                    }
                } else {
                    ws = new MozWebSocket(opt.url);
                }
            }
            return ws;
        },

        _bindSocketEvents: function(ws, opt) {
            var self = this;
            $(ws).bind('open', opt.open)
            .bind('close', opt.close)
            .bind('message', function(event) {
                try {
                    if ('function' === typeof opt.message) {
                        if (self._dataType && 'json' === self._dataType.toLowerCase()) {
                            var json = JSON.parse(event.originalEvent.data);
                            opt.message.call(this, json);
                        } else if (self._dataType && 'xml' === self._dataType.toLowerCase()) {
                            var domParser = new DOMParser();
                            var dom = domParser.parseFromString(event.originalEvent.data, 'text/xml');
                            opt.message.call(this, dom);
                        } else {
                            opt.message.call(this, event.originalEvent.data);
                        }
                    }
                } catch (exception) {
                    if ('function' === typeof opt.error) {
                      opt.error.call(this, exception);
                    }
                }
            }).bind('error', function(exception) {
                if ('function' === typeof opt.error) {
                    opt.error.call(this, exception);
                }
            });
        },

        _webSocket: function(opt) {
           var ws = this._createWebSocket(opt);
           this._bindSocketEvents(ws, opt);

           return ws;
        },

        _getSocketEventHandler: function(attempt) {
            var self = this;
            return {
                open: function(e) {
                    var sock = this;
                    if (attempt) {
                        attempt.resolve(sock);
                    }
                },
                close: function(e) {
                    if (attempt) {
                        attempt.rejectWith(e);
                    }
                },
                message: function(message) {
                    for (var i=0, len=self._listeners.length; i<len; i++) {
                        try {
                            self._listeners[i].deferred.notify.apply(self, [message]);
                        } catch (error) {
                        }
                    }
                },
                error: function(e) {
                    self._ws = null;
                    for (var i=0, len=self._listeners.length; i<len; i++) {
                        self._listeners[i].deferred.reject.apply(self, [e]);
                    }
                    if (attempt) {
                        attempt.rejectWith.apply(self, [e]);
                    }
                }
            };
        },

        _connect: function() {
            var attempt = $.Deferred();

            if (this._ws) {
                if (2 === this._ws.readyState) {
                    // close previous socket
                    this._ws.close();
                } else if (3 === this._ws.readyState) {
                    // close previous socket
                    this._ws.close();
                } else if (0 === this._ws.readyState) {
                    return attempt.promise();
                } else if (1 === this._ws.readyState) {
                    attempt.resolve(this._ws);
                    return attempt.promise();
                }
            }

            this._ws = this._webSocket($.extend(this._opt, this._getSocketEventHandler(attempt)));

            return attempt.promise();
        },

        _reset: function() {
            this._reConnectTries = this._prop(this._opt, 'attempts', 60); // default 10min
            this._reConnectDeferred = $.Deferred();
        },

        _close: function() {
            if (this._ws) {
                this._ws.close();
                this._ws = null;
            }
        },

        _isConnected: function() {
            if (null === this._ws) {
                return false;
            } else if (1 === this._ws.readyState) {
                return true;
            }
            return false;
        },

        _reConnectTry: function() {
            var self = this;
            this._connect().done(function() {
                self._reConnectDeferred.resolve.apply(self, [self._ws]);
            }).fail(function(e) {
                self._reConnectTries--;
                if (self._reConnectTries > 0) {
                    window.setTimeout(function() {
                        self._reConnect.apply(self, []);
                    }, self._prop.apply(self, [self._opt, 'timeout', 10000]));
                } else {
                    self._reConnectDeferred.rejectWith.apply(self, [e]);
                }
            });
        },

        _reConnect: function() {
            var self = this;
            if (null === this._reConnectDeferred) {
                this._reset();
            } else if ('resolved' === this._reConnectDeferred.state()) {
                this._reset();
            } else if ('rejected' === this._reConnectDeferred.state()) {
                this._reset();
            }

            if (this._ws && this._ws.readyState === 1) {
                this._reConnectDeferred.resolve(this._ws);
            } else {
                this._reConnectTry();
            }

            return self._reConnectDeferred.promise.apply(self, []);
        },

        _preparePayload: function(data) {
            var payload;
            if (this._opt.dataType && 'text' === this._opt.dataType.toLowerCase()) {
                payload = data;
            } else if (this._opt.dataType && 'xml' === this._opt.dataType.toLowerCase()) {
                payload = data;
            } else if (this._opt.dataType && 'json' === this._opt.dataType.toLowerCase()) {
                payload = JSON.stringify(data);
            } else {
                payload = JSON.stringify(data); // default
            }
            return payload;
        },

        _send: function(data) {
            var self = this;
            var attempt = $.Deferred();

            (function(json) {
                self._reConnect.apply(self, []).done(function(ws) {
                    ws.send(json);
                    attempt.resolve.apply(self, [self._api]);
                }).fail(function(e) {
                    attempt.rejectWith.apply(self, [e]);
                });
            })(this._preparePayload(data));

            return attempt.promise();
        },

        _indexOfListener: function(listener) {
            for (var i=0, len=this._listeners.length; i<len; i++) {
                if (this._listeners[i].listener === listener) {
                    return i;
                }
            }
            return -1;
        },

         _isEmpty: function(obj, property) {
            if (typeof 'undefined' === obj) {
                return true;
            } else if (null === obj) {
                return true;
            } else if ('undefined' === typeof property) {
                return true;
            } else if (null === property) {
                return true;
            } else if ('' === property) {
                return true;
            } else if ('undefined' === typeof obj[property]) {
                return true;
            } else if (null === obj[property]) {
                return true;
            }
            return false;
         },

        _prop: function(obj, property, defaultValue) {
            if (this._isEmpty(obj, property)) {
                return defaultValue;
            }
            return obj[property];
        },

        _listen: function(listener) {
            var self = this;
            var dInternal = $.Deferred();
             self._reConnect.apply(self, []).done(function() {
                 dInternal.progress(function() {
                     listener.apply(this, arguments);
                 });
                 self._remove.apply(self, [listener]);
                 self._listeners.push({ 'deferred': dInternal, 'listener': listener });
             }).fail(function(e) {
                 dInternal.reject(e);
             });
             return dInternal.promise();
        },

        _listenReconnect: function(listener) {
            var dExternal = $.Deferred();

            var self = this;
            this._listen(listener)
            .fail(function() {
                dExternal.notify(arguments);
                self._listenReconnect.apply(self, [listener]);
            }).done(function() {
                dExternal.resolve();
            });

            return dExternal.promise();
        },

        _remove: function(listener) {
            var index = this._indexOfListener(listener);
            if (0 <= index) {
                this._listeners[index].deferred.resolve();
                this._listeners.splice(index, 1);
            }
        },

        _removeAll: function() {
           for (var i=0, len=this._listeners.length; i<len; i++) {
               this._listeners[i].deferred.resolve();
           }
           this._listeners = [];
        }
     };

    $.extend({
        simpleWebSocket: function(opt) {
            return new SimpleWebSocket(opt);
        }
    });

    return $.simpleWebSocket;
}));
<|endoftext|>


<commit_before>/*
---

name: ART

description: The heart of ART.

authors: [Valerio Proietti](http://mad4milk.net), [The MooTools development team](http://mootools.net/developers)

provides: [ART, ART.Element, ART.Container]

...
*/

/* # kappa */

Math.kappa = (4 * (Math.sqrt(2) - 1) / 3);

var ART = new Class;

ART.Element = new Class({

	/* dom */

	inject: function(element){
		if (element.toElement) element = element.toElement();
		element.appendChild(this.element);
		return this;
	},

	eject: function(){
		var parent = this.element.parentNode;
		if (parent) parent.removeChild(this.element);
		return this;
	},

	/* attributes */

	set: function(k, v){
		var element = this.toElement();
		if (typeof k != 'string') for (var p in k) this.set(p, k[p]);
		else element.setAttribute(k.hyphenate(), v);
		return this;
	},

	get: function(a){
		var element = this.toElement();
		if (arguments.length > 1){
			var res = {};
			for (var i = 0; i < arguments.length; i++){
				var argCC = arguments[i].camelCase();
				res[argCC] = element.getAttribute(arg.hyphenate());
			}
			return res;
		} else {
			return this.element.getAttribute(a.hyphenate());
		}
	},

	/* $ */

	toElement: function(){
		return this.element;
	}

});

ART.Container = new Class({

	push: function(){
		for (var i = 0; i < arguments.length; i++) arguments[i].inject(this);
		return this;
	},

	pull: function(){
		var element = (this.toElement) ? this.toElement() : null;
		for (var i = 0; i < arguments.length; i++){
			var child = arguments[i], parent = child.parentNode;
			if (child.parentNode && child.parentNode === element) child.eject();
		}
		return this;
	}

});

Color.detach = function(color){
	color = new Color(color); var alpha = color.get('alpha');
	return [color.set('alpha', 1).toString(), alpha];
};
<commit_msg> - added a basic event manager in ART.Element. Since the real HTML element is not supposed to be accessed publicly, removed the toElement method and the events are now simply bound to the current art instance.  - got rid of set / get (not used anymore).<commit_after>/*
---

name: ART

description: The heart of ART.

authors: [Valerio Proietti](http://mad4milk.net), [The MooTools development team](http://mootools.net/developers)

provides: [ART, ART.Element, ART.Container]

...
*/

/* # kappa */

Math.kappa = (4 * (Math.sqrt(2) - 1) / 3);

var ART = new Class;

ART.Element = new Class({

	/* dom */

	inject: function(element){
		if (element.element) element = element.element;
		element.appendChild(this.element);
		return this;
	},

	eject: function(){
		var element = this.element, parent = element.parentNode;
		if (parent) parent.removeChild(element);
		return this;
	},

	/* events */

	listen: function(type, fn){
		if (!this._events) this._events = {};

		if (typeof type != 'string'){ // listen type / fn with object
			for (var t in type) this.listen(t, type[t]);
		} else { // listen to one
			if (!this._events[type]) this._events[type] = new Table;
			var events = this._events[type];
			if (events.get(fn)) return this;
			var bound = fn.bind(this);
			events.set(fn, bound);
			var element = this.element;
			if (element.addEventListener) element.addEventListener(type, bound, false);
			else element.attachEvent('on' + type, bound);
		}

		return this;
	},

	ignore: function(type, fn){
		if (!this._events) return this;

		if (typeof type != 'string'){ // ignore type / fn with object
			for (var t in type) this.ignore(t, type[t]);
			return this;
		}

		var events = this._events[type];
		if (!events) return this;

		if (fn == null){ // ignore every of type
			events.each(function(fn, bound){
				this.ignore(type, fn);
			}, this);
		} else { // ignore one
			var bound = events.get(fn);
			if (!bound) return this;
			var element = this.element;
			if (element.removeEventListener) element.removeEventListener(type, bound, false);
			else element.detachEvent('on' + type, bound);
		}

		return this;
	}

});

ART.Container = new Class({

	push: function(){
		for (var i = 0; i < arguments.length; i++) arguments[i].inject(this);
		return this;
	},

	pull: function(){
		var element = this.element;
		for (var i = 0; i < arguments.length; i++){
			var child = arguments[i], parent = child.parentNode;
			if (child.parentNode && child.parentNode === element) child.eject();
		}
		return this;
	}

});

Color.detach = function(color){
	color = new Color(color);
	return [Color.rgb(color.red, color.green, color.blue).toString(), color.alpha];
};
<|endoftext|>


<commit_before>L.LevelButtons = L.Control.extend({
	'options': {
		'position': 'topleft',
		'autoZIndex': true
	},
	onAdd: function(map) {
		this._map = map;
		var plugin_container = L.DomUtil.create('div', 'leaflet-control-level-buttons-panel leaflet-bar');

		var up_button = L.DomUtil.create('a', 'leaflet-control-level-buttons-a', plugin_container);
		up_button.textContent = '\u25B2';
		up_button.href = '#';
		L.DomEvent.addListener(up_button, 'click', this._onUpButton, this);
		L.DomEvent.disableClickPropagation(up_button);
		plugin_container.appendChild(up_button);

		var floor_button = L.DomUtil.create('span', 'leaflet-control-level-buttons-span', plugin_container);
		floor_button.id = 'floor_button';

		plugin_container.appendChild(floor_button);

		var down_button = L.DomUtil.create('a', 'leaflet-control-level-buttons-a', plugin_container);
		down_button.textContent = '\u25BC';
		down_button.href = '#';
		L.DomEvent.addListener(down_button, 'click', this._onDownButton, this);
		L.DomEvent.disableClickPropagation(down_button);
		plugin_container.appendChild(down_button);

		return plugin_container;
	},
	onRemove: function() {},
	_onUpButton: function(event) {
		var upper_floor_index = this._tibia_map_obj.floor - 1;

		if (upper_floor_index >= 0) {
			this._bringToFront(upper_floor_index);
			this._setFloor(upper_floor_index);
			this._updateUrl(upper_floor_index);
		}
		event.preventDefault();
	},
	_onDownButton: function(event) {
		var lower_floor_index = this._tibia_map_obj.floor + 1;
		if (lower_floor_index <= 15) {
			this._bringToFront(lower_floor_index);
			this._setFloor(lower_floor_index);
			this._updateUrl(lower_floor_index);
		}

		event.preventDefault();
	},
	setTibiaMap: function(tibia_map_obj) {
		this._tibia_map_obj = tibia_map_obj;
		var floor_button = L.DomUtil.get('floor_button');
		this._setFloor(this._tibia_map_obj.floor);
	},
	_bringToFront: function(layer_index) {
		// Simulate a click on the chosen option.
		this.options.layers_widget._form[layer_index].click();
	},
	_setFloor: function(floor) {
		var floor_button = L.DomUtil.get('floor_button');
		floor_button.textContent = String(floor).padStart(2, '0');
	},
	_updateUrl: function(floor) {
		var coordinates = this._tibia_map_obj.getUrlPosition();
		coordinates.floor = floor;
		this._tibia_map_obj.setUrlPosition(coordinates, true);
	}
});

L.levelButtons = function(options) {
	return new L.LevelButtons(options);
};
<commit_msg>Use floor labels -8 to +7 instead of 0 to 15<commit_after>L.LevelButtons = L.Control.extend({
	'options': {
		'position': 'topleft',
		'autoZIndex': true
	},
	onAdd: function(map) {
		this._map = map;
		var plugin_container = L.DomUtil.create('div', 'leaflet-control-level-buttons-panel leaflet-bar');

		var up_button = L.DomUtil.create('a', 'leaflet-control-level-buttons-a', plugin_container);
		up_button.textContent = '\u25B2';
		up_button.href = '#';
		L.DomEvent.addListener(up_button, 'click', this._onUpButton, this);
		L.DomEvent.disableClickPropagation(up_button);
		plugin_container.appendChild(up_button);

		var floor_button = L.DomUtil.create('span', 'leaflet-control-level-buttons-span', plugin_container);
		floor_button.id = 'floor_button';

		plugin_container.appendChild(floor_button);

		var down_button = L.DomUtil.create('a', 'leaflet-control-level-buttons-a', plugin_container);
		down_button.textContent = '\u25BC';
		down_button.href = '#';
		L.DomEvent.addListener(down_button, 'click', this._onDownButton, this);
		L.DomEvent.disableClickPropagation(down_button);
		plugin_container.appendChild(down_button);

		return plugin_container;
	},
	onRemove: function() {},
	_onUpButton: function(event) {
		var upper_floor_index = this._tibia_map_obj.floor - 1;

		if (upper_floor_index >= 0) {
			this._bringToFront(upper_floor_index);
			this._setFloor(upper_floor_index);
			this._updateUrl(upper_floor_index);
		}
		event.preventDefault();
	},
	_onDownButton: function(event) {
		var lower_floor_index = this._tibia_map_obj.floor + 1;
		if (lower_floor_index <= 15) {
			this._bringToFront(lower_floor_index);
			this._setFloor(lower_floor_index);
			this._updateUrl(lower_floor_index);
		}

		event.preventDefault();
	},
	setTibiaMap: function(tibia_map_obj) {
		this._tibia_map_obj = tibia_map_obj;
		var floor_button = L.DomUtil.get('floor_button');
		this._setFloor(this._tibia_map_obj.floor);
	},
	_bringToFront: function(layer_index) {
		// Simulate a click on the chosen option.
		this.options.layers_widget._form[layer_index].click();
	},
	_setFloor: function(floor) {
		var floor_button = L.DomUtil.get('floor_button');
		var ground_floor = 7; // 0: high above ground; 15: deep underground
		var text = '';
		if (floor == ground_floor) {
			text = '0';
		} else if (floor < ground_floor){
			text = '+' + String(ground_floor - floor);
		} else {
			text = '-' + String(floor - ground_floor);
		}
		floor_button.textContent = text;
	},
	_updateUrl: function(floor) {
		var coordinates = this._tibia_map_obj.getUrlPosition();
		coordinates.floor = floor;
		this._tibia_map_obj.setUrlPosition(coordinates, true);
	}
});

L.levelButtons = function(options) {
	return new L.LevelButtons(options);
};
<|endoftext|>


<commit_before>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * Future.js                                              *
 *                                                        *
 * hprose Future for HTML5.                               *
 *                                                        *
 * LastModified: Jun 25, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

(function (global) {
    'use strict';

    var PENDING = 0;
    var FULFILLED = 1;
    var REJECTED = 2;

    var setImmediate = global.setImmediate || function(f) { setTimeout(f, 0); };

    function Future(computation) {
        if (typeof computation === "function") {
            var completer = new Completer();
            setImmediate(function() {
                try {
                    completer.complete(computation());
                }
                catch(e) {
                    completer.completeError(e);
                }
            });
            return completer.future;
        }
    }

    function delayed(duration, computation) {
        if (computation === undefined) {
            computation = function() { return null; };
        }
        var completer = new Completer();
        global.setTimeout(function() {
            try {
                completer.complete(computation());
            }
            catch(e) {
                completer.completeError(e);
            }
        }, duration);
        return completer.future;
    }

    function error(e) {
        var completer = new Completer();
        completer.completeError(e);
        return completer.future;
    }

    function sync(computation) {
        var completer = new Completer(true);
        try {
            completer.complete(computation());
        }
        catch(e) {
            completer.completeError(e);
        }
        return completer.future;
    }

    function value(v) {
        return sync(function() { return v; });
    }

    Object.defineProperties(Future, {
        delayed: { value: delayed },
        error: { value: error },
        sync: { value : sync },
        value: { value : value }
    });

    global.hprose.Future = Future;

    function isFuture(obj) {
        return (obj instanceof Future) && (typeof (obj.then === "function"));
    }

    function Completer(sync) {
        var _status = PENDING;
        var _result;
        var _error;
        var _callbacks = [];
        var _future = new Future();
        var run = sync ?
            function(callback, x) {
                return Future.sync(function() { return callback(x); });
            } :
            function(callback, x) {
                return new Future(function() { return callback(x); });
            };

        function resolve(onComplete, onError, x) {
            if (isFuture(x)) {
                if (x === _future) {
                    throw new TypeError('Self resolution');
                }
                return x.then(onComplete, onError);
            }
            if ((typeof x === "object") || (typeof x === "function")) {
                var completer = new Completer();
                var then;
                try {
                    then = x.then;
                }
                catch (e) {
                    completer.completeError(e);
                    return completer.future;
                }
                if (typeof then === "function") {
                    try {
                        then.call(x, completer.complete, completer.completeError);
                    }
                    catch (e) {
                        completer.completeError(e);
                    }
                    return completer.future;
                }
            }
            if (onComplete) {
                return run(onComplete, x);
            }
            return x;
        }

        // Calling complete must not be done more than once.
        function complete(result) {
            if (_status === PENDING) {
                _status = FULFILLED;
                _result = result;
                while (_callbacks.length > 0) {
                    var callback = _callbacks.shift();
                    result = resolve(callback[0], callback[1], result);
                }
            }
        }

        // Calling complete must not be done more than once.
        function completeError(error) {
            if (_status === PENDING) {
                _status = REJECTED;
                _error = error;
                var callback;
                var result;
                while (_callbacks.length > 0) {
                    callback = _callbacks.shift();
                    if (callback[1]) {
                        result = run(callback[1], error);
                        break;
                    }
                }
                if (_callbacks.length > 0) {
                    while (_callbacks.length > 0) {
                        callback = _callbacks.shift();
                        result = resolve(callback[0], callback[1], result);
                    }
                }
            }
        }

        function then(onComplete, onError) {
            if (typeof onComplete !== "function") onComplete = null;
            if (typeof onError !== "function") onError = null;
            if (onComplete || onError) {
                if (onComplete && (_status === FULFILLED)) {
                     return resolve(onComplete, onError, _result);
                }
                if (onError && (_status === REJECTED)) {
                    return run(onError, _error);
                }
                _callbacks.push([onComplete, onError]);
            }
            return _future;
        }

        function catchError(onError) {
            return then(null, onError);
        }

        function whenComplete(action) {
            return then(
                function(v) {
                    var f = action();
                    if (isFuture(f)) return f.then(function() { return v; });
                    return v;
                },
                function(e) {
                    var f = action();
                    if (isFuture(f)) return f.then(function() { throw e; });
                    throw e;
                }
            );
        }

        Object.defineProperties(_future, {
            then: { value: then },
            catchError: { value: catchError },
            whenComplete: { value: whenComplete }
        });

        Object.defineProperties(this, {
            future: { get: function() { return _future; } },
            isCompleted: { get: function() { return (_status !== PENDING); } },
            complete: { value : complete },
            completeError: { value : completeError }
        });
    }

    Object.defineProperty(Completer, 'isFuture', { value: isFuture });
    Object.defineProperty(Completer, 'sync', { value: function() { return new Completer(true); } });

    global.hprose.Completer = Completer;
})(this);
<commit_msg>while changed to do ... while.<commit_after>/**********************************************************\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: http://www.hprose.com/                 |
|                   http://www.hprose.org/                 |
|                                                          |
\**********************************************************/

/**********************************************************\
 *                                                        *
 * Future.js                                              *
 *                                                        *
 * hprose Future for HTML5.                               *
 *                                                        *
 * LastModified: Jun 25, 2015                             *
 * Author: Ma Bingyao <andot@hprose.com>                  *
 *                                                        *
\**********************************************************/

(function (global) {
    'use strict';

    var PENDING = 0;
    var FULFILLED = 1;
    var REJECTED = 2;

    var setImmediate = global.setImmediate || function(f) { setTimeout(f, 0); };

    function Future(computation) {
        if (typeof computation === "function") {
            var completer = new Completer();
            setImmediate(function() {
                try {
                    completer.complete(computation());
                }
                catch(e) {
                    completer.completeError(e);
                }
            });
            return completer.future;
        }
    }

    function delayed(duration, computation) {
        if (computation === undefined) {
            computation = function() { return null; };
        }
        var completer = new Completer();
        global.setTimeout(function() {
            try {
                completer.complete(computation());
            }
            catch(e) {
                completer.completeError(e);
            }
        }, duration);
        return completer.future;
    }

    function error(e) {
        var completer = new Completer();
        completer.completeError(e);
        return completer.future;
    }

    function sync(computation) {
        var completer = new Completer(true);
        try {
            completer.complete(computation());
        }
        catch(e) {
            completer.completeError(e);
        }
        return completer.future;
    }

    function value(v) {
        return sync(function() { return v; });
    }

    Object.defineProperties(Future, {
        delayed: { value: delayed },
        error: { value: error },
        sync: { value : sync },
        value: { value : value }
    });

    global.hprose.Future = Future;

    function isFuture(obj) {
        return (obj instanceof Future) && (typeof (obj.then === "function"));
    }

    function Completer(sync) {
        var _status = PENDING;
        var _result;
        var _error;
        var _callbacks = [];
        var _future = new Future();
        var run = sync ?
            function(callback, x) {
                return Future.sync(function() { return callback(x); });
            } :
            function(callback, x) {
                return new Future(function() { return callback(x); });
            };

        function resolve(onComplete, onError, x) {
            if (isFuture(x)) {
                if (x === _future) {
                    throw new TypeError('Self resolution');
                }
                return x.then(onComplete, onError);
            }
            if ((typeof x === "object") || (typeof x === "function")) {
                var completer = new Completer();
                var then;
                try {
                    then = x.then;
                }
                catch (e) {
                    completer.completeError(e);
                    return completer.future;
                }
                if (typeof then === "function") {
                    try {
                        then.call(x, completer.complete, completer.completeError);
                    }
                    catch (e) {
                        completer.completeError(e);
                    }
                    return completer.future;
                }
            }
            if (onComplete) {
                return run(onComplete, x);
            }
            return x;
        }

        // Calling complete must not be done more than once.
        function complete(result) {
            if (_status === PENDING) {
                _status = FULFILLED;
                _result = result;
                while (_callbacks.length > 0) {
                    var callback = _callbacks.shift();
                    result = resolve(callback[0], callback[1], result);
                }
            }
        }

        // Calling complete must not be done more than once.
        function completeError(error) {
            if (_status === PENDING) {
                _status = REJECTED;
                _error = error;
                var callback;
                var result;
                while (_callbacks.length > 0) {
                    callback = _callbacks.shift();
                    if (callback[1]) {
                        result = run(callback[1], error);
                        break;
                    }
                }
                if (_callbacks.length > 0) {
                    do {
                        callback = _callbacks.shift();
                        result = resolve(callback[0], callback[1], result);
                    } while (_callbacks.length > 0);
                }
            }
        }

        function then(onComplete, onError) {
            if (typeof onComplete !== "function") onComplete = null;
            if (typeof onError !== "function") onError = null;
            if (onComplete || onError) {
                if (onComplete && (_status === FULFILLED)) {
                     return resolve(onComplete, onError, _result);
                }
                if (onError && (_status === REJECTED)) {
                    return run(onError, _error);
                }
                _callbacks.push([onComplete, onError]);
            }
            return _future;
        }

        function catchError(onError) {
            return then(null, onError);
        }

        function whenComplete(action) {
            return then(
                function(v) {
                    var f = action();
                    if (isFuture(f)) return f.then(function() { return v; });
                    return v;
                },
                function(e) {
                    var f = action();
                    if (isFuture(f)) return f.then(function() { throw e; });
                    throw e;
                }
            );
        }

        Object.defineProperties(_future, {
            then: { value: then },
            catchError: { value: catchError },
            whenComplete: { value: whenComplete }
        });

        Object.defineProperties(this, {
            future: { get: function() { return _future; } },
            isCompleted: { get: function() { return (_status !== PENDING); } },
            complete: { value : complete },
            completeError: { value : completeError }
        });
    }

    Object.defineProperty(Completer, 'isFuture', { value: isFuture });
    Object.defineProperty(Completer, 'sync', { value: function() { return new Completer(true); } });

    global.hprose.Completer = Completer;
})(this);
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Splunk, 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.
 */

/**
 * This example shows how to use a custom event format for SplunkLogger.
 */

// Change to require("splunk-logging").Logger;
var SplunkLogger = require("../index").Logger;

/**
 * Only the token property is required.
 */
var config = {
    token: "your-token-here",
    url: "https://localhost:8088"
};

// Create a new logger
var Logger = new SplunkLogger(config);

Logger.error = function(err, context) {
    // Handle errors here
    console.log("error", err, "context", context);
};

/**
 * Override the default eventFormatter() function,
 * which takes a message and severity, returning
 * any type - string or object are recommended.
 *
 * The message parameter can be any type. It will
 * be whatever was passed to Logger.send().
 * Severity will always be a string.
 *
 * In this example, we're building up a string
 * of key=value pairs if message is an object,
 * otherwise the message value is as value for
 * the message key.
 * This string is prefixed with the event
 * severity in square brackets.
 */
Logger.eventFormatter = function(message, severity) {
    var event = "[" + severity + "]";

    if (typeof message === "object") {
        for (var key in message) {
            event += key + "=" + message[key] + " ";
        }
    }
    else {
        event += "message=" + message;
    }

    return event;
};

// Define the payload to send to Splunk's Event Collector
var payload = {
    // Message can be anything, it doesn't have to be an object
    message: {
        temperature: "70F",
        chickenCount: 500
    },
    // Metadata is optional
    metadata: {
        source: "chicken coop",
        sourcetype: "httpevent",
        index: "main",
        host: "farm.local"
    },
    // Severity is also optional
    severity: "info"
};

console.log("Sending payload", payload);

/**
 * Since maxBatchCount is set to 1 by default,
 * calling send will immediately send the payload.
 *
 * The underlying HTTP POST request is made to
 *
 *     https://localhost:8088/services/collector/event/1.0
 *
 * with the following body
 *
 *     {
 *         "source": "chicken coop",
 *         "sourcetype": "httpevent",
 *         "index": "main",
 *         "host": "farm.local",
 *         "event": "[info]temperature=70F chickenCount=500 "
 *     }
 *
 */
Logger.send(payload, function(err, resp, body) {
    // If successful, body will be { text: 'Success', code: 0 }
    console.log("Response from Splunk", body);
});<commit_msg>Editorial updates.<commit_after>/*
 * Copyright 2015 Splunk, 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.
 */

/**
 * This example shows how to use a custom event format for SplunkLogger.
 */

// Change to require("splunk-logging").Logger;
var SplunkLogger = require("../index").Logger;

/**
 * Only the token property is required.
 */
var config = {
    token: "your-token-here",
    url: "https://localhost:8088"
};

// Create a new logger
var Logger = new SplunkLogger(config);

Logger.error = function(err, context) {
    // Handle errors here
    console.log("error", err, "context", context);
};

/**
 * Override the default eventFormatter() function,
 * which takes a message and severity, returning
 * any type; string or object are recommended.
 *
 * The message parameter can be any type. It will
 * be whatever was passed to Logger.send().
 * Severity will always be a string.
 *
 * In this example, we're building up a string
 * of key=value pairs if message is an object,
 * otherwise the message value is as value for
 * the message key.
 *
 * This string is prefixed with the event
 * severity in square brackets.
 */
Logger.eventFormatter = function(message, severity) {
    var event = "[" + severity + "]";

    if (typeof message === "object") {
        for (var key in message) {
            event += key + "=" + message[key] + " ";
        }
    }
    else {
        event += "message=" + message;
    }

    return event;
};

// Define the payload to send to HTTP Event Collector
var payload = {
    // Message can be anything, it doesn't have to be an object
    message: {
        temperature: "70F",
        chickenCount: 500
    },
    // Metadata is optional
    metadata: {
        source: "chicken coop",
        sourcetype: "httpevent",
        index: "main",
        host: "farm.local"
    },
    // Severity is also optional
    severity: "info"
};

console.log("Sending payload", payload);

/**
 * Since maxBatchCount is set to 1 by default,
 * calling send will immediately send the payload.
 *
 * The underlying HTTP POST request is made to
 *
 *     https://localhost:8088/services/collector/event/1.0
 *
 * with the following body
 *
 *     {
 *         "source": "chicken coop",
 *         "sourcetype": "httpevent",
 *         "index": "main",
 *         "host": "farm.local",
 *         "event": "[info]temperature=70F chickenCount=500 "
 *     }
 *
 */
Logger.send(payload, function(err, resp, body) {
    // If successful, body will be { text: 'Success', code: 0 }
    console.log("Response from Splunk", body);
});
<|endoftext|>


<commit_before><commit_msg>Don't overwrite propertiess<commit_after><|endoftext|>


<commit_before>Meteor.startup(function () {
  Session.set("emailNotSaved",false);
});

Meteor.subscribe('files');

Handlebars.registerHelper("wrapperStyle", function(str) {
  return Session.equals('templateChooser', str) ? "true" : "";
});

Handlebars.registerHelper("display_setting", function(selection) {
  return Session.equals("display",selection);
});

Handlebars.registerHelper("getValue", function(value) {
  return Session.get(value);
});

Handlebars.registerHelper("highlight", function(value) {
  return Session.get(value) ? null : 'unchanged';
});

Handlebars.registerHelper("sigFirstName", function() {
  return Session.get("signature").split(' ')[0];
});

Handlebars.registerHelper("unformattedHtml", function(wrapper) {
  // return the HTML code of the template being referenced
  var div = document.createElement('div');
  switch (wrapper) {
    case "blank": UI.insert(UI.render(Template.blankEmailWrapperBody), div); break;
    case "call": UI.insert(UI.render(Template.callEmailWrapperBody), div); break;
    case "event": UI.insert(UI.render(Template.eventEmailWrapperBody), div); break;
    case "mobilize": UI.insert(UI.render(Template.mobilizeEmailWrapperBody), div); break;
    case "petition": UI.insert(UI.render(Template.petitionEmailWrapperBody), div); break;
    case "publicComment": UI.insert(UI.render(Template.publicCommentEmailWrapperBody), div); break;
    case "takeAction": UI.insert(UI.render(Template.takeActionEmailWrapperBody), div); break;
    case "superpacFundraiser": UI.insert(UI.render(Template.superpacFundraiserEmailWrapperBody), div); break;
    default: return "unformatted html not yet set";
  }
  return div.innerHTML;
});

Handlebars.registerHelper("htmlFromMarkdown", function(field) {
  var converter = new Showdown.converter();
  return converter.makeHtml(Session.get(field));
});

Handlebars.registerHelper("removeBackslash", function(field) {
  var str = Session.get(field);
  return str.replace(/\\/g,'');
});

Handlebars.registerHelper("prettifyDate", function(d) {
  if (d) {
    var a_p = "";
    var curr_hour = d.getHours();
    var curr_min = d.getMinutes();
    var pad = function (x) {
      return (x < 10 ? '0' : '') + x;
    };

    if (curr_hour < 12) { a_p = "AM";}
      else { a_p = "PM"; }
    if (curr_hour == 0) { curr_hour = 12; }
    if (curr_hour > 12) { curr_hour = curr_hour - 12; }

    var str = [d.getMonth()+1,d.getDate(),d.getFullYear()-2000].join('/') +
      " " + curr_hour + ":" + pad(curr_min) + " " + a_p;
    return str;
  } else { return ''; }
});

// email functions
setSessionVarsForEmail = function (obj) {
  Session.set("id", obj._id);
  console.log("in setSessionVarsForEmail" + obj._id);
  Session.set("markdown_data", obj.markdown_data);
  Session.set("templateChooser", obj.type);
  Session.set("topper", obj.topper);
  Session.set("notes", obj.notes);
  Session.set("headline", obj.headline);
  Session.set("statement_leadin", obj.statement_leadin);
  Session.set("petition", obj.petition);
  Session.set("link", obj.link);
  Session.set("graphic", obj.graphic);
  Session.set("graphic_alt_text", obj.graphic_alt_text);
  Session.set("signature", obj.signature);
  Session.set("footnotes", obj.footnotes);
  Session.set("facebook", obj.facebook);
  Session.set("twitter", obj.twitter);
  Session.set("refcode", obj.refcode);
  Session.set("creator", obj.creator);
  Session.set("when", obj.when);
};

setSessionVarsForNewEmail = function () {
  // template type is set in the link event handler so not necessary here
  // clear the other email session data
  Session.set("markdown_data", "");
  Session.set("topper", "");
  Session.set("notes", "");
  Session.set("headline", "");
  Session.set("statement_leadin", "");
  Session.set("petition", "");
  if (Session.equals("templateChooser", "superpacFundraiser"))
    Session.set("link","https://secure.actblue.com/contribute/page/savethesenate");
  else Session.set("link", "");
  Session.set("graphic", "");
  Session.set("graphic_alt_text", "");
  if (Session.equals("templateChooser","mobilize"))
    Session.set("signature", "");
  else if (Session.equals("templateChooser","superpacFundraiser"))
    Session.set("signature", "Becky Bond, President");
  else Session.set('signature', Meteor.user().profile.name + ', Campaign Manager');
  Session.set("footnotes", "");
  Session.set("facebook", "");
  Session.set("twitter", "");
  Session.set("refcode", "");
  Session.set("creator", "");
};

setSessionVarsForEmailFromPage = function (obj) {
  Session.set("markdown_data", obj.pageAboutText);
  if (obj.pageType === 'letter')
    Session.set('templateChooser', 'takeaction')
  else Session.set("templateChooser", obj.pageType);
  Session.set("notes", obj.notes);
  Session.set("headline", obj.pageTitle);
  Session.set("statement_leadin", obj.pageStatementLeadIn);
  Session.set("petition", obj.pageStatementText);
  Session.set("link", obj.AKpageURL);
  Session.set("graphic", obj.pageGraphicEmail);
  Session.set("graphic_alt_text", "");
  Session.set("footnotes", "");
  Session.set('signature', Meteor.user().profile.name + ', Campaign Manager');
  Session.set("facebook", "");
  var twitter = obj.pageTwitterCopy.replace(/{ *LINK *}/i, obj.AKpageBitly);
  Session.set("twitter", 'https://twitter.com/intent/tweet?&text='+urlEncodeQuotes(encodeURIComponent(removeCurlyQuotes(twitter))));
  Session.set("creator", Meteor.user().profile.name);
};

initSessionVarsForEmailCompose = function () {
  Session.set("display", "visual");
  Session.set("showNavBar",false);
  Session.set("snippets",false);
  Session.set("toolTips",false);
  Session.set("emailNotSaved",false);
  Session.set("saveDialog",false);
};

removeCurlyQuotes = function (str) {
  var goodQuotes = str
  .replace(/[\u2018\u2019]/g, "'")
  .replace(/[\u201C\u201D]/g, '"');
  return goodQuotes;
};

urlEncodeQuotes = function (str) {
  return str.replace(/['""]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
};

// page functions
setSessionVarsForPage = function (obj) {
  Session.set("id", obj._id);
  Session.set("type", obj.type);
  Session.set("pageType", obj.pageType);
  Session.set('templateChooser', obj.pageType);
  Session.set("notes", obj.notes);
  Session.set("pageTitle", obj.pageTitle);
  Session.set("pageName", obj.pageName);
  Session.set("pageStatementLeadIn", obj.pageStatementLeadIn);
  Session.set("pageStatementText", obj.pageStatementText);
  Session.set("pageAboutText", obj.pageAboutText);
  Session.set("pageGraphicEmail", obj.pageGraphicEmail);
  Session.set("pageGraphicFacebook", obj.pageGraphicFacebook);
  Session.set("pageGraphicHomePage", obj.pageGraphicHomePage);
  Session.set("pageTAFSL", obj.pageTAFSL);
  Session.set("pageTAFCopy", obj.pageTAFCopy);
  Session.set("pageFacebookTitle", obj.pageFacebookTitle);
  Session.set("pageFacebookCopy", obj.pageFacebookCopy);
  Session.set("pageTwitterCopy", obj.pageTwitterCopy);
  Session.set("pageConfEmailSL", obj.pageConfEmailSL);
  Session.set("pageConfEmailBody", obj.pageConfEmailBody);
  Session.set("pageTags", obj.pageTags);
  Session.set("creator", obj.creator);
  Session.set("when", obj.when);
  Session.set('AKpageURL', obj.AKpageURL);
  Session.set('AKpageEditURL', obj.AKpageEditURL);
  Session.set('AKpageBitly', obj.AKpageBitly);
  Session.set('pageSharePageLink', obj.pageSharePageLink);
  Session.set('AKpageID',obj.AKpageID);
  Session.set('AKpageResourceURI', obj.AKpageResourceURI);

  // event variables
  Session.set("eventDefaultTitle", obj.eventDefaultTitle);
  Session.set("eventDefaultSize", obj.eventDefaultSize);
  Session.set("eventMaxSize", obj.eventMaxSize);
  Session.set("eventStartDate", obj.eventStartDate);
  Session.set("eventStartTime", obj.eventStartTime);
  Session.set("eventUmbrellaCampaignURL", obj.eventUmbrellaCampaignURL);
  Session.set("eventUmbrellaHostURL", obj.eventUmbrellaHostURL);
  Session.set("eventUmbrellaSignupPageURL", obj.eventUmbrellaSignupPageURL);
};

setSessionVarsForNewPage = function () {
  // template type is set in the link event handler so not necessary here
  // clear the other email session data
  Session.set("type", "page");
  Session.set("notes", "");
  Session.set("pageTitle", "");
  Session.set("pageName", "");
  Session.set("pageStatementLeadIn", "");
  Session.set("pageStatementText", "");
  Session.set("pageAboutText", "");
  Session.set("pageGraphicEmail", "");
  Session.set("pageGraphicFacebook", "");
  Session.set("pageGraphicHomePage", "");
  Session.set("pageTAFSL", "");
  Session.set("pageTAFCopy", "");
  Session.set("pageFacebookTitle", "");
  Session.set("pageFacebookCopy", "");
  Session.set("pageTwitterCopy", "");
  Session.set("pageConfEmailSL", "");
  Session.set("pageConfEmailBody", "");
  Session.set("pageTags", "");
  Session.set("creator", "");
  Session.set('AKpageURL', "");
  Session.set('AKpageEditURL', "");
  Session.set('AKpageBitly', "");
  Session.set('pageSharePageLink', "");
  Session.set('AKpageID',"");
  Session.set('AKpageResourceURI', "");
}

setSessionVarsForNewEvent = function () {
  // additional variables to be initialized for new events
  Session.set("eventDefaultTitle", "");
  Session.set("eventDefaultSize", "");
  Session.set("eventMaxSize", "");
  Session.set("eventStartDate", "");
  Session.set("eventStartTime", "");
  Session.set("eventUmbrellaCampaignURL", "");
  Session.set("eventUmbrellaHostURL", "");
  Session.set("eventUmbrellaSignupPageURL", "");
  Session.set('subEventCreatedMsg', "");
};

setSessionVarsForNewSubEvent = function (obj) {
  Session.set("subEventTitle", obj.eventDefaultTitle);
  Session.set("subEventMaxAttendees", obj.eventDefaultSize);
  Session.set("subEventStartsAt", obj.eventStartDate + " " + obj.eventStartTime);
  Session.set("subEventHostEmail", obj.subEventHostEmail || Meteor.user().profile.name.substr(0,1)+Meteor.user().profile.name.split(" ")[1]+"@credoaction.com");

  Session.set("subEventVenue", obj.subEventVenue);
  Session.set("subEventAddress1", obj.subEventAddress1);
  Session.set("subEventAddress2", obj.subEventAddress2);
  Session.set("subEventCity", obj.subEventCity);
  Session.set("subEventState", obj.subEventState);
  Session.set("subEventZip", obj.subEventZip);
  Session.set("subEventDirections", obj.subEventDirections);
  Session.set("subEventPublicDescription", obj.subEventPublicDescription);
  Session.set("subEventNoteToAttendees", obj.subEventNoteToAttendees);

/*
  Session.set("subEventVenue", "");
  Session.set("subEventAddress1", "");
  Session.set("subEventAddress2", "");
  Session.set("subEventCity", "");
  Session.set("subEventState", "");
  Session.set("subEventZip", "");
  Session.set("subEventDirections", "");
  Session.set("subEventPublicDescription", "");
  Session.set("subEventNoteToAttendees", "");
*/
  Session.set("subEventCreatedMsg","");
};

initSessionVarsForPageCompose = function () {
  Session.set("showNavBar",false);
  Session.set("snippets",false);
  Session.set("toolTips",false);
  Session.set("pageNotSaved",false);
  Session.set("saveDialog",false);
};

window.onbeforeunload = function () {
  if (Session.get("emailNotSaved")) {
    return "This email hasn't been saved.";
  } else if (Session.get("pageNotSaved")) {
    return "This page hasn't been saved.";
  } else { return null; }
};

Handlebars.registerHelper("headlineButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'headlineAsc': return "▲";
    case 'headlineDesc': return '▼';
    default: return '—';
  }
});

Handlebars.registerHelper("typeButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'typeAsc': return "▲";
    case 'typeDesc': return '▼';
    default: return '—';
  }
});

Handlebars.registerHelper("createdByButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'createdByAsc': return "▲";
    case 'createdByDesc': return '▼';
    default: return '—';
  }
});

Handlebars.registerHelper("savedByButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'savedByAsc': return "▲";
    case 'savedByDesc': return '▼';
    default: return '—';
  }
});

Handlebars.registerHelper("savedAtButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'savedAtAsc': return "▲";
    case 'savedAtDesc': return '▼';
    default: return '—';
  }
});

Handlebars.registerHelper("belongsToUser", function(name) {
  return Meteor.user() && Meteor.user().profile.name === name;
});

Handlebars.registerHelper("isNotEvent", function(pageType) {
  return pageType !== 'event';
});

Handlebars.registerHelper("isAdmin", function() {
  var admins = ['Jin Ding'];

  return Meteor.user() && admins.indexOf(Meteor.user().profile.name) >= 0;
});
<commit_msg>update Handlebars.registerHelper to UI.registerHelper<commit_after>Meteor.startup(function () {
  Session.set("emailNotSaved",false);
});

Meteor.subscribe('files');

UI.registerHelper("wrapperStyle", function(str) {
  return Session.equals('templateChooser', str) ? "true" : "";
});

UI.registerHelper("display_setting", function(selection) {
  return Session.equals("display",selection);
});

UI.registerHelper("getValue", function(value) {
  return Session.get(value);
});

UI.registerHelper("highlight", function(value) {
  return Session.get(value) ? null : 'unchanged';
});

UI.registerHelper("sigFirstName", function() {
  return Session.get("signature").split(' ')[0];
});

UI.registerHelper("unformattedHtml", function(wrapper) {
  // return the HTML code of the template being referenced
  var div = document.createElement('div');
  switch (wrapper) {
    case "blank": UI.insert(UI.render(Template.blankEmailWrapperBody), div); break;
    case "call": UI.insert(UI.render(Template.callEmailWrapperBody), div); break;
    case "event": UI.insert(UI.render(Template.eventEmailWrapperBody), div); break;
    case "mobilize": UI.insert(UI.render(Template.mobilizeEmailWrapperBody), div); break;
    case "petition": UI.insert(UI.render(Template.petitionEmailWrapperBody), div); break;
    case "publicComment": UI.insert(UI.render(Template.publicCommentEmailWrapperBody), div); break;
    case "takeAction": UI.insert(UI.render(Template.takeActionEmailWrapperBody), div); break;
    case "superpacFundraiser": UI.insert(UI.render(Template.superpacFundraiserEmailWrapperBody), div); break;
    default: return "unformatted html not yet set";
  }
  return div.innerHTML;
});

UI.registerHelper("htmlFromMarkdown", function(field) {
  var converter = new Showdown.converter();
  return converter.makeHtml(Session.get(field));
});

UI.registerHelper("removeBackslash", function(field) {
  var str = Session.get(field);
  return str.replace(/\\/g,'');
});

UI.registerHelper("prettifyDate", function(d) {
  if (d) {
    var a_p = "";
    var curr_hour = d.getHours();
    var curr_min = d.getMinutes();
    var pad = function (x) {
      return (x < 10 ? '0' : '') + x;
    };

    if (curr_hour < 12) { a_p = "AM";}
      else { a_p = "PM"; }
    if (curr_hour == 0) { curr_hour = 12; }
    if (curr_hour > 12) { curr_hour = curr_hour - 12; }

    var str = [d.getMonth()+1,d.getDate(),d.getFullYear()-2000].join('/') +
      " " + curr_hour + ":" + pad(curr_min) + " " + a_p;
    return str;
  } else { return ''; }
});

// email functions
setSessionVarsForEmail = function (obj) {
  Session.set("id", obj._id);
  console.log("in setSessionVarsForEmail" + obj._id);
  Session.set("markdown_data", obj.markdown_data);
  Session.set("templateChooser", obj.type);
  Session.set("topper", obj.topper);
  Session.set("notes", obj.notes);
  Session.set("headline", obj.headline);
  Session.set("statement_leadin", obj.statement_leadin);
  Session.set("petition", obj.petition);
  Session.set("link", obj.link);
  Session.set("graphic", obj.graphic);
  Session.set("graphic_alt_text", obj.graphic_alt_text);
  Session.set("signature", obj.signature);
  Session.set("footnotes", obj.footnotes);
  Session.set("facebook", obj.facebook);
  Session.set("twitter", obj.twitter);
  Session.set("refcode", obj.refcode);
  Session.set("creator", obj.creator);
  Session.set("when", obj.when);
};

setSessionVarsForNewEmail = function () {
  // template type is set in the link event handler so not necessary here
  // clear the other email session data
  Session.set("markdown_data", "");
  Session.set("topper", "");
  Session.set("notes", "");
  Session.set("headline", "");
  Session.set("statement_leadin", "");
  Session.set("petition", "");
  if (Session.equals("templateChooser", "superpacFundraiser"))
    Session.set("link","https://secure.actblue.com/contribute/page/savethesenate");
  else Session.set("link", "");
  Session.set("graphic", "");
  Session.set("graphic_alt_text", "");
  if (Session.equals("templateChooser","mobilize"))
    Session.set("signature", "");
  else if (Session.equals("templateChooser","superpacFundraiser"))
    Session.set("signature", "Becky Bond, President");
  else Session.set('signature', Meteor.user().profile.name + ', Campaign Manager');
  Session.set("footnotes", "");
  Session.set("facebook", "");
  Session.set("twitter", "");
  Session.set("refcode", "");
  Session.set("creator", "");
};

setSessionVarsForEmailFromPage = function (obj) {
  Session.set("markdown_data", obj.pageAboutText);
  if (obj.pageType === 'letter')
    Session.set('templateChooser', 'takeaction')
  else Session.set("templateChooser", obj.pageType);
  Session.set("notes", obj.notes);
  Session.set("headline", obj.pageTitle);
  Session.set("statement_leadin", obj.pageStatementLeadIn);
  Session.set("petition", obj.pageStatementText);
  Session.set("link", obj.AKpageURL);
  Session.set("graphic", obj.pageGraphicEmail);
  Session.set("graphic_alt_text", "");
  Session.set("footnotes", "");
  Session.set('signature', Meteor.user().profile.name + ', Campaign Manager');
  Session.set("facebook", "");
  var twitter = obj.pageTwitterCopy.replace(/{ *LINK *}/i, obj.AKpageBitly);
  Session.set("twitter", 'https://twitter.com/intent/tweet?&text='+urlEncodeQuotes(encodeURIComponent(removeCurlyQuotes(twitter))));
  Session.set("creator", Meteor.user().profile.name);
};

initSessionVarsForEmailCompose = function () {
  Session.set("display", "visual");
  Session.set("showNavBar",false);
  Session.set("snippets",false);
  Session.set("toolTips",false);
  Session.set("emailNotSaved",false);
  Session.set("saveDialog",false);
};

removeCurlyQuotes = function (str) {
  var goodQuotes = str
  .replace(/[\u2018\u2019]/g, "'")
  .replace(/[\u201C\u201D]/g, '"');
  return goodQuotes;
};

urlEncodeQuotes = function (str) {
  return str.replace(/['""]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
};

// page functions
setSessionVarsForPage = function (obj) {
  Session.set("id", obj._id);
  Session.set("type", obj.type);
  Session.set("pageType", obj.pageType);
  Session.set('templateChooser', obj.pageType);
  Session.set("notes", obj.notes);
  Session.set("pageTitle", obj.pageTitle);
  Session.set("pageName", obj.pageName);
  Session.set("pageStatementLeadIn", obj.pageStatementLeadIn);
  Session.set("pageStatementText", obj.pageStatementText);
  Session.set("pageAboutText", obj.pageAboutText);
  Session.set("pageGraphicEmail", obj.pageGraphicEmail);
  Session.set("pageGraphicFacebook", obj.pageGraphicFacebook);
  Session.set("pageGraphicHomePage", obj.pageGraphicHomePage);
  Session.set("pageTAFSL", obj.pageTAFSL);
  Session.set("pageTAFCopy", obj.pageTAFCopy);
  Session.set("pageFacebookTitle", obj.pageFacebookTitle);
  Session.set("pageFacebookCopy", obj.pageFacebookCopy);
  Session.set("pageTwitterCopy", obj.pageTwitterCopy);
  Session.set("pageConfEmailSL", obj.pageConfEmailSL);
  Session.set("pageConfEmailBody", obj.pageConfEmailBody);
  Session.set("pageTags", obj.pageTags);
  Session.set("creator", obj.creator);
  Session.set("when", obj.when);
  Session.set('AKpageURL', obj.AKpageURL);
  Session.set('AKpageEditURL', obj.AKpageEditURL);
  Session.set('AKpageBitly', obj.AKpageBitly);
  Session.set('pageSharePageLink', obj.pageSharePageLink);
  Session.set('AKpageID',obj.AKpageID);
  Session.set('AKpageResourceURI', obj.AKpageResourceURI);

  // event variables
  Session.set("eventDefaultTitle", obj.eventDefaultTitle);
  Session.set("eventDefaultSize", obj.eventDefaultSize);
  Session.set("eventMaxSize", obj.eventMaxSize);
  Session.set("eventStartDate", obj.eventStartDate);
  Session.set("eventStartTime", obj.eventStartTime);
  Session.set("eventUmbrellaCampaignURL", obj.eventUmbrellaCampaignURL);
  Session.set("eventUmbrellaHostURL", obj.eventUmbrellaHostURL);
  Session.set("eventUmbrellaSignupPageURL", obj.eventUmbrellaSignupPageURL);
};

setSessionVarsForNewPage = function () {
  // template type is set in the link event handler so not necessary here
  // clear the other email session data
  Session.set("type", "page");
  Session.set("notes", "");
  Session.set("pageTitle", "");
  Session.set("pageName", "");
  Session.set("pageStatementLeadIn", "");
  Session.set("pageStatementText", "");
  Session.set("pageAboutText", "");
  Session.set("pageGraphicEmail", "");
  Session.set("pageGraphicFacebook", "");
  Session.set("pageGraphicHomePage", "");
  Session.set("pageTAFSL", "");
  Session.set("pageTAFCopy", "");
  Session.set("pageFacebookTitle", "");
  Session.set("pageFacebookCopy", "");
  Session.set("pageTwitterCopy", "");
  Session.set("pageConfEmailSL", "");
  Session.set("pageConfEmailBody", "");
  Session.set("pageTags", "");
  Session.set("creator", "");
  Session.set('AKpageURL', "");
  Session.set('AKpageEditURL', "");
  Session.set('AKpageBitly', "");
  Session.set('pageSharePageLink', "");
  Session.set('AKpageID',"");
  Session.set('AKpageResourceURI', "");
}

setSessionVarsForNewEvent = function () {
  // additional variables to be initialized for new events
  Session.set("eventDefaultTitle", "");
  Session.set("eventDefaultSize", "");
  Session.set("eventMaxSize", "");
  Session.set("eventStartDate", "");
  Session.set("eventStartTime", "");
  Session.set("eventUmbrellaCampaignURL", "");
  Session.set("eventUmbrellaHostURL", "");
  Session.set("eventUmbrellaSignupPageURL", "");
  Session.set('subEventCreatedMsg', "");
};

setSessionVarsForNewSubEvent = function (obj) {
  Session.set("subEventTitle", obj.eventDefaultTitle);
  Session.set("subEventMaxAttendees", obj.eventDefaultSize);
  Session.set("subEventStartsAt", obj.eventStartDate + " " + obj.eventStartTime);
  Session.set("subEventHostEmail", obj.subEventHostEmail || Meteor.user().profile.name.substr(0,1)+Meteor.user().profile.name.split(" ")[1]+"@credoaction.com");

  Session.set("subEventVenue", obj.subEventVenue);
  Session.set("subEventAddress1", obj.subEventAddress1);
  Session.set("subEventAddress2", obj.subEventAddress2);
  Session.set("subEventCity", obj.subEventCity);
  Session.set("subEventState", obj.subEventState);
  Session.set("subEventZip", obj.subEventZip);
  Session.set("subEventDirections", obj.subEventDirections);
  Session.set("subEventPublicDescription", obj.subEventPublicDescription);
  Session.set("subEventNoteToAttendees", obj.subEventNoteToAttendees);

/*
  Session.set("subEventVenue", "");
  Session.set("subEventAddress1", "");
  Session.set("subEventAddress2", "");
  Session.set("subEventCity", "");
  Session.set("subEventState", "");
  Session.set("subEventZip", "");
  Session.set("subEventDirections", "");
  Session.set("subEventPublicDescription", "");
  Session.set("subEventNoteToAttendees", "");
*/
  Session.set("subEventCreatedMsg","");
};

initSessionVarsForPageCompose = function () {
  Session.set("showNavBar",false);
  Session.set("snippets",false);
  Session.set("toolTips",false);
  Session.set("pageNotSaved",false);
  Session.set("saveDialog",false);
};

window.onbeforeunload = function () {
  if (Session.get("emailNotSaved")) {
    return "This email hasn't been saved.";
  } else if (Session.get("pageNotSaved")) {
    return "This page hasn't been saved.";
  } else { return null; }
};

UI.registerHelper("headlineButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'headlineAsc': return "▲";
    case 'headlineDesc': return '▼';
    default: return '—';
  }
});

UI.registerHelper("typeButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'typeAsc': return "▲";
    case 'typeDesc': return '▼';
    default: return '—';
  }
});

UI.registerHelper("createdByButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'createdByAsc': return "▲";
    case 'createdByDesc': return '▼';
    default: return '—';
  }
});

UI.registerHelper("savedByButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'savedByAsc': return "▲";
    case 'savedByDesc': return '▼';
    default: return '—';
  }
});

UI.registerHelper("savedAtButtonText", function() {
  switch (Session.get("fileSort")) {
    case 'savedAtAsc': return "▲";
    case 'savedAtDesc': return '▼';
    default: return '—';
  }
});

UI.registerHelper("belongsToUser", function(name) {
  return Meteor.user() && Meteor.user().profile.name === name;
});

UI.registerHelper("isNotEvent", function(pageType) {
  return pageType !== 'event';
});

UI.registerHelper("isAdmin", function() {
  var admins = ['Jin Ding'];

  return Meteor.user() && admins.indexOf(Meteor.user().profile.name) >= 0;
});
<|endoftext|>


<commit_before>define(['app'], function (app) {

app.directive('searchFilterDates', function ($http) {
    return {
        restrict: 'EAC',
        templateUrl: '/app/views/directives/search-filter-dates.partial.html',
        replace: true,
        scope: {
              title: '@title',
              query: '=query',
              field: '@field'
              //since: '=since',
              //until: '=until'
        },
        link: function ($scope, element, attrs, ngModelController) {
        },
        controller : ["$scope", function ($scope) {

            var now = new Date();

            $scope.dates = [
                { text: 'Any', date: '' },
                { text: 'Last day', date: new Date(new Date(now).setDate(now.getDate()-1)).toISOString() },
                { text: 'Last week', date: new Date(new Date(now).setDate(now.getDate()-7)).toISOString() },
                { text: 'Last two weeks', date: new Date(new Date(now).setDate(now.getDate()-14)).toISOString() },
                { text: 'Last month', date: new Date(new Date(now).setMonth(now.getMonth()-1)).toISOString() },
                { text: 'Last two months', date: new Date(new Date(now).setMonth(now.getMonth()-2)).toISOString() },
                { text: 'Last six months', date: new Date(new Date(now).setMonth(now.getMonth()-6)).toISOString() },
                { text: 'Last year', date: new Date(new Date(now).setMonth(now.getMonth()-12)).toISOString() },
            ];

            $scope.since = null;
            $scope.until = null;
            $scope.selectedDate = '';

            $scope.$watch('since', updateQuery);
            $scope.$watch('until', updateQuery);

            function updateQuery () {

                if($scope.since || $scope.until) {
                    var since = $scope.since ? $scope.since + 'T00:00:00.000Z' : '*';
                    var until = $scope.until ? $scope.until + 'T23:59:59.999Z' : '*';

                    $scope.query = ' (' + $scope.field +':[ ' + since + ' TO ' + until + ' ] ) ';
                } else {
                    $scope.query = '*:*';
                }
            };

            $scope.$watch('selectedDate', function (value) {
                $scope.since = $scope.selectedDate.date ? new Date($scope.selectedDate.date).toISOString().substr(0, 10) : null;
                $scope.until = null;
            });

            $scope.updateQuery = updateQuery;

             $('.dropdowndate').on("click", "*", function (e) {
                e.stopPropagation();
            });

            $(document).on('click', 'span.month, th.next, th.prev, th.switch, span.year, td.day, th.dow, th.datepicker-switch', function (e) {
                e.stopPropagation();
            });

            $scope.clearSelection = function(){
                $scope.since = null;
                $scope.until = null;
                $scope.selectedDate = '';
            }

			$scope.$parent.$on('clearSelectSelection', function(){
				 $scope.clearSelection();
			})

            $scope.hasSelectedItems = function(){
                    return $scope.query.length > 0 && $scope.query !="*:*";
            }
        }]
    }
})

});
<commit_msg>date filter string for filter box<commit_after>define(['app'], function (app) {

app.directive('searchFilterDates', function ($http) {
    return {
        restrict: 'EAC',
        templateUrl: '/app/views/directives/search-filter-dates.partial.html',
        replace: true,
        scope: {
              title: '@title',
              query: '=query',
              field: '@field',
              api   : '=?'
              //since: '=since',
              //until: '=until'
        },
        link: function ($scope, element, attrs, ngModelController) {
        },
        controller : ["$scope", "$filter", function ($scope, $filter) {

            $scope.api = {
                getDateString : getDateString,
                clearSelection  : clearSelection
            };

            function clearSelection(){
                $scope.since = null;
                $scope.until = null;
                $scope.selectedDate = '';
            }
            function getDateString(){
                if($scope.since || $scope.until) {
                    var since = $scope.since ? 'since ' +  $filter("formatDate")($scope.since)  : '';
                    var until = $scope.until ? ' until ' +  $filter("formatDate")($scope.until)  : '';

                    return since + until;
                }
                return '';
            }

            var now = new Date();

            $scope.dates = [
                { text: 'Any', date: '' },
                { text: 'Last day', date: new Date(new Date(now).setDate(now.getDate()-1)).toISOString() },
                { text: 'Last week', date: new Date(new Date(now).setDate(now.getDate()-7)).toISOString() },
                { text: 'Last two weeks', date: new Date(new Date(now).setDate(now.getDate()-14)).toISOString() },
                { text: 'Last month', date: new Date(new Date(now).setMonth(now.getMonth()-1)).toISOString() },
                { text: 'Last two months', date: new Date(new Date(now).setMonth(now.getMonth()-2)).toISOString() },
                { text: 'Last six months', date: new Date(new Date(now).setMonth(now.getMonth()-6)).toISOString() },
                { text: 'Last year', date: new Date(new Date(now).setMonth(now.getMonth()-12)).toISOString() },
            ];

            $scope.since = null;
            $scope.until = null;
            $scope.selectedDate = '';

            $scope.$watch('since', updateQuery);
            $scope.$watch('until', updateQuery);

            function updateQuery () {

                if($scope.since || $scope.until) {
                    var since = $scope.since ? $scope.since + 'T00:00:00.000Z' : '*';
                    var until = $scope.until ? $scope.until + 'T23:59:59.999Z' : '*';

                    $scope.query = ' (' + $scope.field +':[ ' + since + ' TO ' + until + ' ] ) ';
                } else {
                    $scope.query = '*:*';
                }
            };

            $scope.$watch('selectedDate', function (value) {
                $scope.since = $scope.selectedDate.date ? new Date($scope.selectedDate.date).toISOString().substr(0, 10) : null;
                $scope.until = null;
            });

            $scope.updateQuery = updateQuery;

             $('.dropdowndate').on("click", "*", function (e) {
                e.stopPropagation();
            });

            $(document).on('click', 'span.month, th.next, th.prev, th.switch, span.year, td.day, th.dow, th.datepicker-switch', function (e) {
                e.stopPropagation();
            });

			$scope.$parent.$on('clearSelectSelection', function(){
				 clearSelection();
			})

            $scope.hasSelectedItems = function(){
                    return $scope.query.length > 0 && $scope.query !="*:*";
            }
        }]
    }
})

});
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var Transform = require( 'readable-stream' ).Transform;
var logger = require( 'debug' );
var Buffer = require( '@stdlib/buffer/ctor' );
var copy = require( '@stdlib/utils/copy' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );

// VARIABLES //

var debug = logger( 'join-stream' );

// MAIN //

/**
* Join stream constructor.
*
* @constructor
* @param {Options} [options] - stream options
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.readableObjectMode=false] - specifies whether the readable side should be in object mode
* @throws {TypeError} must provide valid options
* @returns {JoinStream} join stream
*
* @example
* var inspectStream = require( '@stdlib/streams/utils/inspect' );
*
* function log( chunk ) {
*    console.log( chunk );
* }
*
* var stream = new JoinStream();
*
* stream.pipe( inspectStream( log )  );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3'
*/
function JoinStream( options ) {
	var opts;
	var err;
	if ( !( this instanceof JoinStream ) ) {
		if ( arguments.length ) {
			return new JoinStream( options );
		}
		return new JoinStream();
	}
	opts = copy( DEFAULTS );
	if ( arguments.length ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// The stream's writable state should always be in object mode to prevent incoming data from being buffered (concatenated) and thus lose separation...
	opts.writableObjectMode = true;

	// The stream converts each chunk into a string so no need to encode strings written to the join stream as Buffer objects:
	opts.decodeStrings = false;

	// Make the stream a Transform stream:
	debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
	Transform.call( this, opts );

	// The destruction state:
	this._destroyed = false;

	// Cache the encoding...
	this._encoding = ( opts.encoding === null ) ? 'utf8' : opts.encoding;

	// Cache the separator...
	if ( this._encoding === 'utf8' ) {
		this._sep = opts.sep;
	} else {
		this._sep = new Buffer( opts.sep, this._encoding );
	}
	// Flag indicating if the stream has received streamed data:
	this._init = false;

	// Chunk counter:
	this._idx = -1;

	return this;
}

/*
* Create a prototype which inherits from the parent prototype.
*/
JoinStream.prototype = Object.create( Transform.prototype );

/*
* Set the constructor.
*/
JoinStream.prototype.constructor = JoinStream;

/**
* Implements the `_transform` method.
*
* @private
* @memberof JoinStream.prototype
* @function _transform
* @param {(Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
JoinStream.prototype._transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle

/**
* Implements the `_flush` method.
*
* @private
* @memberof JoinStream.prototype
* @function _flush
* @param {Callback} clbk - callback to invoke after performing flush tasks
*/
JoinStream.prototype._flush = require( './_flush.js' ); // eslint-disable-line no-underscore-dangle

/**
* Gracefully destroys a stream, providing backwards compatibility.
*
* @memberof JoinStream.prototype
* @function destroy
* @param {Object} [error] - optional error message
* @returns {JoinStream} Stream instance
*/
JoinStream.prototype.destroy = require( './destroy.js' );

// EXPORTS //

module.exports = JoinStream;
<commit_msg>Use `inherit` utility<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

// MODULES //

var Transform = require( 'readable-stream' ).Transform;
var logger = require( 'debug' );
var Buffer = require( '@stdlib/buffer/ctor' );
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );

// VARIABLES //

var debug = logger( 'join-stream' );

// MAIN //

/**
* Join stream constructor.
*
* @constructor
* @param {Options} [options] - stream options
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to `strings`
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.readableObjectMode=false] - specifies whether the readable side should be in object mode
* @throws {TypeError} must provide valid options
* @returns {JoinStream} join stream
*
* @example
* var inspectStream = require( '@stdlib/streams/utils/inspect' );
*
* function log( chunk ) {
*    console.log( chunk );
* }
*
* var stream = new JoinStream();
*
* stream.pipe( inspectStream( log )  );
*
* stream.write( '1' );
* stream.write( '2' );
* stream.write( '3' );
*
* stream.end();
*
* // prints: '1\n2\n3'
*/
function JoinStream( options ) {
	var opts;
	var err;
	if ( !( this instanceof JoinStream ) ) {
		if ( arguments.length ) {
			return new JoinStream( options );
		}
		return new JoinStream();
	}
	opts = copy( DEFAULTS );
	if ( arguments.length ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// The stream's writable state should always be in object mode to prevent incoming data from being buffered (concatenated) and thus lose separation...
	opts.writableObjectMode = true;

	// The stream converts each chunk into a string so no need to encode strings written to the join stream as Buffer objects:
	opts.decodeStrings = false;

	// Make the stream a Transform stream:
	debug( 'Creating a transform stream configured with the following options: %s.', JSON.stringify( opts ) );
	Transform.call( this, opts );

	// The destruction state:
	this._destroyed = false;

	// Cache the encoding...
	this._encoding = ( opts.encoding === null ) ? 'utf8' : opts.encoding;

	// Cache the separator...
	if ( this._encoding === 'utf8' ) {
		this._sep = opts.sep;
	} else {
		this._sep = new Buffer( opts.sep, this._encoding );
	}
	// Flag indicating if the stream has received streamed data:
	this._init = false;

	// Chunk counter:
	this._idx = -1;

	return this;
}

/*
* Inherit from the `Transform` prototype.
*/
inherit( JoinStream, Transform );

/**
* Implements the `_transform` method.
*
* @private
* @memberof JoinStream.prototype
* @function _transform
* @param {(Buffer|string)} chunk - streamed chunk
* @param {string} encoding - Buffer encoding
* @param {Callback} clbk - callback to invoke after transforming the streamed chunk
*/
JoinStream.prototype._transform = require( './_transform.js' ); // eslint-disable-line no-underscore-dangle

/**
* Implements the `_flush` method.
*
* @private
* @memberof JoinStream.prototype
* @function _flush
* @param {Callback} clbk - callback to invoke after performing flush tasks
*/
JoinStream.prototype._flush = require( './_flush.js' ); // eslint-disable-line no-underscore-dangle

/**
* Gracefully destroys a stream, providing backwards compatibility.
*
* @memberof JoinStream.prototype
* @function destroy
* @param {Object} [error] - optional error message
* @returns {JoinStream} Stream instance
*/
JoinStream.prototype.destroy = require( './destroy.js' );

// EXPORTS //

module.exports = JoinStream;
<|endoftext|>