<commit_before>(function($){

    $.scrollable = function(opts){
        if(opts == undefined){
            opts = $.fn.scrollable.defaults;
        }
        this.options = opts;
    };

    $.extend($.scrollable.prototype, {
        init: function(element){
            this.element = element.css('overflow', 'hidden');
            this.element.addClass('scrollable');
            this.element.wrapInner('
');
            this.element.wrapInner('
');
            this.scrollableArea = this.element.find('.scrollable-area:eq(0)');
            this.scrollableContainer = this.element.find('.scrollable-container:eq(0)');
            this.scrolling = { x: { container: null, handle: null }, y: { container: null, handle: null } };
            this.updateContainer();
            var $this = this;
            $(window).on('resize', function(){
                $this.updateContainer();
                $this.updateArea();
            });
            this.element.on('update', function(){
                $this.updateContainer();
                $this.updateArea();
                $this.options.onUpdate();
            });
            if(this.options.autoHide){
                this.element.addClass('autohide');
                this.element.hover(function(){
                    $(this).addClass('hover');
                }, function(){
                    $(this).removeClass('hover');
                });
            }
            if(this.options.mouseWheel){
                this.element.on('mousewheel', function(e){
                    if(e.deltaY != 0 && $this.scrolling.y.handle != null){
                        if($this.getOffset('top', $this.scrolling.y.handle) >= 0){
                            var new_top = $this.getOffset('top', $this.scrolling.y.handle) + (e.deltaY * -1);
                            new_top = (new_top <= 0 ? 0 : new_top);
                            new_top = (new_top + $this.scrolling.y.handle.height() >= $this.scrolling.y.container.height() ? $this.scrolling.y.container.height() - $this.scrolling.y.handle.height() : new_top);
                            $this.scrolling.y.handle.css('top', new_top);
                            $this.moveArea({ top: new_top }, 'y');
                        }
                    }
                    if(e.deltaX != 0 && $this.scrolling.x.handle != null){
                        if($this.getOffset('left', $this.scrolling.x.handle) >= 0){
                            var new_left = $this.getOffset('left', $this.scrolling.x.handle) + e.deltaX;
                            new_left = (new_left <= 0 ? 0 : new_left);
                            new_left = (new_left + $this.scrolling.x.handle.width() >= $this.scrolling.x.container.width() ? $this.scrolling.x.container.width() - $this.scrolling.x.handle.width() : new_left);
                            $this.scrolling.x.handle.css('left', new_left);
                            $this.moveArea({ left: new_left }, 'x');
                        }
                    }
                });
            }
        },
        getOffset: function(direction, el){
            if(el.css(direction) == 'auto'){
                return 0;
            } else {
                return parseInt(el.css(direction));
            }
        },
        getAreaSize: function(direction){
            if(direction == 'width'){
                return this.scrollableArea.prop('scrollWidth');
            } else {
                return this.scrollableArea.prop('scrollHeight');
            }
        },
        updateScrollbars: function(){
            if(this.scrollableContainer.width() < this.getAreaSize('width')){
                if(this.scrolling.x.container == null){
                    this.drawScrollbar('x');
                }
            } else {
                if(this.scrolling.x.container != null){
                    this.scrolling.x.container.parent().remove();
                    this.scrolling.x.handle = null;
                    this.scrolling.x.container = null;
                }
            }
            if(this.scrollableContainer.height() < this.scrollableArea.height()){
                if(this.scrolling.y.container == null){
                    this.drawScrollbar('y');
                }
            } else {
                if(this.scrolling.y.container != null){
                    this.scrolling.y.container.parent().remove();
                    this.scrolling.y.handle = null;
                    this.scrolling.y.container = null;
                }
            }
            this.updateHandleSize();
        },
        updateContainer: function(){
            if(!this.element.height())
            {
                this.element.height(this.scrollableArea.height());
            }

            if(!this.element.width())
            {
                this.element.width('100%');
            }

            this.scrollableContainer.width(this.element.width());
            this.scrollableContainer.height(this.element.height());
            this.updateScrollbars();
        },
        drawScrollbar: function(axis){
            var $this = this;
            this.scrolling[axis].handle = $('').addClass('handle').hover(function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); });
            this.scrolling[axis].container = $('').addClass('handle-container').append(this.scrolling[axis].handle);
            this.element.prepend($('').addClass('scrollbar').addClass('scrollbar-' + axis).append(this.scrolling[axis].container));
            $('.scrollbar-' + axis + ' .handle-container .handle', this.element).draggable({
                axis: axis,
                containment: 'parent',
                drag: function(e, ui){
                    $this.moveArea(ui.position, axis);
                }
            });
        },
        updateHandleSize: function(){
            if(this.scrolling.x.container != null && this.scrolling.y.container != null){
                this.scrolling.x.container.parent().addClass('corner');
                this.scrolling.y.container.parent().addClass('corner');
            } else {
                if(this.scrolling.x.container != null){
                    this.scrolling.x.container.parent().removeClass('corner');
                }
                if(this.scrolling.y.container != null){
                    this.scrolling.y.container.parent().removeClass('corner');
                }
            }
            var ratios = [
                this.scrollableContainer.width() / this.getAreaSize('width'),
                this.scrollableContainer.height() / this.getAreaSize('height')
            ];
            if(this.scrolling.x.container != null){
                this.scrolling.x.handle.width(Math.round(this.scrolling.x.container.width() * ratios[0]));
            }
            if(this.scrolling.y.container != null){
                this.scrolling.y.handle.height(Math.round(this.scrolling.y.container.height() * ratios[1]));
            }
        },
        moveArea: function(offset, axis){
            var ratio = 0;
            if(axis == 'x'){
                ratio = (this.getAreaSize('width') - this.scrollableContainer.width()) / (this.scrolling.x.container.width() - this.scrolling.x.handle.width());
                this.scrollableArea.css('left', Math.round((offset.left * ratio) * -1));
            } else {
                ratio = (this.getAreaSize('height') - this.scrollableContainer.height()) / (this.scrolling.y.container.height() - this.scrolling.y.handle.height());
                this.scrollableArea.css('top', Math.round((offset.top * ratio) * -1));
            }
        },
        updateArea: function(){
            if(this.scrolling.y.container != null){
                var percent_y = Math.round((this.getOffset('top', this.scrollableArea) / (this.scrollableContainer.height() - this.getAreaSize('height'))) * 100);
                percent_y = percent_y >= 100 ? 100 : percent_y;
                var new_top = Math.round((this.scrolling.y.container.height() - this.scrolling.y.handle.height()) * percent_y / 100);
                this.scrolling.y.handle.css('top', new_top);
                if(percent_y == 100){
                    this.moveArea({ top: new_top }, 'y');
                }
            } else {
                this.scrollableArea.css('top', 0);
            }
            if(this.scrolling.x.container != null){
                var percent_x = Math.round((this.getOffset('left', this.scrollableArea) / (this.scrollableContainer.width() - this.getAreaSize('width'))) * 100);
                percent_x = percent_x >= 100 ? 100 : percent_x;
                var new_left = Math.round((this.scrolling.x.container.width() - this.scrolling.x.handle.width()) * percent_x / 100);
                this.scrolling.x.handle.css('left', new_left);
                if(percent_x == 100){
                    this.moveArea({ left: new_left }, 'x');
                }
            } else {
                this.scrollableArea.css('left', 0);
            }
        }
    });

    $.fn.scrollable = function(options){
        if(options == undefined){
            options = {};
        }
        this.each(function(){
            new $.scrollable($.extend({}, $.fn.scrollable.defaults, options)).init($(this));
        });
        return this;
    };

    $.fn.scrollable.defaults = {
        onUpdate: function(){},
        mouseWheel: true,
        autoHide: true
    };
})(jQuery);<commit_msg>Some fixes<commit_after>(function($){

    $.scrollable = function(opts){
        if(opts == undefined){
            opts = $.fn.scrollable.defaults;
        }
        this.options = opts;
    };

    $.extend($.scrollable.prototype, {
        init: function(element){
            this.element = element.css('overflow', 'hidden');
            this.element.addClass('scrollable');
            this.element.wrapInner('
');
            this.element.wrapInner('
');
            this.scrollableArea = this.element.find('.scrollable-area:eq(0)');
            this.scrollableContainer = this.element.find('.scrollable-container:eq(0)');
            this.scrolling = { x: { container: null, handle: null }, y: { container: null, handle: null } };
            this.updateContainer();
            this.lastWidth = this.getAreaSize('width');
            this.lastHeight = this.getAreaSize('height');
            var $this = this;
            $(window).on('resize', function(){
                $this.updateContainer();
                $this.updateArea();
            });
            this.element.on('update', function(){
                $this.updateContainer();
                $this.updateArea();
                $this.options.onUpdate();
            });
            if(this.options.autoHide){
                this.element.addClass('autohide');
                this.element.hover(function(){
                    $(this).addClass('hover');
                }, function(){
                    $(this).removeClass('hover');
                });
            }
            setInterval(function(){
                if($this.lastWidth != $this.getAreaSize('width') || $this.lastHeight != $this.getAreaSize('height')){
                    $this.element.trigger('update');
                    $this.lastWidth = $this.getAreaSize('width');
                    $this.lastHeight = $this.getAreaSize('height');
                }
            }, 500);
            if(this.options.mouseWheel){
                this.element.on('mousewheel', function(e){
                    if(e.deltaY != 0 && $this.scrolling.y.handle != null){
                        if($this.getOffset('top', $this.scrolling.y.handle) >= 0){
                            e.preventDefault();
                            var new_top = $this.getOffset('top', $this.scrolling.y.handle) + (e.deltaY * -1);
                            new_top = (new_top <= 0 ? 0 : new_top);
                            new_top = (new_top + $this.scrolling.y.handle.height() >= $this.scrolling.y.container.height() ? $this.scrolling.y.container.height() - $this.scrolling.y.handle.height() : new_top);
                            $this.scrolling.y.handle.css('top', new_top);
                            $this.moveArea({ top: new_top }, 'y');
                        }
                    }
                    if(e.deltaX != 0 && $this.scrolling.x.handle != null){
                        if($this.getOffset('left', $this.scrolling.x.handle) >= 0){
                            e.preventDefault();
                            var new_left = $this.getOffset('left', $this.scrolling.x.handle) + e.deltaX;
                            new_left = (new_left <= 0 ? 0 : new_left);
                            new_left = (new_left + $this.scrolling.x.handle.width() >= $this.scrolling.x.container.width() ? $this.scrolling.x.container.width() - $this.scrolling.x.handle.width() : new_left);
                            $this.scrolling.x.handle.css('left', new_left);
                            $this.moveArea({ left: new_left }, 'x');
                        }
                    }
                });
            }
        },
        getOffset: function(direction, el){
            if(el.css(direction) == 'auto'){
                return 0;
            } else {
                return parseInt(el.css(direction));
            }
        },
        getAreaSize: function(direction){
            if(direction == 'width'){
                return this.scrollableArea.prop('scrollWidth');
            } else {
                return this.scrollableArea.prop('scrollHeight');
            }
        },
        updateScrollbars: function(){
            if(this.scrollableContainer.width() < this.getAreaSize('width')){
                if(this.scrolling.x.container == null){
                    this.drawScrollbar('x');
                }
            } else {
                if(this.scrolling.x.container != null){
                    this.scrolling.x.container.parent().remove();
                    this.scrolling.x.handle = null;
                    this.scrolling.x.container = null;
                }
            }
            if(this.scrollableContainer.height() < this.scrollableArea.height()){
                if(this.scrolling.y.container == null){
                    this.drawScrollbar('y');
                }
            } else {
                if(this.scrolling.y.container != null){
                    this.scrolling.y.container.parent().remove();
                    this.scrolling.y.handle = null;
                    this.scrolling.y.container = null;
                }
            }
            this.updateHandleSize();
        },
        updateContainer: function(){
            if(!this.element.height())
            {
                this.element.height(this.scrollableArea.height());
            }

            if(!this.element.width())
            {
                this.element.width('100%');
            }

            this.scrollableContainer.width(this.element.width());
            this.scrollableContainer.height(this.element.height());
            this.updateScrollbars();
        },
        drawScrollbar: function(axis){
            var $this = this;
            this.scrolling[axis].handle = $('').addClass('handle').hover(function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); });
            this.scrolling[axis].container = $('').addClass('handle-container').append(this.scrolling[axis].handle);
            this.element.prepend($('').addClass('scrollbar').addClass('scrollbar-' + axis).append(this.scrolling[axis].container));
            $('.scrollbar-' + axis + ' .handle-container .handle', this.element).draggable({
                axis: axis,
                containment: 'parent',
                drag: function(e, ui){
                    $this.moveArea(ui.position, axis);
                }
            });
        },
        updateHandleSize: function(){
            if(this.scrolling.x.container != null && this.scrolling.y.container != null){
                this.scrolling.x.container.parent().addClass('corner');
                this.scrolling.y.container.parent().addClass('corner');
            } else {
                if(this.scrolling.x.container != null){
                    this.scrolling.x.container.parent().removeClass('corner');
                }
                if(this.scrolling.y.container != null){
                    this.scrolling.y.container.parent().removeClass('corner');
                }
            }
            var ratios = [
                this.scrollableContainer.width() / this.getAreaSize('width'),
                this.scrollableContainer.height() / this.getAreaSize('height')
            ];
            if(this.scrolling.x.container != null){
                this.scrolling.x.handle.width(Math.round(this.scrolling.x.container.width() * ratios[0]));
            }
            if(this.scrolling.y.container != null){
                this.scrolling.y.handle.height(Math.round(this.scrolling.y.container.height() * ratios[1]));
            }
        },
        moveArea: function(offset, axis){
            var ratio = 0;
            if(axis == 'x'){
                ratio = (this.getAreaSize('width') - this.scrollableContainer.width()) / (this.scrolling.x.container.width() - this.scrolling.x.handle.width());
                this.scrollableArea.css('left', Math.round((offset.left * ratio) * -1));
            } else {
                ratio = (this.getAreaSize('height') - this.scrollableContainer.height()) / (this.scrolling.y.container.height() - this.scrolling.y.handle.height());
                this.scrollableArea.css('top', Math.round((offset.top * ratio) * -1));
            }
        },
        updateArea: function(){
            if(this.scrolling.y.container != null){
                var percent_y = Math.round((this.getOffset('top', this.scrollableArea) / (this.scrollableContainer.height() - this.getAreaSize('height'))) * 100);
                percent_y = percent_y >= 100 ? 100 : percent_y;
                var new_top = Math.round((this.scrolling.y.container.height() - this.scrolling.y.handle.height()) * percent_y / 100);
                this.scrolling.y.handle.css('top', new_top);
                if(percent_y == 100){
                    this.moveArea({ top: new_top }, 'y');
                }
            } else {
                this.scrollableArea.css('top', 0);
            }
            if(this.scrolling.x.container != null){
                var percent_x = Math.round((this.getOffset('left', this.scrollableArea) / (this.scrollableContainer.width() - this.getAreaSize('width'))) * 100);
                percent_x = percent_x >= 100 ? 100 : percent_x;
                var new_left = Math.round((this.scrolling.x.container.width() - this.scrolling.x.handle.width()) * percent_x / 100);
                this.scrolling.x.handle.css('left', new_left);
                if(percent_x == 100){
                    this.moveArea({ left: new_left }, 'x');
                }
            } else {
                this.scrollableArea.css('left', 0);
            }
        }
    });

    $.fn.scrollable = function(options){
        if(options == undefined){
            options = {};
        }
        this.each(function(){
            new $.scrollable($.extend({}, $.fn.scrollable.defaults, options)).init($(this));
        });
        return this;
    };

    $.fn.scrollable.defaults = {
        onUpdate: function(){},
        mouseWheel: true,
        autoHide: true
    };
})(jQuery);

/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version: 3.1.12
 *
 * Requires: jQuery 1.2.2+
 */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});<|endoftext|>


<commit_before>module.exports = function(fl, callback){
	Ti.API.info("loading friendlist: ");
	Ti.API.info(JSON.stringify(fl));
	var tbl_data = [];
	var table = Titanium.UI.createView
	({
		backgroundColor:'transparent',
		top:10,
		width:Ti.UI.SIZE,
		height:Ti.UI.SIZE,
		layout:'vertical',
		right: 10,
		bottom: 10
	});
	//result.Products.List
	for(var i = 0; i < fl.length; ++i)
	{
		f = fl[i];
		var row = Ti.UI.createView({
			height: Ti.UI.SIZE,
			width: Ti.UI.FILL
		});

		var rc = Ti.UI.createView({
			width: Ti.UI.FILL,
			height: Ti.UI.SIZE,
			top: 12,
			//right: 5,
			borderRadius: 5,
			backgroundColor: '#fcf3e1',
			layout: 'horizontal'
		});
		rc.friend = f;
		// This image will be the image of the user
		var image = Ti.UI.createImageView
		({
  			  	//height: Ti.UI.SIZE,
		  		width: '100dp',//'27%',
		  		//height: 100,
				top: 10,
				bottom: 10,
				left: 5,
				borderWidth: 1,
				borderRadius: 10,
		  		clipsToBounds: true,
		  		image: f.picture_url,
		  		touchEnabled: false
		});
		var txt_container = Ti.UI.createView({
			height: Ti.UI.SIZE,
			width: '70%',
			top: 5,
			layout: 'vertical',
		  		touchEnabled: false
		});
		// Label for the location of the wine within the row
		var lbl_location = Ti.UI.createLabel
		({
			color:'black',
			bottom:5,
			right: 5,
			text: f.checkin_count + ' Check-Ins',
			font:{fontSize:12,fontWeight:'normal',fontFamily:'Helvetica Neue'},
			touchEnabled:false
		});

		// Label for the type of wine within the row
		var lbl_type = Ti.UI.createLabel
		({
			color:'black',
			text: f.fname + ' ' + f.lname,
			bottom:lbl_location.top,
			font:{fontSize:14,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			touchEnabled:false

		});

		row.addEventListener('click',function(data){
			callback(data.source.friend);
		});
		// Add each of these features to the row, then push the row
		row.add(rc);
		rc.add(image);
		rc.add(txt_container);
		txt_container.add(lbl_location);
		txt_container.add(lbl_type);
		table.add(row);
	}

	return table;
}

<commit_msg>fixed iphone friends bug<commit_after>module.exports = function(fl, callback){
	Ti.API.info("loading friendlist: ");
	Ti.API.info(JSON.stringify(fl));
	var tbl_data = [];
	var table = Titanium.UI.createView
	({
		backgroundColor:'transparent',
		top:10,
		width:Ti.UI.SIZE,
		height:Ti.UI.SIZE,
		layout:'vertical',
		right: 10,
		bottom: 10
	});
	//result.Products.List
	for(var i = 0; i < fl.length; ++i)
	{
		f = fl[i];
		var row = Ti.UI.createView({
			height: Ti.UI.SIZE,
			width: Ti.UI.FILL
		});

		var rc = Ti.UI.createView({
			width: Ti.UI.FILL,
			height: Ti.UI.SIZE,
			top: 12,
			//right: 5,
			borderRadius: 5,
			backgroundColor: '#fcf3e1',
			layout: 'horizontal'
		});
		rc.friend = f;
		// This image will be the image of the user
		var image = Ti.UI.createImageView
		({
  			  	height: Ti.UI.SIZE,
		  		width: '27%',
		  		//height: 100,
				top: 10,
				bottom: 10,
				left: 5,
				borderWidth: 1,
				borderRadius: 10,
		  		clipsToBounds: true,
		  		image: f.picture_url,
		  		touchEnabled: false
		});
		var txt_container = Ti.UI.createView({
			height: Ti.UI.SIZE,
			width: '70%',
			top: 5,
			layout: 'vertical',
		  		touchEnabled: false
		});
		// Label for the location of the wine within the row
		var lbl_location = Ti.UI.createLabel
		({
			color:'black',
			bottom:5,
			right: 5,
			text: f.checkin_count + ' Check-Ins',
			font:{fontSize:12,fontWeight:'normal',fontFamily:'Helvetica Neue'},
			touchEnabled:false
		});

		// Label for the type of wine within the row
		var lbl_type = Ti.UI.createLabel
		({
			color:'black',
			text: f.fname + ' ' + f.lname,
			bottom:lbl_location.top,
			font:{fontSize:14,fontWeight:'bold',fontFamily:'Helvetica Neue'},
			touchEnabled:false

		});

		row.addEventListener('click',function(data){
			callback(data.source.friend);
		});
		// Add each of these features to the row, then push the row
		row.add(rc);
		rc.add(image);
		rc.add(txt_container);
		txt_container.add(lbl_location);
		txt_container.add(lbl_type);
		table.add(row);
	}

	return table;
}

<|endoftext|>


<commit_before>/**
 * Copyright 2014 iaceob
 *
 * 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.
 */

;(function($) {
    var pluginName = "top_msg";
    $[pluginName] = function(message, type, arg) {
        var defaults = {
            background:"#de4343",
            bordercolor:"#fff",
            color:"#000",
            height:70,
            fontsize:20,
            close:3e3,
            click: false,
            domid:"JQ_TOP_MSG",
            msg:message ? message :""
        };
        if (type) {
            defaults.background = "#48bb5e";
        }
        if ( arg.click ) {
        	defaults.click = true;
        }
        var options = $.extend(defaults, arg);
        var barStyle = " width: 100%;position: fixed;height: " + options.height + "px;top: 0px;left: 0px;right: 0px;margin: 0px;display: none; z-index: 99999";
        var overlayStyle = "height: " + options.height + "px;background-color: " + options.background + ";border: solid 1px " + options.bordercolor + ";";
        var messageStyle = " width: 100%;position: absolute;height: " + options.height + "px;top: 0px;left: 0px;right: 0px;margin: 0px;color: " + options.color + ";font-weight: bold;font-size: " + options.fontsize + "px;text-align: center;padding: 10px 0px";
        var html = '

' + options.msg + "

";
        if ($("#" + options.domid).length > 0) {
            // Hide already existing bars
            $("#" + options.domid).hide();
            $("#" + options.domid).slideUp(200, function() {
                $("#" + options.domid).remove();
            });
        }
        if ( options.click ) {
            $(html).click(function() {
                $(this).slideUp(200, function() {
                    $(this).remove();
                });
            }).appendTo($("body")).slideDown(200);
        } else {
            $(html).appendTo($("body")).slideDown(200).delay(options.close).slideUp(200, function() {
                $(this).remove();
            });
        }
    };
    $.extend($[pluginName], {
        version:1.0,
        TYPE_ERROR:0,
        TYPE_OK:1
    });
})(jQuery);
<commit_msg>update click bug<commit_after>/**
 * Copyright 2014 iaceob
 *
 * 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.
 */

;(function($) {
    var pluginName = "top_msg";
    $[pluginName] = function(message, type, arg) {
        var defaults = {
            background:"#de4343",
            bordercolor:"#fff",
            color:"#000",
            height:70,
            fontsize:20,
            close:3e3,
            click: false,
            domid:"JQ_TOP_MSG",
            msg:message ? message :""
        };
        if ( type ) {
            defaults.background = "#48bb5e";
        }
        if ( arg ? arg.click : false ) {
        	defaults.click = true;
        }
        var options = $.extend(defaults, arg);
        var barStyle = " width: 100%;position: fixed;height: " + options.height + "px;top: 0px;left: 0px;right: 0px;margin: 0px;display: none; z-index: 99999";
        var overlayStyle = "height: " + options.height + "px;background-color: " + options.background + ";border: solid 1px " + options.bordercolor + ";";
        var messageStyle = " width: 100%;position: absolute;height: " + options.height + "px;top: 0px;left: 0px;right: 0px;margin: 0px;color: " + options.color + ";font-weight: bold;font-size: " + options.fontsize + "px;text-align: center;padding: 10px 0px";
        var html = '

' + options.msg + "

";
        if ($("#" + options.domid).length > 0) {
            $("#" + options.domid).hide();
            $("#" + options.domid).slideUp(200, function() {
                $("#" + options.domid).remove();
            });
        }
        if ( options.click ) {
            $(html).click(function() {
                $(this).slideUp(200, function() {
                    $(this).remove();
                });
            }).appendTo($("body")).slideDown(200);
        } else {
            $(html).appendTo($("body")).slideDown(200).delay(options.close).slideUp(200, function() {
                $(this).remove();
            });
        }
    };
    $.extend($[pluginName], {
        version:1.0,
        TYPE_ERROR:0,
        TYPE_OK:1
    });
})(jQuery);
<|endoftext|>


<commit_before>class Database {
  constructor(file = null) {
    if (file != null) {
      const filebuffer = fs.readFileSync(file);
      this.sql = new SQL.Database(filebuffer);
    } else {
      throw new Error('No file provided', 'Database.class.js',7)
    }
  }

  exec(sqlstr) {
    const aux = this.sql.exec(sqlstr)[0];
    if(aux === undefined) throw new Error("Empty response",'Database.class.js',15)
    const res = [];
    for (var i = 0; i < aux.values.length; i++) {
      res[i] = {}
      for (var j = 0; j < aux.columns.length; j++) {
        res[i][aux.columns[j]] = aux.values[i][j];
      }
    }
    return res;
  }

  export(filepath) {
    const binArray = this.sql.export()
    fs.writeFile(filepath, binArray, (err) => {
      if (err) {
        throw err;
      }
    });
  }

  print(res) {
    let str = "|\t"
    for (var i = 0; i < res[0].columns.length; i++) {
      str += res[0].columns[i].toUpperCase() + "\t|\t"
    }
    for (var i = 0; i < res[0].values.length; i++) {
      str = "|\t";
      for (var j = 0; j < res[0].columns.length; j++) {
        str += res[0].values[i][j]
        str += "\t|\t"
      }
    }
  }

  // @Change
  lookup(date, account, amount, state) {
    const lastlookup = this.exec('SELECT lastlookup FROM Accounts WHERE name="'+account+'"')[0].lastlookup;
    if(moment(date, "YYYY-MM-DD").isBefore(moment(lastlookup,"YYYY-MM-DD"))){
      this.fullLookup(account);
    } else if (moment(date, "YYYY-MM-DD").isBefore(moment().format("YYYY-MM-DD"))){
      this.newlookup(lastlookup,account);
    } else {
      this.locallookup(account, amount, date, state);
    }
  }

  fullLookup(account) {
    // In Bank
    let sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET inBank = Coalesce(Accounts.baseAmount+(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name AND state='fa fa-check-circle' AND date<=:date),Accounts.baseAmount) WHERE name =:name2"
    );
    sqlstmt.run({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    // Today
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET today = Coalesce(Accounts.baseAmount+(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name AND date<=:date),Accounts.baseAmount) WHERE name =:name2"
    );
    sqlstmt.run({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    //Future
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET future = Coalesce(Accounts.baseAmount +(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name),Accounts.baseAmount) WHERE name =:name2"
    );
    sqlstmt.run({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    try{
      this.exec('UPDATE Accounts SET lastlookup='+moment().format('YYYY-MM-DD')+' WHERE name="'+account+'"');
    } catch (e) {}
    this.buildChartData(account);
  }

  newlookup(lastlookup, account) {
    // In Bank
    let sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET inBank = (Accounts.inBank+(SELECT SUM(amount) FROM OPERATION LEFT JOIN Accounts ON OPERATION.account_name=Accounts.name WHERE account_name =:name AND OPERATION.date<=:date AND OPERATION.date>Accounts.lastlookup AND state='fa fa-check-circle')) WHERE name =:name2"
    );
    sqlstmt.bind({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    // Today
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET today = (Accounts.today+(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name AND date<=:date)) WHERE name =:name2"
    );
    sqlstmt.bind({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    //Future
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET future = (Accounts.future +(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name)) WHERE name =:name2"
    );
    sqlstmt.bind({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    try {
      this.exec('UPDATE Accounts SET lastlookup='+moment().format('YYYY-MM-DD')+' WHERE name="'+account+'"');
    } catch(e){}
  }

  locallookup(account, operation, dateBTF, stateBTF){
      if (stateBTF === "fa fa-check-circle" && !moment(dateBTF,'YYYY-MM-DD').isAfter(moment())) {
        this.sql.run("UPDATE Accounts SET future = (Accounts.future+"+operation+"), inBank = (Accounts.inBank+"+operation+"), today = (Accounts.today+"+operation+"), future = (Accounts.future+"+operation+") WHERE name ='"+account+"'");
      } else if(moment(dateBTF,'YYYY-MM-DD').isAfter(moment())) {
        this.sql.run("UPDATE Accounts SET future = (Accounts.future+"+operation+") WHERE name ='"+account+"'");
      } else {
        this.sql.run("UPDATE Accounts SET today = (Accounts.today+"+operation+"), future = (Accounts.future+"+operation+") WHERE name ='"+account+"'");
      }
  }

  insertOperation(account, data, df) {
    if(account === null || account === undefined) throw new Error('No account provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("INSERT INTO OPERATION(date,state,beneficiary,category,label,amount,type,account_name) VALUES(:date,:state,:beneficiary,:category,:label,:amount,:type,:account_name)")
    sqlstmt.getAsObject({
      ':date' : moment(data[0],df).format('YYYY-MM-DD'),
      ':state' : data[1],
      ':beneficiary' : data[2],
      ':category' : data[3],
      ':label' : data[4],
      ':amount' : data[5],
      ':type' : data[6],
      ':account_name' : account
    });
    sqlstmt.free();
    this.locallookup(account,data[5], moment(data[0],df).format('YYYY-MM-DD'),data[1]);
    this.buildChartData(account);
  }

  insertRecurringOperation(account,data,df){
    //[amount,type,benef,cat,label,date,offset,timespan,time]
    if(account === null || account === undefined) throw new Error('No account provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("INSERT INTO Recurrings(amount,type,beneficiary,category,label,date,offset,timespan,times,account_name) VALUES(:amount,:type,:benef,:cat,:label,:date,:offset,:timespan,:time,:account_name)")
    sqlstmt.getAsObject({
      ':amount' : data[0],
      ':type' : data[1],
      ':benef' : data[2],
      ':cat' : data[3],
      ':label' : data[4],
      ':date' : moment(data[5],df).format('YYYY-MM-DD'),
      ':offset' : data[6],
      ':timespan' : data[7],
      ':time' : data[8],
      ':account_name' : account
    });
    sqlstmt.free();
  }

  editRecurringOperation(id,account,data,df){
    //[amount,type,benef,cat,label,date,offset,timespan,time]
    if(account === null || account === undefined) throw new Error('No account provided','Database.class.js',52)
    if(id === null || id === undefined) throw new Error('No id provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("UPDATE Recurrings SET amount=:amount,type=:type,beneficiary=:benef,category=:cat,label=:label,date=:date,offset=:offset,timespan=:timespan,times=:time,account_name=:account_name WHERE id="+id)
    sqlstmt.getAsObject({
      ':amount' : data[0],
      ':type' : data[1],
      ':benef' : data[2],
      ':cat' : data[3],
      ':label' : data[4],
      ':date' : moment(data[5],df).format('YYYY-MM-DD'),
      ':offset' : data[6],
      ':timespan' : data[7],
      ':time' : data[8],
      ':account_name' : account
    });
    sqlstmt.free();
  }

  editOperation(id, data, df){
    if(data[0] === null || data[0] === undefined) throw new Error('No account provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("UPDATE OPERATION SET date=:date,state=:state,beneficiary=:beneficiary,category=:category,label=:label,amount=:amount,type=:type,account_name=:account_name WHERE id="+id)
    sqlstmt.getAsObject({
      ':date' : moment(data[1],df).format('YYYY-MM-DD'),
      ':state' : data[2],
      ':beneficiary' : data[3],
      ':category' : data[4],
      ':label' : data[5],
      ':amount' : data[6],
      ':type' : data[7],
      ':account_name' : data[0]
    });
    sqlstmt.free();
    this.fullLookup(data[0]);
  }

  deleteOperation(id) {
    if( typeof id != "number") throw new Error('Invalid token')
    const account = this.exec('SELECT account_name from OPERATION where id='+id)[0].account_name
    this.sql.run('DELETE FROM OPERATION WHERE `id`='+id);
    this.fullLookup(account);
  }

  deleteRec(id){
    if( typeof id != "number") throw new Error('Invalid token')
    this.sql.run('DELETE FROM Recurrings WHERE `id`='+id);
  }

  launchPending(id){
    let resSQL = this.exec('SELECT * FROM Recurrings WHERE id='+id)[0]
    this.insertOperation(resSQL.account_name,[resSQL.date,"fa fa-circle-o",resSQL.beneficiary,resSQL.category,resSQL.label, resSQL.amount, resSQL.type],'YYYY-MM-DD')
    let newDate = moment(resSQL.date,'YYYY-MM-DD').add(resSQL.offset,resSQL.timespan).format('YYYY-MM-DD');
    resSQL.times = Number(resSQL.times)
    if (resSQL.times !== null) {
      if (resSQL.times === 1) {
        this.deleteRec(id);
      } else {
        const sqlstmt = this.sql.prepare("UPDATE Recurrings SET date=:date, times=:times WHERE id="+id)
        sqlstmt.getAsObject({
          ":date" : newDate,
          ":times": resSQL.times - 1
        });
        sqlstmt.free();
      }
    } else {
      const sqlstmt = this.sql.prepare("UPDATE Recurrings SET date=:date, WHERE id="+id)
      sqlstmt.getAsObject({
        ":date" : newDate
      });
      sqlstmt.free();
    }
  }
  updateTable(account,date,state,amount){
    const res = [];
    let sqlstr = "SELECT `id`,`state`,`date`,`type`,`beneficiary`,`category`,`label`,`amount` FROM OPERATION WHERE `account_name`=:account";
    if (state !== "*") {
      sqlstr += " AND `state`=:state";
    }
    if(amount === "plus"){
      sqlstr += " AND `amount`>=0";
    } else if(amount === "minus"){
      sqlstr += " AND `amount`<=0";
    }
    sqlstr += " AND `date`>=:date ORDER BY `date` DESC"
    const sqlstmt = this.sql.prepare(sqlstr);
    sqlstmt.bind({
      ':account' : account,
      ':date' : date,
      ':state' : state,
      ':amount' : amount
    })
    while(sqlstmt.step()){
      res.push(sqlstmt.get())
    }
    sqlstmt.free();
    return res;
  }

  addAccount(name, currency, baseAmount){
    const sqlstmt = this.sql.prepare("INSERT INTO Accounts VALUES (:name, :currency, :inBank, :today, :future,:amount,:date)");
    sqlstmt.getAsObject({
      ':name' :name,
      ':currency' : currency,
      ':inBank' : baseAmount,
      ':today' : baseAmount,
      ':future' : baseAmount,
      ':amount' : baseAmount,
      ':date' : moment().format('YYYY-MM-DD')
    });
    sqlstmt.free();
  }

  deleteAccount(name) {
    this.sql.run('DELETE FROM `Accounts` WHERE name="'+name+'"')
  }

  buildChartData(account){
    this.sql.run('DELETE FROM `ChronoBase` WHERE account="'+account+'"');
    const operations = this.exec('SELECT date, amount FROM OPERATION WHERE account_name="'+account+'" ORDER BY date');
    const baseAmount = this.exec('SELECT baseAmount FROM Accounts WHERE name="'+account+'"')[0].baseAmount;
    let currentAmount = baseAmount;
    let sqlstmt = this.sql.prepare("INSERT INTO ChronoBase(date,amount,account) VALUES (:date,:amount,:account)")
    for (var i = 0; i < operations.length; i++) {
      currentAmount += operations[i].amount;
      sqlstmt.run({
        ':date' : operations[i].date,
        ':amount' : currentAmount,
        ':account': account
      });
    }
    sqlstmt.free(); sqlstmt=null;
  }
}
<commit_msg>:wrench: Full database clean from account's deletion<commit_after>class Database {
  constructor(file = null) {
    if (file != null) {
      const filebuffer = fs.readFileSync(file);
      this.sql = new SQL.Database(filebuffer);
    } else {
      throw new Error('No file provided', 'Database.class.js',7)
    }
  }

  exec(sqlstr) {
    const aux = this.sql.exec(sqlstr)[0];
    if(aux === undefined) throw new Error("Empty response",'Database.class.js',15)
    const res = [];
    for (var i = 0; i < aux.values.length; i++) {
      res[i] = {}
      for (var j = 0; j < aux.columns.length; j++) {
        res[i][aux.columns[j]] = aux.values[i][j];
      }
    }
    return res;
  }

  export(filepath) {
    const binArray = this.sql.export()
    fs.writeFile(filepath, binArray, (err) => {
      if (err) {
        throw err;
      }
    });
  }

  print(res) {
    let str = "|\t"
    for (var i = 0; i < res[0].columns.length; i++) {
      str += res[0].columns[i].toUpperCase() + "\t|\t"
    }
    for (var i = 0; i < res[0].values.length; i++) {
      str = "|\t";
      for (var j = 0; j < res[0].columns.length; j++) {
        str += res[0].values[i][j]
        str += "\t|\t"
      }
    }
  }

  // @Change
  lookup(date, account, amount, state) {
    const lastlookup = this.exec('SELECT lastlookup FROM Accounts WHERE name="'+account+'"')[0].lastlookup;
    if(moment(date, "YYYY-MM-DD").isBefore(moment(lastlookup,"YYYY-MM-DD"))){
      this.fullLookup(account);
    } else if (moment(date, "YYYY-MM-DD").isBefore(moment().format("YYYY-MM-DD"))){
      this.newlookup(lastlookup,account);
    } else {
      this.locallookup(account, amount, date, state);
    }
  }

  fullLookup(account) {
    // In Bank
    let sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET inBank = Coalesce(Accounts.baseAmount+(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name AND state='fa fa-check-circle' AND date<=:date),Accounts.baseAmount) WHERE name =:name2"
    );
    sqlstmt.run({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    // Today
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET today = Coalesce(Accounts.baseAmount+(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name AND date<=:date),Accounts.baseAmount) WHERE name =:name2"
    );
    sqlstmt.run({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    //Future
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET future = Coalesce(Accounts.baseAmount +(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name),Accounts.baseAmount) WHERE name =:name2"
    );
    sqlstmt.run({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    try{
      this.exec('UPDATE Accounts SET lastlookup='+moment().format('YYYY-MM-DD')+' WHERE name="'+account+'"');
    } catch (e) {}
    this.buildChartData(account);
  }

  newlookup(lastlookup, account) {
    // In Bank
    let sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET inBank = (Accounts.inBank+(SELECT SUM(amount) FROM OPERATION LEFT JOIN Accounts ON OPERATION.account_name=Accounts.name WHERE account_name =:name AND OPERATION.date<=:date AND OPERATION.date>Accounts.lastlookup AND state='fa fa-check-circle')) WHERE name =:name2"
    );
    sqlstmt.bind({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    // Today
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET today = (Accounts.today+(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name AND date<=:date)) WHERE name =:name2"
    );
    sqlstmt.bind({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    //Future
    sqlstmt = this.sql.prepare(
      "UPDATE Accounts SET future = (Accounts.future +(SELECT SUM(amount) FROM OPERATION WHERE account_name =:name)) WHERE name =:name2"
    );
    sqlstmt.bind({
      ':name':account,
      ':date': moment().format('YYYY-MM-DD'),
      ':name2': account
    })
    sqlstmt.free(); sqlstmt = null;
    try {
      this.exec('UPDATE Accounts SET lastlookup='+moment().format('YYYY-MM-DD')+' WHERE name="'+account+'"');
    } catch(e){}
  }

  locallookup(account, operation, dateBTF, stateBTF){
      if (stateBTF === "fa fa-check-circle" && !moment(dateBTF,'YYYY-MM-DD').isAfter(moment())) {
        this.sql.run("UPDATE Accounts SET future = (Accounts.future+"+operation+"), inBank = (Accounts.inBank+"+operation+"), today = (Accounts.today+"+operation+"), future = (Accounts.future+"+operation+") WHERE name ='"+account+"'");
      } else if(moment(dateBTF,'YYYY-MM-DD').isAfter(moment())) {
        this.sql.run("UPDATE Accounts SET future = (Accounts.future+"+operation+") WHERE name ='"+account+"'");
      } else {
        this.sql.run("UPDATE Accounts SET today = (Accounts.today+"+operation+"), future = (Accounts.future+"+operation+") WHERE name ='"+account+"'");
      }
  }

  insertOperation(account, data, df) {
    if(account === null || account === undefined) throw new Error('No account provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("INSERT INTO OPERATION(date,state,beneficiary,category,label,amount,type,account_name) VALUES(:date,:state,:beneficiary,:category,:label,:amount,:type,:account_name)")
    sqlstmt.getAsObject({
      ':date' : moment(data[0],df).format('YYYY-MM-DD'),
      ':state' : data[1],
      ':beneficiary' : data[2],
      ':category' : data[3],
      ':label' : data[4],
      ':amount' : data[5],
      ':type' : data[6],
      ':account_name' : account
    });
    sqlstmt.free();
    this.locallookup(account,data[5], moment(data[0],df).format('YYYY-MM-DD'),data[1]);
    this.buildChartData(account);
  }

  insertRecurringOperation(account,data,df){
    //[amount,type,benef,cat,label,date,offset,timespan,time]
    if(account === null || account === undefined) throw new Error('No account provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("INSERT INTO Recurrings(amount,type,beneficiary,category,label,date,offset,timespan,times,account_name) VALUES(:amount,:type,:benef,:cat,:label,:date,:offset,:timespan,:time,:account_name)")
    sqlstmt.getAsObject({
      ':amount' : data[0],
      ':type' : data[1],
      ':benef' : data[2],
      ':cat' : data[3],
      ':label' : data[4],
      ':date' : moment(data[5],df).format('YYYY-MM-DD'),
      ':offset' : data[6],
      ':timespan' : data[7],
      ':time' : data[8],
      ':account_name' : account
    });
    sqlstmt.free();
  }

  editRecurringOperation(id,account,data,df){
    //[amount,type,benef,cat,label,date,offset,timespan,time]
    if(account === null || account === undefined) throw new Error('No account provided','Database.class.js',52)
    if(id === null || id === undefined) throw new Error('No id provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("UPDATE Recurrings SET amount=:amount,type=:type,beneficiary=:benef,category=:cat,label=:label,date=:date,offset=:offset,timespan=:timespan,times=:time,account_name=:account_name WHERE id="+id)
    sqlstmt.getAsObject({
      ':amount' : data[0],
      ':type' : data[1],
      ':benef' : data[2],
      ':cat' : data[3],
      ':label' : data[4],
      ':date' : moment(data[5],df).format('YYYY-MM-DD'),
      ':offset' : data[6],
      ':timespan' : data[7],
      ':time' : data[8],
      ':account_name' : account
    });
    sqlstmt.free();
  }

  editOperation(id, data, df){
    if(data[0] === null || data[0] === undefined) throw new Error('No account provided','Database.class.js',52)
    const sqlstmt = this.sql.prepare("UPDATE OPERATION SET date=:date,state=:state,beneficiary=:beneficiary,category=:category,label=:label,amount=:amount,type=:type,account_name=:account_name WHERE id="+id)
    sqlstmt.getAsObject({
      ':date' : moment(data[1],df).format('YYYY-MM-DD'),
      ':state' : data[2],
      ':beneficiary' : data[3],
      ':category' : data[4],
      ':label' : data[5],
      ':amount' : data[6],
      ':type' : data[7],
      ':account_name' : data[0]
    });
    sqlstmt.free();
    this.fullLookup(data[0]);
  }

  deleteOperation(id) {
    if( typeof id != "number") throw new Error('Invalid token')
    const account = this.exec('SELECT account_name from OPERATION where id='+id)[0].account_name
    this.sql.run('DELETE FROM OPERATION WHERE `id`='+id);
    this.fullLookup(account);
  }

  deleteRec(id){
    if( typeof id != "number") throw new Error('Invalid token')
    this.sql.run('DELETE FROM Recurrings WHERE `id`='+id);
  }

  launchPending(id){
    let resSQL = this.exec('SELECT * FROM Recurrings WHERE id='+id)[0]
    this.insertOperation(resSQL.account_name,[resSQL.date,"fa fa-circle-o",resSQL.beneficiary,resSQL.category,resSQL.label, resSQL.amount, resSQL.type],'YYYY-MM-DD')
    let newDate = moment(resSQL.date,'YYYY-MM-DD').add(resSQL.offset,resSQL.timespan).format('YYYY-MM-DD');
    resSQL.times = Number(resSQL.times)
    if (resSQL.times !== null) {
      if (resSQL.times === 1) {
        this.deleteRec(id);
      } else {
        const sqlstmt = this.sql.prepare("UPDATE Recurrings SET date=:date, times=:times WHERE id="+id)
        sqlstmt.getAsObject({
          ":date" : newDate,
          ":times": resSQL.times - 1
        });
        sqlstmt.free();
      }
    } else {
      const sqlstmt = this.sql.prepare("UPDATE Recurrings SET date=:date, WHERE id="+id)
      sqlstmt.getAsObject({
        ":date" : newDate
      });
      sqlstmt.free();
    }
  }
  updateTable(account,date,state,amount){
    const res = [];
    let sqlstr = "SELECT `id`,`state`,`date`,`type`,`beneficiary`,`category`,`label`,`amount` FROM OPERATION WHERE `account_name`=:account";
    if (state !== "*") {
      sqlstr += " AND `state`=:state";
    }
    if(amount === "plus"){
      sqlstr += " AND `amount`>=0";
    } else if(amount === "minus"){
      sqlstr += " AND `amount`<=0";
    }
    sqlstr += " AND `date`>=:date ORDER BY `date` DESC"
    const sqlstmt = this.sql.prepare(sqlstr);
    sqlstmt.bind({
      ':account' : account,
      ':date' : date,
      ':state' : state,
      ':amount' : amount
    })
    while(sqlstmt.step()){
      res.push(sqlstmt.get())
    }
    sqlstmt.free();
    return res;
  }

  addAccount(name, currency, baseAmount){
    const sqlstmt = this.sql.prepare("INSERT INTO Accounts VALUES (:name, :currency, :inBank, :today, :future,:amount,:date)");
    sqlstmt.getAsObject({
      ':name' :name,
      ':currency' : currency,
      ':inBank' : baseAmount,
      ':today' : baseAmount,
      ':future' : baseAmount,
      ':amount' : baseAmount,
      ':date' : moment().format('YYYY-MM-DD')
    });
    sqlstmt.free();
  }

  deleteAccount(name) {
    this.sql.run('DELETE FROM `Accounts` WHERE name="'+name+'"')
    this.sql.run('DELETE FROM `OPERATIONS` WHERE account_name="'+name+'"')
    this.sql.run('DELETE FROM `Recurrings` WHERE account_name="'+name+'"')
    this.sql.run('DELETE FROM `Chronobase` WHERE account="'+name+'"')
  }

  buildChartData(account){
    this.sql.run('DELETE FROM `ChronoBase` WHERE account="'+account+'"');
    const operations = this.exec('SELECT date, amount FROM OPERATION WHERE account_name="'+account+'" ORDER BY date');
    const baseAmount = this.exec('SELECT baseAmount FROM Accounts WHERE name="'+account+'"')[0].baseAmount;
    let currentAmount = baseAmount;
    let sqlstmt = this.sql.prepare("INSERT INTO ChronoBase(date,amount,account) VALUES (:date,:amount,:account)")
    for (var i = 0; i < operations.length; i++) {
      currentAmount += operations[i].amount;
      sqlstmt.run({
        ':date' : operations[i].date,
        ':amount' : currentAmount,
        ':account': account
      });
    }
    sqlstmt.free(); sqlstmt=null;
  }
}
<|endoftext|>


<commit_before>class EtherAddressLookup {

    constructor()
    {
        this.setDefaultExtensionSettings();
        this.init();
    }

    setDefaultExtensionSettings()
    {
        this.blHighlight = false;
        this.strBlockchainExplorer = "https://etherscan.io/address";

        this.intSettingsCount = 0;
        this.intSettingsTotalCount = 2;
    }

    //Gets extension settings and then converts addresses to links
    init()
    {
        //Get the highlight option for the user
        chrome.runtime.sendMessage({func: "highlight_option"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                this.blHighlight = (objResponse.resp == 1 ? true : false);
            }
            ++this.intSettingsCount;
        }.bind(this));

        //Get the blockchain explorer for the user
        chrome.runtime.sendMessage({func: "blockchain_explorer"}, function(objResponse) {
            this.strBlockchainExplorer = objResponse.resp;
            ++this.intSettingsCount;
        }.bind(this));

        //Update the DOM once all settings have been received...
        setTimeout(function() {
            if(this.intSettingsCount === this.intSettingsTotalCount) {
                this.convertAddressToLink();
            }
        }.bind(this), 1)
    }

    //Finds Ethereum addresses and converts to a link to a block explorer
    convertAddressToLink()
    {
        var arrWhitelistedTags = new Array("code", "span", "p", "td");
        var strRegex = /(?:^|\s)((?:0x)?[0-9a-fA-F]{40})(?:\s|$)/gi;

        //Get the whitelisted nodes
        for(var i=0; i<arrWhitelistedTags.length; i++) {
            var objNodes = document.getElementsByTagName(arrWhitelistedTags[i]);
            //Loop through the whitelisted content
            for(var x=0; x<objNodes.length; x++) {
                var strContent = objNodes[x].innerText;
                if( /((?:0x)?[0-9a-fA-F]{40})/gi.exec(strContent) !== null) {
                    objNodes[x].innerHTML = strContent.replace(
                        new RegExp(strRegex, "gi"),
                        '$1'
                    );
                }
            }
        }

        if(this.blHighlight) {
            this.addHighlightStyle();
        }
    }

    //Removes the highlight style from Ethereum addresses
    removeHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-no_highlight");
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
        }
        return false;
    }

    //Adds the highlight style
    addHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
            objEtherAddresses[i].classList.remove("ext-etheraddresslookup-link-no_highlight");
        }
        return false;
    }
}

window.addEventListener("load", function() {
    let objEtherAddressLookup = new EtherAddressLookup();
});

//Send message from the extension to here.
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        let objEtherAddressLookup = new EtherAddressLookup();
        if(typeof request.func !== "undefined") {
            if(typeof objEtherAddressLookup[request.func] == "function") {
                objEtherAddressLookup[request.func]();
                sendResponse({status: "ok"});
                return true;
            }
        }
        sendResponse({status: "fail"});
    }
);<commit_msg>Issue #6 - Added li to the whitelist<commit_after>class EtherAddressLookup {

    constructor()
    {
        this.setDefaultExtensionSettings();
        this.init();
    }

    setDefaultExtensionSettings()
    {
        this.blHighlight = false;
        this.strBlockchainExplorer = "https://etherscan.io/address";

        this.intSettingsCount = 0;
        this.intSettingsTotalCount = 2;
    }

    //Gets extension settings and then converts addresses to links
    init()
    {
        //Get the highlight option for the user
        chrome.runtime.sendMessage({func: "highlight_option"}, function(objResponse) {
            if(objResponse && objResponse.hasOwnProperty("resp")) {
                this.blHighlight = (objResponse.resp == 1 ? true : false);
            }
            ++this.intSettingsCount;
        }.bind(this));

        //Get the blockchain explorer for the user
        chrome.runtime.sendMessage({func: "blockchain_explorer"}, function(objResponse) {
            this.strBlockchainExplorer = objResponse.resp;
            ++this.intSettingsCount;
        }.bind(this));

        //Update the DOM once all settings have been received...
        setTimeout(function() {
            if(this.intSettingsCount === this.intSettingsTotalCount) {
                this.convertAddressToLink();
            }
        }.bind(this), 1)
    }

    //Finds Ethereum addresses and converts to a link to a block explorer
    convertAddressToLink()
    {
        var arrWhitelistedTags = new Array("code", "span", "p", "td", "li");
        var strRegex = /(?:^|\s)((?:0x)?[0-9a-fA-F]{40})(?:\s|$)/gi;

        //Get the whitelisted nodes
        for(var i=0; i<arrWhitelistedTags.length; i++) {
            var objNodes = document.getElementsByTagName(arrWhitelistedTags[i]);
            //Loop through the whitelisted content
            for(var x=0; x<objNodes.length; x++) {
                var strContent = objNodes[x].innerText;
                if( /((?:0x)?[0-9a-fA-F]{40})/gi.exec(strContent) !== null) {
                    objNodes[x].innerHTML = strContent.replace(
                        new RegExp(strRegex, "gi"),
                        '$1'
                    );
                }
            }
        }

        if(this.blHighlight) {
            this.addHighlightStyle();
        }
    }

    //Removes the highlight style from Ethereum addresses
    removeHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-no_highlight");
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
        }
        return false;
    }

    //Adds the highlight style
    addHighlightStyle()
    {
        var objEtherAddresses = document.getElementsByClassName("ext-etheraddresslookup-link");
        for (var i = 0; i < objEtherAddresses.length; i++) {
            objEtherAddresses[i].classList.add("ext-etheraddresslookup-link-highlight");
            objEtherAddresses[i].classList.remove("ext-etheraddresslookup-link-no_highlight");
        }
        return false;
    }
}

window.addEventListener("load", function() {
    let objEtherAddressLookup = new EtherAddressLookup();
});

//Send message from the extension to here.
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        let objEtherAddressLookup = new EtherAddressLookup();
        if(typeof request.func !== "undefined") {
            if(typeof objEtherAddressLookup[request.func] == "function") {
                objEtherAddressLookup[request.func]();
                sendResponse({status: "ok"});
                return true;
            }
        }
        sendResponse({status: "fail"});
    }
);<|endoftext|>


<commit_before>/**
 *

 * -ListenstoHELP_COMMANDand displays notifications.
 * - Provides interactive tutorial for first time users.
 *

 */
mindmaps.HelpController = function(eventBus, commandRegistry) {

	function setupInteractiveMode() {
		if (isTutorialDone() || mindmaps.DEBUG) {
			console.debug("skipping tutorial in debug mode");
			return;
		}

		var notifications = [];
		var interactiveMode = true;

		eventBus.once(mindmaps.Event.DOCUMENT_OPENED, function() {
			setTimeout(start, 1000);
		});
		var helpMain, helpRoot;

		function closeAllNotifications() {
			notifications.forEach(function(n) {
				n.close();
			});
		}

		function start() {
			helpMain = new mindmaps.Notification(
					"#toolbar",
					{
						position : "bottomMiddle",
						maxWidth : 550,
						title : "Welcome to mindmaps",
						content : "Hello there, it seems like you are new here! These bubbles "
								+ "will guide you through the app. Or they won't if you want to skip this tutorial and click here."
					});
			notifications.push(helpMain);
			helpMain.$().find("a.skip-tutorial").click(function() {
				interactiveMode = false;
				closeAllNotifications();
				tutorialDone();
			});
			setTimeout(theRoot, 2000);
		}

		function theRoot() {
			if (isTutorialDone())
				return;

			helpRoot = new mindmaps.Notification(
					".node-caption.root",
					{
						position : "bottomMiddle",
						closeButton : true,
						maxWidth : 350,
						title : "This is where you start - your main idea",
						content : "Double click the idea to change what it says. This will be the main topic of your mind map."
					});
			notifications.push(helpRoot);

			eventBus.once(mindmaps.Event.NODE_TEXT_CAPTION_CHANGED, function() {
				helpRoot.close();
				setTimeout(theNub, 900);
			});
		}

		function theNub() {
			if (isTutorialDone())
				return;

			var helpNub = new mindmaps.Notification(
					".node-caption.root",
					{
						position : "bottomMiddle",
						closeButton : true,
						maxWidth : 350,
						title : "Creating new ideas",
						content : "Now it's time to build your mind map.
 Move your mouse over the idea, click and then drag"
								+ " the red circle somewhere on the map. This is how you create a new branch."
					});
			notifications.push(helpNub);
			eventBus.once(mindmaps.Event.NODE_CREATED, function() {
				helpMain.close();
				helpNub.close();
				setTimeout(newNode, 900);
			});
		}

		function newNode() {
			if (isTutorialDone())
				return;

			var helpNewNode = new mindmaps.Notification(
					".node-container.root > .node-container:first",
					{
						position : "bottomMiddle",
						closeButton : true,
						maxWidth : 350,
						title : "Your first branch",
						content : "Great! This is easy, right? The red circle is your most important tool. Now, you can move your idea"
								+ " around by dragging it or double click to change the text again."
					});
			notifications.push(helpNewNode);
			setTimeout(inspector, 2000);

			eventBus.once(mindmaps.Event.NODE_MOVED, function() {
				helpNewNode.close();
				setTimeout(navigate, 0);
				setTimeout(toolbar, 15000);
				setTimeout(menu, 10000);
				setTimeout(tutorialDone, 20000);
			});
		}

		function navigate() {
			if (isTutorialDone())
				return;

			var helpNavigate = new mindmaps.Notification(
					".float-panel:has(#navigator)",
					{
						position : "bottomRight",
						closeButton : true,
						maxWidth : 350,
						expires : 10000,
						title : "Navigation",
						content : "You can click and drag the background of the map to move around. Use your mousewheel or slider over there to zoom in and out."
					});
			notifications.push(helpNavigate);
		}

		function inspector() {
			if (isTutorialDone())
				return;

			var helpInspector = new mindmaps.Notification(
					"#inspector",
					{
						position : "leftBottom",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "Don't like the colors?",
						content : "Use these controls to change the appearance of your ideas. "
								+ "Try clicking the icon in the upper right corner to minimize this panel."
					});
			notifications.push(helpInspector);
		}

		function toolbar() {
			if (isTutorialDone())
				return;

			var helpToolbar = new mindmaps.Notification(
					"#toolbar .buttons-left",
					{
						position : "bottomLeft",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "The tool bar",
						content : "Those buttons do what they say. You can use them or work with keyboard shortcuts. "
								+ "Hover over the buttons for the key combinations."
					});
			notifications.push(helpToolbar);
		}

		function menu() {
			if (isTutorialDone())
				return;

			var helpMenu = new mindmaps.Notification(
					"#toolbar .buttons-right",
					{
						position : "leftTop",
						closeButton : true,
						maxWidth : 350,
						title : "Save your work",
						content : "The button to the right opens a menu where you can save your mind map or start working "
								+ "on another one if you like."
					});
			notifications.push(helpMenu);
		}

		function isTutorialDone() {
			return mindmaps.LocalStorage.get("mindmaps.tutorial.done") == 1;
		}

		function tutorialDone() {
			mindmaps.LocalStorage.put("mindmaps.tutorial.done", 1);
		}

	}

	function setupHelpButton() {
		var command = commandRegistry.get(mindmaps.HelpCommand);
		command.setHandler(showHelp);

		var notifications = [];
		function showHelp() {
			// true if atleast one notifications is still on screen
			var displaying = notifications.some(function(noti) {
				return noti.isVisible();
			});

			// hide notifications if visible
			if (displaying) {
				notifications.forEach(function(noti) {
					noti.close();
				});
				notifications.length = 0;
				return;
			}

			// show notifications
			var helpRoot = new mindmaps.Notification(
					".node-caption.root",
					{
						position : "bottomLeft",
						closeButton : true,
						maxWidth : 350,
						title : "This is your main idea",
						content : "Double click an idea to edit its text. Move the mouse over "
								+ "an idea and drag the red circle to create a new idea."
					});

			var helpNavigator = new mindmaps.Notification(
					"#navigator",
					{
						position : "leftTop",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "This is the navigator",
						content : "Use this panel to get an overview of your map. "
								+ "You can navigate around by dragging the red rectangle or change the zoom by clicking on the magnifier buttons."
					});

			var helpInspector = new mindmaps.Notification(
					"#inspector",
					{
						position : "leftTop",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "This is the inspector",
						content : "Use these controls to change the appearance of your ideas. "
								+ "Try clicking the icon in the upper right corner to minimize this panel."
					});

			var helpToolbar = new mindmaps.Notification(
					"#toolbar .buttons-left",
					{
						position : "bottomLeft",
						closeButton : true,
						maxWidth : 350,
						title : "This is your toolbar",
						content : "Those buttons do what they say. You can use them or work with keyboard shortcuts. "
								+ "Hover over the buttons for the key combinations."
					});

			notifications.push(helpRoot, helpNavigator, helpInspector,
					helpToolbar);
		}
	}

	setupInteractiveMode();
	setupHelpButton();
};
<commit_msg>layout<commit_after>/**
 *

 * -ListenstoHELP_COMMANDand displays notifications.
 * - Provides interactive tutorial for first time users.
 *

 */
mindmaps.HelpController = function(eventBus, commandRegistry) {

	function setupInteractiveMode() {
		if (isTutorialDone()) {
			console.debug("skipping tutorial in debug mode");
			return;
		}

		var notifications = [];
		var interactiveMode = true;

		eventBus.once(mindmaps.Event.DOCUMENT_OPENED, function() {
			setTimeout(start, 1000);
		});
		var helpMain, helpRoot;

		function closeAllNotifications() {
			notifications.forEach(function(n) {
				n.close();
			});
		}

		function start() {
			helpMain = new mindmaps.Notification(
					"#toolbar",
					{
						position : "bottomMiddle",
						maxWidth : 550,
						title : "Welcome to mindmaps",
						content : "Hello there, it seems like you are new here! These bubbles "
								+ "will guide you through the app. Or they won't if you want to skip this tutorial and click here."
					});
			notifications.push(helpMain);
			helpMain.$().find("a.skip-tutorial").click(function() {
				interactiveMode = false;
				closeAllNotifications();
				tutorialDone();
			});
			setTimeout(theRoot, 2000);
		}

		function theRoot() {
			if (isTutorialDone())
				return;

			helpRoot = new mindmaps.Notification(
					".node-caption.root",
					{
						position : "bottomMiddle",
						closeButton : true,
						maxWidth : 350,
						title : "This is where you start - your main idea",
						content : "Double click the idea to change what it says. This will be the main topic of your mind map."
					});
			notifications.push(helpRoot);

			eventBus.once(mindmaps.Event.NODE_TEXT_CAPTION_CHANGED, function() {
				helpRoot.close();
				setTimeout(theNub, 900);
			});
		}

		function theNub() {
			if (isTutorialDone())
				return;

			var helpNub = new mindmaps.Notification(
					".node-caption.root",
					{
						position : "bottomMiddle",
						closeButton : true,
						maxWidth : 350,
						padding: 20,
						title : "Creating new ideas",
						content : "Now it's time to build your mind map.
 Move your mouse over the idea, click and then drag"
								+ " the red circle away from the root. This is how you create a new branch."
					});
			notifications.push(helpNub);
			eventBus.once(mindmaps.Event.NODE_CREATED, function() {
				helpMain.close();
				helpNub.close();
				setTimeout(newNode, 900);
			});
		}

		function newNode() {
			if (isTutorialDone())
				return;

			var helpNewNode = new mindmaps.Notification(
					".node-container.root > .node-container:first",
					{
						position : "bottomMiddle",
						closeButton : true,
						maxWidth : 350,
						title : "Your first branch",
						content : "Great! This is easy, right? The red circle is your most important tool. Now, you can move your idea"
								+ " around by dragging it or double click to change the text again."
					});
			notifications.push(helpNewNode);
			setTimeout(inspector, 2000);

			eventBus.once(mindmaps.Event.NODE_MOVED, function() {
				helpNewNode.close();
				setTimeout(navigate, 0);
				setTimeout(toolbar, 15000);
				setTimeout(menu, 10000);
				setTimeout(tutorialDone, 20000);
			});
		}

		function navigate() {
			if (isTutorialDone())
				return;

			var helpNavigate = new mindmaps.Notification(
					".float-panel:has(#navigator)",
					{
						position : "bottomRight",
						closeButton : true,
						maxWidth : 350,
						expires : 10000,
						title : "Navigation",
						content : "You can click and drag the background of the map to move around. Use your mousewheel or slider over there to zoom in and out."
					});
			notifications.push(helpNavigate);
		}

		function inspector() {
			if (isTutorialDone())
				return;

			var helpInspector = new mindmaps.Notification(
					"#inspector",
					{
						position : "leftBottom",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "Don't like the colors?",
						content : "Use these controls to change the appearance of your ideas. "
								+ "Try clicking the icon in the upper right corner to minimize this panel."
					});
			notifications.push(helpInspector);
		}

		function toolbar() {
			if (isTutorialDone())
				return;

			var helpToolbar = new mindmaps.Notification(
					"#toolbar .buttons-left",
					{
						position : "bottomLeft",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "The tool bar",
						content : "Those buttons do what they say. You can use them or work with keyboard shortcuts. "
								+ "Hover over the buttons for the key combinations."
					});
			notifications.push(helpToolbar);
		}

		function menu() {
			if (isTutorialDone())
				return;

			var helpMenu = new mindmaps.Notification(
					"#toolbar .buttons-right",
					{
						position : "leftTop",
						closeButton : true,
						maxWidth : 350,
						title : "Save your work",
						content : "The button to the right opens a menu where you can save your mind map or start working "
								+ "on another one if you like."
					});
			notifications.push(helpMenu);
		}

		function isTutorialDone() {
			return mindmaps.LocalStorage.get("mindmaps.tutorial.done") == 1;
		}

		function tutorialDone() {
			mindmaps.LocalStorage.put("mindmaps.tutorial.done", 1);
		}

	}

	function setupHelpButton() {
		var command = commandRegistry.get(mindmaps.HelpCommand);
		command.setHandler(showHelp);

		var notifications = [];
		function showHelp() {
			// true if atleast one notifications is still on screen
			var displaying = notifications.some(function(noti) {
				return noti.isVisible();
			});

			// hide notifications if visible
			if (displaying) {
				notifications.forEach(function(noti) {
					noti.close();
				});
				notifications.length = 0;
				return;
			}

			// show notifications
			var helpRoot = new mindmaps.Notification(
					".node-caption.root",
					{
						position : "bottomLeft",
						closeButton : true,
						maxWidth : 350,
						title : "This is your main idea",
						content : "Double click an idea to edit its text. Move the mouse over "
								+ "an idea and drag the red circle to create a new idea."
					});

			var helpNavigator = new mindmaps.Notification(
					"#navigator",
					{
						position : "leftTop",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "This is the navigator",
						content : "Use this panel to get an overview of your map. "
								+ "You can navigate around by dragging the red rectangle or change the zoom by clicking on the magnifier buttons."
					});

			var helpInspector = new mindmaps.Notification(
					"#inspector",
					{
						position : "leftTop",
						closeButton : true,
						maxWidth : 350,
						padding : 20,
						title : "This is the inspector",
						content : "Use these controls to change the appearance of your ideas. "
								+ "Try clicking the icon in the upper right corner to minimize this panel."
					});

			var helpToolbar = new mindmaps.Notification(
					"#toolbar .buttons-left",
					{
						position : "bottomLeft",
						closeButton : true,
						maxWidth : 350,
						title : "This is your toolbar",
						content : "Those buttons do what they say. You can use them or work with keyboard shortcuts. "
								+ "Hover over the buttons for the key combinations."
					});

			notifications.push(helpRoot, helpNavigator, helpInspector,
					helpToolbar);
		}
	}

	setupInteractiveMode();
	setupHelpButton();
};
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');
var parseAuthor = require('parse-author');
var askName = require('inquirer-npm-name');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);

  },
  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage
    };

    if (_.isObject(this.pkg.author)) {
      this.props.authorName = this.pkg.author.name;
      this.props.authorEmail = this.pkg.author.email;
      this.props.authorUrl = this.pkg.author.url;
    } else if (_.isString(this.pkg.author)) {
      var info = parseAuthor(this.pkg.author);
      this.props.authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }
  },
  prompting: {

    askFor: function () {
      var done = this.async();

      this.option('name', {
         type: String,
         required: false,
         desc: 'Project name'
       });

      // Have Yeoman greet the user.
      this.log(yosay(
        'Welcome to the sweet ' + chalk.red('Starthackit') + ' generator!'
      ));

      var prompts = [{
        type: 'confirm',
        name: 'someOption',
        message: 'Would you like to enable this option?',
        default: true
      }];

      this.prompt(prompts, function (props) {
        this.props = props;
        // To access props later use this.props.someOption;

        done();
      }.bind(this));
    },
    askForModuleName: function () {
      if (this.options.name) {
        this.props.name = _.kebabCase(this.options.name);
        return;
      }
      var done = this.async();
      this.props = {};
      askName({
        name: 'name',
        message: 'Project Name',
        default: path.basename(process.cwd()),
        filter: _.kebabCase,
        validate: function (str) {
          return str.length > 0;
        }
      }, this, function (name) {
        this.props.name = name;
        done();
      }.bind(this));
    }
  },

  writing: {
    app: function () {
      console.log("destinationPath: ", this.destinationPath());
      this.sourceRoot(path.join(__dirname, '../../../'));
      console.log("sourceRoot: ", this.sourceRoot());
      //this.mkdir("server");
      this.directory('server');
      //this.mkdir("client");
      this.directory('client');
      this.directory('deploy');
      this.fs.copy(
        this.templatePath('.travis.yml'),
        this.destinationPath('.travis.yml')
      );
      this.sourceRoot(path.join(__dirname, 'template'));
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
    },

    projectfiles: function () {

    }
  },

  install: function () {
    this.installDependencies();
  }
});
<commit_msg>do not use bower for the yo generator<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var path = require('path');
var _ = require('lodash');
var parseAuthor = require('parse-author');
var askName = require('inquirer-npm-name');

module.exports = yeoman.generators.Base.extend({
  constructor: function () {
    yeoman.generators.Base.apply(this, arguments);

  },
  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage
    };

    if (_.isObject(this.pkg.author)) {
      this.props.authorName = this.pkg.author.name;
      this.props.authorEmail = this.pkg.author.email;
      this.props.authorUrl = this.pkg.author.url;
    } else if (_.isString(this.pkg.author)) {
      var info = parseAuthor(this.pkg.author);
      this.props.authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }
  },
  prompting: {

    askFor: function () {
      var done = this.async();

      this.option('name', {
         type: String,
         required: false,
         desc: 'Project name'
       });

      // Have Yeoman greet the user.
      this.log(yosay(
        'Welcome to the sweet ' + chalk.red('Starthackit') + ' generator!'
      ));

      var prompts = [{
        type: 'confirm',
        name: 'someOption',
        message: 'Would you like to enable this option?',
        default: true
      }];

      this.prompt(prompts, function (props) {
        this.props = props;
        // To access props later use this.props.someOption;

        done();
      }.bind(this));
    },
    askForModuleName: function () {
      if (this.options.name) {
        this.props.name = _.kebabCase(this.options.name);
        return;
      }
      var done = this.async();
      this.props = {};
      askName({
        name: 'name',
        message: 'Project Name',
        default: path.basename(process.cwd()),
        filter: _.kebabCase,
        validate: function (str) {
          return str.length > 0;
        }
      }, this, function (name) {
        this.props.name = name;
        done();
      }.bind(this));
    }
  },

  writing: {
    app: function () {
      //console.log("destinationPath: ", this.destinationPath());
      this.sourceRoot(path.join(__dirname, '../../../'));
      //console.log("sourceRoot: ", this.sourceRoot());
      this.directory('server');
      this.directory('client');
      this.directory('deploy');
      this.fs.copy(
        this.templatePath('.travis.yml'),
        this.destinationPath('.travis.yml')
      );
      this.sourceRoot(path.join(__dirname, 'template'));
      this.fs.copy(
        this.templatePath('_package.json'),
        this.destinationPath('package.json')
      );
    },

    projectfiles: function () {

    }
  },

  install: function () {
    this.installDependencies({bower: false});
  }
});
<|endoftext|>


<commit_before>RoomConference.prototype = Object.create(THREE.Object3D.prototype);
RoomConference.prototype.constructor = RoomConference;

	function RoomConference(scene){
		THREE.Object3D.call(this);
		var room = this;
		scene.room = this;

		this.photoSphere = new PhotoSphere(scene, 'images/rooms/PANO_Vergaderruimte.jpg');

		this.textLights = new TextLights(scene, {});

		THREE.ImageUtils.loadTexture('images/monuta/monuta1.png', undefined, function(texture){
			room.whiteboard = new DetailImage(scene, texture, {
				scale: 60,
				degree: 120,
				verticalDegree: -10,
				radius: 10 * SCALE,
			});
            room.whiteboard.mesh.rotation.z = 0.15;
            room.whiteboard.mesh.rotation.y = -0.5;
		});

        THREE.ImageUtils.loadTexture('images/monuta/monuta2.png', undefined, function(texture){
            room.whiteboard = new DetailImage(scene, texture, {
                scale: 67,
                degree: 180,
                verticalDegree: -44,
                radius: 14 * SCALE
            });
            room.whiteboard.mesh.rotation.z = -0.12;
            room.whiteboard.mesh.rotation.x = -1;
        });

        THREE.ImageUtils.loadTexture('images/monuta/monuta_logo_rood.png', undefined, function(texture){
            room.whiteboard = new DetailImage(scene, texture, {
                scale: 5,
                degree: 180,
                verticalDegree: -10,
                radius: 10 * SCALE
            });
            //room.whiteboard.mesh.position.y += 40;
            room.whiteboard.mesh.rotation.z = -0.04;
//            room.whiteboard.mesh.rotation.y = -0.5;
//            room.whiteboard.mesh.rotation.x = -1;
        });

        this.navigationArrowToArrival = new NavigationArrow(scene, {
			degree: -53,
			verticalOffset: 0,
			onFocus: function(){
				// remove the room
				room.remove();
				// Start a new room
				new RoomBack(scene);
				scene.rotation.y += 250;
			}
		});

		this.remove = function(){
			this.photoSphere.remove();

			this.textLights.remove();

			this.navigationArrowToArrival.remove();

			if (room.vandijk1 != undefined){
				room.vandijk1.remove();
			}
			if (room.vandijk2 != undefined){
				room.vandijk2.remove();
			}
			if (room.vandijk3 != undefined){
				room.vandijk3.remove();
			}
			if (room.whiteboard != undefined){
				room.whiteboard.remove();
			}

			// part
			if (room.part2 != undefined){
				room.part2.remove();
			}

			// remove self
			scene.removeRoom(this);
		}
	}<commit_msg>Uitvaartkostenmeter toegevoegd aan Monuta kamer<commit_after>RoomConference.prototype = Object.create(THREE.Object3D.prototype);
RoomConference.prototype.constructor = RoomConference;

	function RoomConference(scene){
		THREE.Object3D.call(this);
		var room = this;
		scene.room = this;

		this.photoSphere = new PhotoSphere(scene, 'images/rooms/PANO_Vergaderruimte.jpg');

		this.textLights = new TextLights(scene, {});

		THREE.ImageUtils.loadTexture('images/monuta/monuta1.png', undefined, function(texture){
			room.whiteboard = new DetailImage(scene, texture, {
				scale: 60,
				degree: 120,
				verticalDegree: -10,
				radius: 10 * SCALE,
			});
            room.whiteboard.mesh.rotation.z = 0.15;
            room.whiteboard.mesh.rotation.y = -0.5;
		});

        THREE.ImageUtils.loadTexture('images/monuta/monuta2.png', undefined, function(texture){
            room.whiteboard = new DetailImage(scene, texture, {
                scale: 67,
                degree: 180,
                verticalDegree: -44,
                radius: 14 * SCALE
            });
            room.whiteboard.mesh.rotation.z = -0.12;
            room.whiteboard.mesh.rotation.x = -1;
        });

        THREE.ImageUtils.loadTexture('images/monuta/uitvaartkostenmeter.jpg', undefined, function(texture){
            room.whiteboard = new DetailImage(scene, texture, {
                scale: 60,
                degree: 246,
                verticalDegree: -4,
                radius: 10 * SCALE
            });
            room.whiteboard.mesh.rotation.z = -0.20;
            room.whiteboard.mesh.rotation.x = 0;
        });

        THREE.ImageUtils.loadTexture('images/monuta/monuta_logo_rood.png', undefined, function(texture){
            room.whiteboard = new DetailImage(scene, texture, {
                scale: 5,
                degree: 180,
                verticalDegree: -10,
                radius: 10 * SCALE
            });
            //room.whiteboard.mesh.position.y += 40;
            room.whiteboard.mesh.rotation.z = -0.04;
//            room.whiteboard.mesh.rotation.y = -0.5;
//            room.whiteboard.mesh.rotation.x = -1;
        });

        this.navigationArrowToArrival = new NavigationArrow(scene, {
			degree: -53,
			verticalOffset: 0,
			onFocus: function(){
				// remove the room
				room.remove();
				// Start a new room
				new RoomBack(scene);
				scene.rotation.y += 250;
			}
		});

		this.remove = function(){
			this.photoSphere.remove();

			this.textLights.remove();

			this.navigationArrowToArrival.remove();

			if (room.vandijk1 != undefined){
				room.vandijk1.remove();
			}
			if (room.vandijk2 != undefined){
				room.vandijk2.remove();
			}
			if (room.vandijk3 != undefined){
				room.vandijk3.remove();
			}
			if (room.whiteboard != undefined){
				room.whiteboard.remove();
			}

			// part
			if (room.part2 != undefined){
				room.part2.remove();
			}

			// remove self
			scene.removeRoom(this);
		}
	}<|endoftext|>


<commit_before>'use strict';

import dom from './dom';
import { EventEmitterProxy } from 'metal-events';

/**
 * DomEventEmitterProxy utility. It extends `EventEmitterProxy` to also accept
 * dom elements as origin emitters.
 * @extends {EventEmitterProxy}
 */
class DomEventEmitterProxy extends EventEmitterProxy {
	/**
	 * Adds the given listener for the given event.
	 * @param {string} event.
	 * @param {!function()} listener
	 * @return {!EventHandle} The listened event's handle.
	 * @protected
	 * @override
	 */
	addListener_(event, listener) {
		if (this.originEmitter_.addEventListener) {
			if (event.startsWith('delegate:')) {
				var index = event.indexOf(':', 9);
				var eventName = event.substring(9, index);
				var selector = event.substring(index + 1);
				return dom.delegate(this.originEmitter_, eventName, selector, listener);
			} else {
				return dom.on(this.originEmitter_, event, listener);
			}
		} else {
			return super.addListener_(event, listener);
		}
	}

	/**
	 * Checks if the given event is supported by the origin element.
	 * @param {string} event
	 * @protected
	 */
	isSupportedDomEvent_(event) {
		if (!this.originEmitter_ || !this.originEmitter_.addEventListener) {
			return true;
		}
		return (event.startsWith('delegate:') && event.indexOf(':', 9) !== -1) ||
			dom.supportsEvent(this.originEmitter_, event);
	}

	/**
	 * Checks if the given event should be proxied.
	 * @param {string} event
	 * @return {boolean}
	 * @protected
	 * @override
	 */
	shouldProxyEvent_(event) {
		return super.shouldProxyEvent_(event) && this.isSupportedDomEvent_(event);
	}
}

export default DomEventEmitterProxy;
<commit_msg>Stops using startsWith - Fixes #1<commit_after>'use strict';

import dom from './dom';
import { EventEmitterProxy } from 'metal-events';

/**
 * DomEventEmitterProxy utility. It extends `EventEmitterProxy` to also accept
 * dom elements as origin emitters.
 * @extends {EventEmitterProxy}
 */
class DomEventEmitterProxy extends EventEmitterProxy {
	/**
	 * Adds the given listener for the given event.
	 * @param {string} event.
	 * @param {!function()} listener
	 * @return {!EventHandle} The listened event's handle.
	 * @protected
	 * @override
	 */
	addListener_(event, listener) {
		if (this.originEmitter_.addEventListener) {
			if (this.isDelegateEvent_(event)) {
				var index = event.indexOf(':', 9);
				var eventName = event.substring(9, index);
				var selector = event.substring(index + 1);
				return dom.delegate(this.originEmitter_, eventName, selector, listener);
			} else {
				return dom.on(this.originEmitter_, event, listener);
			}
		} else {
			return super.addListener_(event, listener);
		}
	}

	/**
	 * Checks if the given event is of the delegate type.
	 * @param {string} event
	 * @return {boolean}
	 * @protected
	 */
	isDelegateEvent_(event) {
		return event.substr(0, 9) === 'delegate:';
	}

	/**
	 * Checks if the given event is supported by the origin element.
	 * @param {string} event
	 * @protected
	 */
	isSupportedDomEvent_(event) {
		if (!this.originEmitter_ || !this.originEmitter_.addEventListener) {
			return true;
		}
		return (this.isDelegateEvent_(event) && event.indexOf(':', 9) !== -1) ||
			dom.supportsEvent(this.originEmitter_, event);
	}

	/**
	 * Checks if the given event should be proxied.
	 * @param {string} event
	 * @return {boolean}
	 * @protected
	 * @override
	 */
	shouldProxyEvent_(event) {
		return super.shouldProxyEvent_(event) && this.isSupportedDomEvent_(event);
	}
}

export default DomEventEmitterProxy;
<|endoftext|>