<commit_before>/*

	jQuery Tags Input Plugin 1.3.3

	Copyright (c) 2011 XOXCO, Inc

	Documentation for this plugin lives here:
	http://xoxco.com/clickable/jquery-tags-input

	Licensed under the MIT license:
	http://www.opensource.org/licenses/mit-license.php

	ben@xoxco.com

*/

(function($) {

	var delimiter = new Array();
	var tags_callbacks = new Array();
	$.fn.doAutosize = function(o){
	    var minWidth = $(this).data('minwidth'),
	        maxWidth = $(this).data('maxwidth'),
	        val = '',
	        input = $(this),
	        testSubject = $('#'+$(this).data('tester_id'));

	    if (val === (val = input.val())) {return;}

	    // Enter new content into testSubject
	    var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
	    testSubject.html(escaped);
	    // Calculate new width + whether to change
	    var testerWidth = testSubject.width(),
	        newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
	        currentWidth = input.width(),
	        isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
	                             || (newWidth > minWidth && newWidth < maxWidth);

	    // Animate width
	    if (isValidWidthChange) {
	        input.width(newWidth);
	    }

  };
  $.fn.resetAutosize = function(options){
    // alert(JSON.stringify(options));
    var minWidth =  $(this).data('minwidth') || options.minInputWidth || $(this).width(),
        maxWidth = $(this).data('maxwidth') || options.maxInputWidth || ($(this).closest('.tagsinput').width() - options.inputPadding),
        val = '',
        input = $(this),
        testSubject = $('<tester/>').css({
            position: 'absolute',
            top: -9999,
            left: -9999,
            width: 'auto',
            fontSize: input.css('fontSize'),
            fontFamily: input.css('fontFamily'),
            fontWeight: input.css('fontWeight'),
            letterSpacing: input.css('letterSpacing'),
            whiteSpace: 'nowrap'
        }),
        testerId = $(this).attr('id')+'_autosize_tester';
    if(! $('#'+testerId).length > 0){
      testSubject.attr('id', testerId);
      testSubject.appendTo('body');
    }

    input.data('minwidth', minWidth);
    input.data('maxwidth', maxWidth);
    input.data('tester_id', testerId);
    input.css('width', minWidth);
  };

	$.fn.addTag = function(value,options) {
			options = jQuery.extend({focus:false,callback:true},options);
			this.each(function() {
				var id = $(this).attr('id');

				var tagslist = $(this).val().split(delimiter[id]);
				if (tagslist[0] == '') {
					tagslist = new Array();
				}

				value = jQuery.trim(value);

				if (options.unique) {
					var skipTag = $(this).tagExist(value);
					if(skipTag == true) {
					    //Marks fake input as not_valid to let styling it
    				    $('#'+id+'_tag').addClass('not_valid');
    				}
				} else {
					var skipTag = false;
				}

				if (value !='' && skipTag != true) {
                    $('').addClass('tag').append(
                        $('').text(value).append('  '),
                        $('', {
                            href  : '#',
                            title : 'Removing tag',
                            text  : 'x'
                        }).click(function () {
                            return $('#' + id).removeTag(escape(value));
                        })
                    ).insertBefore('#' + id + '_addTag');

					tagslist.push(value);

					$('#'+id+'_tag').val('');
					if (options.focus) {
						$('#'+id+'_tag').focus();
					} else {
						$('#'+id+'_tag').blur();
					}

					$.fn.tagsInput.updateTagsField(this,tagslist);

					if (options.callback && tags_callbacks[id] && tags_callbacks[id]['onAddTag']) {
						var f = tags_callbacks[id]['onAddTag'];
						f.call(this, value);
					}
					if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
					{
						var i = tagslist.length;
						var f = tags_callbacks[id]['onChange'];
						f.call(this, $(this), tagslist[i-1]);
					}
				}

			});

			return false;
		};

	$.fn.removeTag = function(value) {
			value = unescape(value);
			this.each(function() {
				var id = $(this).attr('id');

				var old = $(this).val().split(delimiter[id]);

				$('#'+id+'_tagsinput .tag').remove();
				str = '';
				for (i=0; i< old.length; i++) {
					if (old[i]!=value) {
						str = str + delimiter[id] +old[i];
					}
				}

				$.fn.tagsInput.importTags(this,str);

				if (tags_callbacks[id] && tags_callbacks[id]['onRemoveTag']) {
					var f = tags_callbacks[id]['onRemoveTag'];
					f.call(this, value);
				}
			});

			return false;
		};

	$.fn.tagExist = function(val) {
		var id = $(this).attr('id');
		var tagslist = $(this).val().split(delimiter[id]);
		return (jQuery.inArray(val, tagslist) >= 0); //true when tag exists, false when not
	};

	// clear all existing tags and import new ones from a string
	$.fn.importTags = function(str) {
                id = $(this).attr('id');
		$('#'+id+'_tagsinput .tag').remove();
		$.fn.tagsInput.importTags(this,str);
	}

	$.fn.tagsInput = function(options) {
    var settings = jQuery.extend({
      interactive:true,
      defaultText:'add a tag',
      minChars:0,
      width:'300px',
      height:'100px',
      autocomplete: {selectFirst: false },
      'hide':true,
      'delimiter':',',
      'unique':true,
      removeWithBackspace:true,
      placeholderColor:'#666666',
      autosize: true,
      comfortZone: 20,
      inputPadding: 6*2
    },options);

		this.each(function() {
			if (settings.hide) {
				$(this).hide();
			}
			var id = $(this).attr('id');
			if (!id || delimiter[$(this).attr('id')]) {
				id = $(this).attr('id', 'tags' + new Date().getTime()).attr('id');
			}

			var data = jQuery.extend({
				pid:id,
				real_input: '#'+id,
				holder: '#'+id+'_tagsinput',
				input_wrapper: '#'+id+'_addTag',
				fake_input: '#'+id+'_tag'
			},settings);

			delimiter[id] = data.delimiter;

			if (settings.onAddTag || settings.onRemoveTag || settings.onChange) {
				tags_callbacks[id] = new Array();
				tags_callbacks[id]['onAddTag'] = settings.onAddTag;
				tags_callbacks[id]['onRemoveTag'] = settings.onRemoveTag;
				tags_callbacks[id]['onChange'] = settings.onChange;
			}

			var markup = '

';

			if (settings.interactive) {
				markup = markup + '<input id="'+id+'_tag" value="" data-default="'+settings.defaultText+'" />';
			}

			markup = markup + '

';

			$(markup).insertAfter(this);

			$(data.holder).css('width',settings.width);
			$(data.holder).css('min-height',settings.height);
			$(data.holder).css('height','100%');

			if ($(data.real_input).val()!='') {
				$.fn.tagsInput.importTags($(data.real_input),$(data.real_input).val());
			}
			if (settings.interactive) {
				$(data.fake_input).val($(data.fake_input).attr('data-default'));
				$(data.fake_input).css('color',settings.placeholderColor);
		        $(data.fake_input).resetAutosize(settings);

				$(data.holder).bind('click',data,function(event) {
					$(event.data.fake_input).focus();
				});

				$(data.fake_input).bind('focus',data,function(event) {
					if ($(event.data.fake_input).val()==$(event.data.fake_input).attr('data-default')) {
						$(event.data.fake_input).val('');
					}
					$(event.data.fake_input).css('color','#000000');
				});

				if (settings.autocomplete_url != undefined) {
					autocomplete_options = {source: settings.autocomplete_url};
					for (attrname in settings.autocomplete) {
						autocomplete_options[attrname] = settings.autocomplete[attrname];
					}

					if (jQuery.Autocompleter !== undefined) {
						$(data.fake_input).autocomplete(autocomplete_options);
                        $(data.fake_input).bind('result',data,function(event,data,formatted) {
							if (data) {
								$('#'+id).addTag(data[0] + "",{focus:true,unique:(settings.unique)});
							}
					  	});
					} else if (jQuery.ui.autocomplete !== undefined) {
						$(data.fake_input).autocomplete(autocomplete_options);
						$(data.fake_input).bind('autocompleteselect',data,function(event,ui) {
							$(event.data.real_input).addTag(ui.item.value,{focus:true,unique:(settings.unique)});
							return false;
						});
					}

				} else {
						// if a user tabs out of the field, create a new tag
						// this is only available if autocomplete is not used.
						$(data.fake_input).bind('blur',data,function(event) {
							var d = $(this).attr('data-default');
							if ($(event.data.fake_input).val()!='' && $(event.data.fake_input).val()!=d) {
								if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
									$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
							} else {
								$(event.data.fake_input).val($(event.data.fake_input).attr('data-default'));
								$(event.data.fake_input).css('color',settings.placeholderColor);
							}
							return false;
						});

				}
				// if user types a comma, create a new tag
				$(data.fake_input).bind('keypress',data,function(event) {
					if (event.which==event.data.delimiter.charCodeAt(0) || event.which==13 ) {
					    event.preventDefault();
						if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
							$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
					  	$(event.data.fake_input).resetAutosize(settings);
						return false;
					} else if (event.data.autosize) {
			            $(event.data.fake_input).doAutosize(settings);

          			}
				});
				//Delete last tag on backspace
				data.removeWithBackspace && $(data.fake_input).bind('keydown', function(event)
				{
					if(event.keyCode == 8 && $(this).val() == '')
					{
						 event.preventDefault();
						 var last_tag = $(this).closest('.tagsinput').find('.tag:last').text();
						 var id = $(this).attr('id').replace(/_tag$/, '');
						 last_tag = last_tag.replace(/[\s]+x$/, '');
						 $('#' + id).removeTag(escape(last_tag));
						 $(this).trigger('focus');
					}
				});
				$(data.fake_input).blur();

				//Removes the not_valid class when user changes the value of the fake input
				if(data.unique) {
				    $(data.fake_input).keydown(function(event){
				        if(event.keyCode == 8 || String.fromCharCode(event.which).match(/\w+|[áéíóúÁÉÍÓÚñÑ,/]+/)) {
				            $(this).removeClass('not_valid');
				        }
				    });
				}
			} // if settings.interactive
		});

		return this;

	};

	$.fn.tagsInput.updateTagsField = function(obj,tagslist) {
		var id = $(obj).attr('id');
		$(obj).val(tagslist.join(delimiter[id]));
	};

	$.fn.tagsInput.importTags = function(obj,val) {
		$(obj).val('');
		var id = $(obj).attr('id');
		var tags = val.split(delimiter[id]);
		for (i=0; i<tags.length; i++) {
			$(obj).addTag(tags[i],{focus:false,callback:false});
		}
		if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
		{
			var f = tags_callbacks[id]['onChange'];
			f.call(obj, obj, tags[i]);
		}
	};

})(jQuery);
<commit_msg>Allow input of comma seperated list<commit_after>/*

	jQuery Tags Input Plugin 1.3.3

	Copyright (c) 2011 XOXCO, Inc

	Documentation for this plugin lives here:
	http://xoxco.com/clickable/jquery-tags-input

	Licensed under the MIT license:
	http://www.opensource.org/licenses/mit-license.php

	ben@xoxco.com

*/

(function($) {

	var delimiter = new Array();
	var tags_callbacks = new Array();
	$.fn.doAutosize = function(o){
	    var minWidth = $(this).data('minwidth'),
	        maxWidth = $(this).data('maxwidth'),
	        val = '',
	        input = $(this),
	        testSubject = $('#'+$(this).data('tester_id'));

	    if (val === (val = input.val())) {return;}

	    // Enter new content into testSubject
	    var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
	    testSubject.html(escaped);
	    // Calculate new width + whether to change
	    var testerWidth = testSubject.width(),
	        newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
	        currentWidth = input.width(),
	        isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
	                             || (newWidth > minWidth && newWidth < maxWidth);

	    // Animate width
	    if (isValidWidthChange) {
	        input.width(newWidth);
	    }

  };
  $.fn.resetAutosize = function(options){
    // alert(JSON.stringify(options));
    var minWidth =  $(this).data('minwidth') || options.minInputWidth || $(this).width(),
        maxWidth = $(this).data('maxwidth') || options.maxInputWidth || ($(this).closest('.tagsinput').width() - options.inputPadding),
        val = '',
        input = $(this),
        testSubject = $('<tester/>').css({
            position: 'absolute',
            top: -9999,
            left: -9999,
            width: 'auto',
            fontSize: input.css('fontSize'),
            fontFamily: input.css('fontFamily'),
            fontWeight: input.css('fontWeight'),
            letterSpacing: input.css('letterSpacing'),
            whiteSpace: 'nowrap'
        }),
        testerId = $(this).attr('id')+'_autosize_tester';
    if(! $('#'+testerId).length > 0){
      testSubject.attr('id', testerId);
      testSubject.appendTo('body');
    }

    input.data('minwidth', minWidth);
    input.data('maxwidth', maxWidth);
    input.data('tester_id', testerId);
    input.css('width', minWidth);
  };

	$.fn.addTag = function(value,options) {
		if (value.indexOf(',') >= 0) {
            jQuery.each(value.split(','), function (i, val) {
                $('#id_users').addTag(val.trim());
            });
        } else {
            options = jQuery.extend({focus:false,callback:true},options);
			this.each(function() {
				var id = $(this).attr('id');

				var tagslist = $(this).val().split(delimiter[id]);
				if (tagslist[0] == '') {
					tagslist = new Array();
				}

				value = jQuery.trim(value);

				if (options.unique) {
					var skipTag = $(this).tagExist(value);
					if(skipTag == true) {
					    //Marks fake input as not_valid to let styling it
    				    $('#'+id+'_tag').addClass('not_valid');
    				}
				} else {
					var skipTag = false;
				}

				if (value !='' && skipTag != true) {
                    $('').addClass('tag').append(
                        $('').text(value).append('  '),
                        $('', {
                            href  : '#',
                            title : 'Removing tag',
                            text  : 'x'
                        }).click(function () {
                            return $('#' + id).removeTag(escape(value));
                        })
                    ).insertBefore('#' + id + '_addTag');

					tagslist.push(value);

					$('#'+id+'_tag').val('');
					if (options.focus) {
						$('#'+id+'_tag').focus();
					} else {
						$('#'+id+'_tag').blur();
					}

					$.fn.tagsInput.updateTagsField(this,tagslist);

					if (options.callback && tags_callbacks[id] && tags_callbacks[id]['onAddTag']) {
						var f = tags_callbacks[id]['onAddTag'];
						f.call(this, value);
					}
					if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
					{
						var i = tagslist.length;
						var f = tags_callbacks[id]['onChange'];
						f.call(this, $(this), tagslist[i-1]);
					}
				}

			});

			return false;
        }
		};

	$.fn.removeTag = function(value) {
			value = unescape(value);
			this.each(function() {
				var id = $(this).attr('id');

				var old = $(this).val().split(delimiter[id]);

				$('#'+id+'_tagsinput .tag').remove();
				str = '';
				for (i=0; i< old.length; i++) {
					if (old[i]!=value) {
						str = str + delimiter[id] +old[i];
					}
				}

				$.fn.tagsInput.importTags(this,str);

				if (tags_callbacks[id] && tags_callbacks[id]['onRemoveTag']) {
					var f = tags_callbacks[id]['onRemoveTag'];
					f.call(this, value);
				}
			});

			return false;
		};

	$.fn.tagExist = function(val) {
		var id = $(this).attr('id');
		var tagslist = $(this).val().split(delimiter[id]);
		return (jQuery.inArray(val, tagslist) >= 0); //true when tag exists, false when not
	};

	// clear all existing tags and import new ones from a string
	$.fn.importTags = function(str) {
                id = $(this).attr('id');
		$('#'+id+'_tagsinput .tag').remove();
		$.fn.tagsInput.importTags(this,str);
	}

	$.fn.tagsInput = function(options) {
    var settings = jQuery.extend({
      interactive:true,
      defaultText:'add a tag',
      minChars:0,
      width:'300px',
      height:'100px',
      autocomplete: {selectFirst: false },
      'hide':true,
      'delimiter':',',
      'unique':true,
      removeWithBackspace:true,
      placeholderColor:'#666666',
      autosize: true,
      comfortZone: 20,
      inputPadding: 6*2
    },options);

		this.each(function() {
			if (settings.hide) {
				$(this).hide();
			}
			var id = $(this).attr('id');
			if (!id || delimiter[$(this).attr('id')]) {
				id = $(this).attr('id', 'tags' + new Date().getTime()).attr('id');
			}

			var data = jQuery.extend({
				pid:id,
				real_input: '#'+id,
				holder: '#'+id+'_tagsinput',
				input_wrapper: '#'+id+'_addTag',
				fake_input: '#'+id+'_tag'
			},settings);

			delimiter[id] = data.delimiter;

			if (settings.onAddTag || settings.onRemoveTag || settings.onChange) {
				tags_callbacks[id] = new Array();
				tags_callbacks[id]['onAddTag'] = settings.onAddTag;
				tags_callbacks[id]['onRemoveTag'] = settings.onRemoveTag;
				tags_callbacks[id]['onChange'] = settings.onChange;
			}

			var markup = '

';

			if (settings.interactive) {
				markup = markup + '<input id="'+id+'_tag" value="" data-default="'+settings.defaultText+'" />';
			}

			markup = markup + '

';

			$(markup).insertAfter(this);

			$(data.holder).css('width',settings.width);
			$(data.holder).css('min-height',settings.height);
			$(data.holder).css('height','100%');

			if ($(data.real_input).val()!='') {
				$.fn.tagsInput.importTags($(data.real_input),$(data.real_input).val());
			}
			if (settings.interactive) {
				$(data.fake_input).val($(data.fake_input).attr('data-default'));
				$(data.fake_input).css('color',settings.placeholderColor);
		        $(data.fake_input).resetAutosize(settings);

				$(data.holder).bind('click',data,function(event) {
					$(event.data.fake_input).focus();
				});

				$(data.fake_input).bind('focus',data,function(event) {
					if ($(event.data.fake_input).val()==$(event.data.fake_input).attr('data-default')) {
						$(event.data.fake_input).val('');
					}
					$(event.data.fake_input).css('color','#000000');
				});

				if (settings.autocomplete_url != undefined) {
					autocomplete_options = {source: settings.autocomplete_url};
					for (attrname in settings.autocomplete) {
						autocomplete_options[attrname] = settings.autocomplete[attrname];
					}

					if (jQuery.Autocompleter !== undefined) {
						$(data.fake_input).autocomplete(autocomplete_options);
                        $(data.fake_input).bind('result',data,function(event,data,formatted) {
							if (data) {
								$('#'+id).addTag(data[0] + "",{focus:true,unique:(settings.unique)});
							}
					  	});
					} else if (jQuery.ui.autocomplete !== undefined) {
						$(data.fake_input).autocomplete(autocomplete_options);
						$(data.fake_input).bind('autocompleteselect',data,function(event,ui) {
							$(event.data.real_input).addTag(ui.item.value,{focus:true,unique:(settings.unique)});
							return false;
						});
					}

				} else {
						// if a user tabs out of the field, create a new tag
						// this is only available if autocomplete is not used.
						$(data.fake_input).bind('blur',data,function(event) {
							var d = $(this).attr('data-default');
							if ($(event.data.fake_input).val()!='' && $(event.data.fake_input).val()!=d) {
								if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
									$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
							} else {
								$(event.data.fake_input).val($(event.data.fake_input).attr('data-default'));
								$(event.data.fake_input).css('color',settings.placeholderColor);
							}
							return false;
						});

				}
				// if user types a comma, create a new tag
				$(data.fake_input).bind('keypress',data,function(event) {
					if (event.which==event.data.delimiter.charCodeAt(0) || event.which==13 ) {
					    event.preventDefault();
						if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) )
							$(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)});
					  	$(event.data.fake_input).resetAutosize(settings);
						return false;
					} else if (event.data.autosize) {
			            $(event.data.fake_input).doAutosize(settings);

          			}
				});
				//Delete last tag on backspace
				data.removeWithBackspace && $(data.fake_input).bind('keydown', function(event)
				{
					if(event.keyCode == 8 && $(this).val() == '')
					{
						 event.preventDefault();
						 var last_tag = $(this).closest('.tagsinput').find('.tag:last').text();
						 var id = $(this).attr('id').replace(/_tag$/, '');
						 last_tag = last_tag.replace(/[\s]+x$/, '');
						 $('#' + id).removeTag(escape(last_tag));
						 $(this).trigger('focus');
					}
				});
				$(data.fake_input).blur();

				//Removes the not_valid class when user changes the value of the fake input
				if(data.unique) {
				    $(data.fake_input).keydown(function(event){
				        if(event.keyCode == 8 || String.fromCharCode(event.which).match(/\w+|[áéíóúÁÉÍÓÚñÑ,/]+/)) {
				            $(this).removeClass('not_valid');
				        }
				    });
				}
			} // if settings.interactive
		});

		return this;

	};

	$.fn.tagsInput.updateTagsField = function(obj,tagslist) {
		var id = $(obj).attr('id');
		$(obj).val(tagslist.join(delimiter[id]));
	};

	$.fn.tagsInput.importTags = function(obj,val) {
		$(obj).val('');
		var id = $(obj).attr('id');
		var tags = val.split(delimiter[id]);
		for (i=0; i<tags.length; i++) {
			$(obj).addTag(tags[i],{focus:false,callback:false});
		}
		if(tags_callbacks[id] && tags_callbacks[id]['onChange'])
		{
			var f = tags_callbacks[id]['onChange'];
			f.call(obj, obj, tags[i]);
		}
	};

})(jQuery);
<|endoftext|>


<commit_before>Crafty.c("ViewportFollow", {
    mapBoundary: null,
    viewportPadding: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
    },

    init: function() {
    },

    ViewportFollow: function(padding, mapBoundary) {
        if(padding != null) {
            if(typeof(padding) === "object") {
                this.viewportPadding.top = padding.top != null ? padding.top : 0;
                this.viewportPadding.right = padding.right != null ? padding.right : 0;
                this.viewportPadding.bottom = padding.bottom != null ? padding.bottom : 0;
                this.viewportPadding.left = padding.left != null ? padding.left : 0;
            }
            else if(typeof(padding) === "number") {
                this.viewportPadding.top = padding;
                this.viewportPadding.right = padding;
                this.viewportPadding.bottom = padding;
                this.viewportPadding.left = padding;
            }
        }

        if(mapBoundary == null) {
            this.mapBoundary = new Crafty.polygon([0,0], [Crafty.DOM.window.width, 0], [Crafty.DOM.window.width, Crafty.DOM.window.height], [0, Crafty.DOM.window.height]);
        }
        else {
            this.mapBoundary = mapBoundary;
        }

        this.bind('Moved', function(from) {
            var vpx_min = this._x - this.viewportPadding.left,
                vpx_max = this._x - (Crafty.viewport.width - this.viewportPadding.right) + this._w;

            var vpy_min = this._y - this.viewportPadding.top,
                vpy_max = this._y - (Crafty.viewport.height - this.viewportPadding.bottom) + this._h;

            if(this.mapBoundary.containsPoint(vpx_min, this._y) && this.mapBoundary.containsPoint(vpx_max + Crafty.viewport.width, this._y)) {
                if(this._x + Crafty.viewport.x <= this.viewportPadding.left)
                    Crafty.viewport.x = -(this._x - this.viewportPadding.left);
                else if(this._x + Crafty.viewport.x >= (Crafty.viewport.width - this.viewportPadding.right) - this._w)
                    Crafty.viewport.x = -(this._x + this._w - (Crafty.viewport.width - this.viewportPadding.right));
            }

            if(this.mapBoundary.containsPoint(this._x, vpy_min) && this.mapBoundary.containsPoint(this._x, vpy_max + Crafty.viewport.height)) {
                if(this._y + Crafty.viewport.y <= this.viewportPadding.top)
                    Crafty.viewport.y = -(this._y - this.viewportPadding.top);
                else if(this._y + Crafty.viewport.y >= (Crafty.viewport.height - this.viewportPadding.bottom) - this._h)
                    Crafty.viewport.y = -(this._y + this._h - (Crafty.viewport.height - this.viewportPadding.bottom));
            }
        });

        return this;
    }
});<commit_msg>* Added support for reseating the viewport back at a valid position should it exceed the applicable location. * Commented the source<commit_after>/**
 * Crafty-bmViewport
 * Enhances and improves upon the Crafty.viewport through components.
 *  - ViewportFollow
 *      + Forces the viewport to follow the bound entity. This component offers adjustable
 *        "boundary padding" prior to the viewport moving and configurable map boundary via.
 *        Crafty.polygon. If no map boundary is set, the default is to use
 *        Crafty.DOM.window.width and Craft.DOM.window.height; however.
 *
 * Author:  Austin Hanson
 * Date:    5/28/2012
 */

/**@
 * #ViewportFollow
 * @category Graphics
 * @requires Multiway, Fourway, Twoway
 * Forces the viewport to follow the bound entity. This component offers adjustable
 * "boundary padding" prior to the viewport moving and configurable map boundary via.
 * Crafty.polygon. If no map boundary is set, the default is to use
 * Crafty.DOM.window.width and Craft.DOM.window.height; however.
 */
Crafty.c("ViewportFollow", {
    _lockedAtX: false,
    _lockedAtY: false,
    mapBoundary: null,
    viewportPadding: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
    },

    init: function() { },

    /**@
     * #.viewportFollow
     * @comp bmViewport
     * @sign public this .viewportFollow(Integer padding)
     * @sign public this .viewportFollow(Integer padding, Crafty.polygon mapBoundary)
     * @param padding - Distance from the map boundary from which the viewport will
     * begin following the entity.
     * @param mapBoundary - Polygon defining the map boundary
     *
     * @sign public this .viewportFollow(Map padding)
     * @sign public this .viewportFollow(Map padding, Crafty.polygon mapBoundary)
     * @param padding - Map of {top, right, bottom, left} paddings
     * @param mapBoundary - Polygon defining the map boundary
     *
     * @example
     * ~~~
     * Crafty.e("2D, DOM, Color, Fourway, ViewportFollow")
     *      .attr({ x: 32, y: 32, h: 32, w: 32, z:2 })
     *      .color('blue')
     *      .fourway(4)
     *      .ViewportFollow(32, new Crafty.polygon(
     *          [0,0], [MAP_WIDTH, 0],
     *          [MAP_WIDTH, MAP_HEIGHT], [0, MAP_HEIGHT]));
     * ~~~
     */
    viewportFollow: function(padding, mapBoundary) {
        if(padding != null) {
            if(typeof(padding) === "object") {
                this.viewportPadding.top = padding.top != null ? padding.top : 0;
                this.viewportPadding.right = padding.right != null ? padding.right : 0;
                this.viewportPadding.bottom = padding.bottom != null ? padding.bottom : 0;
                this.viewportPadding.left = padding.left != null ? padding.left : 0;
            }
            else if(typeof(padding) === "number") {
                this.viewportPadding.top = padding;
                this.viewportPadding.right = padding;
                this.viewportPadding.bottom = padding;
                this.viewportPadding.left = padding;
            }
        }

        if(mapBoundary == null) {
            this.mapBoundary = new Crafty.polygon([0,0], [Crafty.DOM.window.width, 0], [Crafty.DOM.window.width, Crafty.DOM.window.height], [0, Crafty.DOM.window.height]);
        }
        else {
            this.mapBoundary = mapBoundary;
        }

        this.bind('Moved', function(from) {
            var vpx_min = this._x - this.viewportPadding.left,
                vpx_max = this._x - (Crafty.viewport.width - this.viewportPadding.right) + this._w;

            var vpy_min = this._y - this.viewportPadding.top,
                vpy_max = this._y - (Crafty.viewport.height - this.viewportPadding.bottom) + this._h;

            // Is the viewport within x adjusting range?
            if(this.mapBoundary.containsPoint(vpx_min, this._y) && this.mapBoundary.containsPoint(vpx_max + Crafty.viewport.width, this._y)) {
                // Flag that we're not locked in the y direction
                this._lockedAtX = false;

                if(this._x + Crafty.viewport.x <= this.viewportPadding.left)
                    Crafty.viewport.x = -(this._x - this.viewportPadding.left);
                else if(this._x + Crafty.viewport.x >= (Crafty.viewport.width - this.viewportPadding.right) - this._w)
                    Crafty.viewport.x = -(this._x + this._w - (Crafty.viewport.width - this.viewportPadding.right));
            }
            // No, attempt to reseat the viewport at a valid position
            else if(!this._lockedAtX && !this.mapBoundary.containsPoint(vpx_min, this._y)) {
                // Flag that we're locked on a boundary
                this._lockedAtX = true;

                var vpx = vpx_min;
                for(; !this.mapBoundary.containsPoint(vpx, this._y) && vpx < this._x; vpx++) { }
                Crafty.viewport.x = -vpx;
            }
            else if(!this._lockedAtX && !this.mapBoundary.containsPoint(vpx_max, this._y)) {
                // Flag that we're locked on a boundary
                this._lockedAtX = true;

                var vpx = vpx_max;
                for(; !this.mapBoundary.containsPoint(vpx, this._y) && vpx > (this._x + this._w); vpx--) { }
                Crafty.viewport.x = -vpx;
            }

            // Is the viewport within y adjusting range?
            if(this.mapBoundary.containsPoint(this._x, vpy_min) && this.mapBoundary.containsPoint(this._x, vpy_max + Crafty.viewport.height)) {
                // Flag that we're not locked in the y direction
                this._lockedAtY = false;

                if(this._y + Crafty.viewport.y <= this.viewportPadding.top)
                    Crafty.viewport.y = -(this._y - this.viewportPadding.top);
                else if(this._y + Crafty.viewport.y >= (Crafty.viewport.height - this.viewportPadding.bottom) - this._h)
                    Crafty.viewport.y = -(this._y + this._h - (Crafty.viewport.height - this.viewportPadding.bottom));
            }
            // No, attempt to reseat the viewport at a valid position
            else if(!this._lockedAtY && !this.mapBoundary.containsPoint(this._x, vpy_min)) {
                // Flag that we're locked on a boundary
                this._lockedAtY = true;

                var vpy = vpy_min;
                for(; !this.mapBoundary.containsPoint(this._x, vpy) && vpy < this._y; vpy++) { }
                Crafty.viewport.y = -vpy;
            }
            else if(!this._lockedAtY && !this.mapBoundary.containsPoint(this._x, vpy_max)) {
                // Flag that we're locked on a boundary
                this._lockedAtY = true;

                var vpy = vpy_max;
                for(; !this.mapBoundary.containsPoint(this._x, vpy) && vpy > (this._y + this._h); vpy--) { }
                Crafty.viewport.y = -vpy;
            }
        });

        return this;
    }
});<|endoftext|>


<commit_before>import React from 'react';
import Column from '../ui/components/column';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me } from '../../initial_state';
import { fetchFollowRequests } from '../../actions/accounts';
import { List as ImmutableList } from 'immutable';
import { Link } from 'react-router-dom';
import NavigationBar from '../compose/components/navigation_bar';

const messages = defineMessages({
  home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
  notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
  public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
  settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
  community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
  direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' },
  preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
  follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
  favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
  blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
  domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' },
  mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
  pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' },
  lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
  discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' },
  personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' },
  security: { id: 'navigation_bar.security', defaultMessage: 'Security' },
});

const mapStateToProps = state => ({
  myAccount: state.getIn(['accounts', me]),
  unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
});

const mapDispatchToProps = dispatch => ({
  fetchFollowRequests: () => dispatch(fetchFollowRequests()),
});

const badgeDisplay = (number, limit) => {
  if (number === 0) {
    return undefined;
  } else if (limit && number >= limit) {
    return `${limit}+`;
  } else {
    return number;
  }
};

@connect(mapStateToProps, mapDispatchToProps)
@injectIntl
export default class GettingStarted extends ImmutablePureComponent {

  static propTypes = {
    intl: PropTypes.object.isRequired,
    myAccount: ImmutablePropTypes.map.isRequired,
    columns: ImmutablePropTypes.list,
    multiColumn: PropTypes.bool,
    fetchFollowRequests: PropTypes.func.isRequired,
    unreadFollowRequests: PropTypes.number,
    unreadNotifications: PropTypes.number,
  };

  componentDidMount () {
    const { myAccount, fetchFollowRequests } = this.props;

    if (myAccount.get('locked')) {
      fetchFollowRequests();
    }
  }

  render () {
    const { intl, myAccount, multiColumn, unreadFollowRequests } = this.props;

    const navItems = [];
    let i = 1;
    let height = 0;

    navItems.push(<ColumnLink key='10' icon='vcard-o' text='#自己紹介' to='/timelines/tag/自己紹介' />);
    navItems.push(<ColumnLink key='11' icon='book' text='#作品紹介' to='/timelines/tag/作品紹介' />);

    if (multiColumn) {
      navItems.push(
        <ColumnSubheading key={i++} text={intl.formatMessage(messages.discover)} />,
        <ColumnLink key={i++} icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />,
        <ColumnLink key={i++} icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />,
        <ColumnSubheading key={i++} text={intl.formatMessage(messages.personal)} />
      );

      height += 34*2 + 48*2;
    }

    navItems.push(
      <ColumnLink key={i++} icon='envelope' text={intl.formatMessage(messages.direct)} to='/timelines/direct' />,
      <ColumnLink key={i++} icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />,
      <ColumnLink key={i++} icon='bars' text={intl.formatMessage(messages.lists)} to='/lists' />
    );

    height += 48*3;

    if (myAccount.get('locked')) {
      navItems.push(<ColumnLink key={i++} icon='users' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />);
      height += 48;
    }

    if (!multiColumn) {
      navItems.push(
        <ColumnSubheading key={i++} text={intl.formatMessage(messages.settings_subheading)} />,
        <ColumnLink key={i++} icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />,
        <ColumnLink key={i++} icon='lock' text={intl.formatMessage(messages.security)} href='/auth/edit' />
      );

      height += 34 + 48*2;
    }

    return (
      <Column>
        {multiColumn &&

            <button>

              <FormattedMessage id='getting_started.heading' defaultMessage='Getting started' />
            </button>

}

          {!multiColumn && <NavigationBar account={myAccount} />}
          {navItems}

        {!multiColumn &&
}

            {multiColumn &&
<Link to='/keyboard-shortcuts'><FormattedMessage id='navigation_bar.keyboard_shortcuts' defaultMessage='Hotkeys' /></Link> ·
}

<FormattedMessage id='navigation_bar.info' defaultMessage='About this instance' /> ·

<FormattedMessage id='getting_started.terms' defaultMessage='Terms of service' /> ·

<FormattedMessage id='getting_started.documentation' defaultMessage='Documentation' /> ·

<FormattedMessage id='navigation_bar.logout' defaultMessage='Logout' />

            <FormattedMessage
              id='getting_started.open_source_notice'
              defaultMessage='Mastodon is open source software. You can contribute or report issues on GitHub at {github}.'
              values={{ github: tootsuite/mastodon }}
            />

      </Column>
    );
  }

}
<commit_msg>Fix display of the getting started column<commit_after>import React from 'react';
import Column from '../ui/components/column';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me } from '../../initial_state';
import { fetchFollowRequests } from '../../actions/accounts';
import { List as ImmutableList } from 'immutable';
import { Link } from 'react-router-dom';
import NavigationBar from '../compose/components/navigation_bar';

const messages = defineMessages({
  home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
  notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
  public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
  settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
  community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
  direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' },
  preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
  follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
  favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
  blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
  domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' },
  mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
  pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' },
  lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
  discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' },
  personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' },
  security: { id: 'navigation_bar.security', defaultMessage: 'Security' },
});

const mapStateToProps = state => ({
  myAccount: state.getIn(['accounts', me]),
  unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
});

const mapDispatchToProps = dispatch => ({
  fetchFollowRequests: () => dispatch(fetchFollowRequests()),
});

const badgeDisplay = (number, limit) => {
  if (number === 0) {
    return undefined;
  } else if (limit && number >= limit) {
    return `${limit}+`;
  } else {
    return number;
  }
};

@connect(mapStateToProps, mapDispatchToProps)
@injectIntl
export default class GettingStarted extends ImmutablePureComponent {

  static propTypes = {
    intl: PropTypes.object.isRequired,
    myAccount: ImmutablePropTypes.map.isRequired,
    columns: ImmutablePropTypes.list,
    multiColumn: PropTypes.bool,
    fetchFollowRequests: PropTypes.func.isRequired,
    unreadFollowRequests: PropTypes.number,
    unreadNotifications: PropTypes.number,
  };

  componentDidMount () {
    const { myAccount, fetchFollowRequests } = this.props;

    if (myAccount.get('locked')) {
      fetchFollowRequests();
    }
  }

  render () {
    const { intl, myAccount, multiColumn, unreadFollowRequests } = this.props;

    const navItems = [];
    let i = 1;
    let height = 0;

    if (multiColumn) {
      navItems.push(
        <ColumnSubheading key={i++} text={intl.formatMessage(messages.discover)} />,
        <ColumnLink key={i++} icon='vcard-o' text='#自己紹介' to='/timelines/tag/自己紹介' />,
        <ColumnLink key={i++} icon='book' text='#作品紹介' to='/timelines/tag/作品紹介' />,
        <ColumnLink key={i++} icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />,
        <ColumnLink key={i++} icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />,
        <ColumnSubheading key={i++} text={intl.formatMessage(messages.personal)} />
      );

      height += 34*2 + 48*4;
    }

    navItems.push(
      <ColumnLink key={i++} icon='envelope' text={intl.formatMessage(messages.direct)} to='/timelines/direct' />,
      <ColumnLink key={i++} icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />,
      <ColumnLink key={i++} icon='bars' text={intl.formatMessage(messages.lists)} to='/lists' />
    );

    height += 48*3;

    if (myAccount.get('locked')) {
      navItems.push(<ColumnLink key={i++} icon='users' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />);
      height += 48;
    }

    if (!multiColumn) {
      navItems.push(
        <ColumnSubheading key={i++} text={intl.formatMessage(messages.settings_subheading)} />,
        <ColumnLink key={i++} icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />,
        <ColumnLink key={i++} icon='lock' text={intl.formatMessage(messages.security)} href='/auth/edit' />
      );

      height += 34 + 48*2;
    }

    return (
      <Column>
        {multiColumn &&

            <button>

              <FormattedMessage id='getting_started.heading' defaultMessage='Getting started' />
            </button>

}

          {!multiColumn && <NavigationBar account={myAccount} />}
          {navItems}

        {!multiColumn &&
}

            {multiColumn &&
<Link to='/keyboard-shortcuts'><FormattedMessage id='navigation_bar.keyboard_shortcuts' defaultMessage='Hotkeys' /></Link> ·
}

<FormattedMessage id='navigation_bar.info' defaultMessage='About this instance' /> ·

<FormattedMessage id='getting_started.terms' defaultMessage='Terms of service' /> ·

<FormattedMessage id='getting_started.documentation' defaultMessage='Documentation' /> ·

<FormattedMessage id='navigation_bar.logout' defaultMessage='Logout' />

            <FormattedMessage
              id='getting_started.open_source_notice'
              defaultMessage='Mastodon is open source software. You can contribute or report issues on GitHub at {github}.'
              values={{ github: tootsuite/mastodon }}
            />

      </Column>
    );
  }

}
<|endoftext|>


<commit_before>const refresh = require('./lib/refresh');
const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const Message = require('./../orm/Message')
const commands = require('./commands');
const request = require('request-promise-native');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection', (err) => {
    console.log("UNHANDLED REJECTION AT " + err.stack);
    if (err.toString().includes('Request to use token, but token was unavailable to the client'))
        process.exit();//restart
});
process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack));
bot.on('message', (message) => {
    /**
     * if locked, reject everything except dm
     */

    new Message({
        messageID: message.id,
        channel: message.channel.id
    }).save();
    if (message.author.bot) return;
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            //  if (message.channel.guild)
            return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else if (message.isMentioned(bot.user)) {
        /**remove mentions and then get params */
        let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift.trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", async function (member) {
    var user = member.user;
    if (member.guild.id === "184536578654339072") {
        user.send("Welcome to the Revive Network");
        if (! await refresh(user)) {
            const ma = await bot.channels.get("317859245309689856").send(user.toString() + "Type `accept` to continue. You will be kicked if you don't accept within 1 minute");
            await member.addRole(bot.guilds.get("184536578654339072").roles.get("317854639431221248"));
            // Await !vote messages
            const filter = (message) => {
                if (message.author.id === member.user.id)
                    if (message.content.toLowerCase().includes("accept") && message.member.roles.get("317854639431221248")) {
                        message.member.removeRole("317854639431221248");
                        return message;
                    }
            }
            // Errors: ['time'] treats ending because of the time limit as an error
            bot.channels.get("317859245309689856").awaitMessages(filter, { max: 1, time: 60000, errors: ['time'] })
                .then(collected => {
                    ma.delete();
                    if (collected.size < 1) {
                        member.kick();
                    }
                    return collected;
                })
                .then(collected => collected.map((m) => m.delete()));
        }
    }
});/**
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    process.exit();//force restart
});*/

bot.on('ready', () => {
    console.log("ReviveBot Ready");
});
bot.on("guildMemberUpdate", async function (member, newMem) {
    let user = member.user;
    if (member.guild && (member.guild.id === "184536578654339072")) {
        let oldMem = member;
        if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return;
        if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return;
        if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) {
            await request('http://revive-bot-discord.revive.systems/v0/discord/reverse_link/' + user.id);
        }
    }
});
<commit_msg>ignore bot accounts<commit_after>const refresh = require('./lib/refresh');
const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const Message = require('./../orm/Message')
const commands = require('./commands');
const request = require('request-promise-native');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection', (err) => {
    console.log("UNHANDLED REJECTION AT " + err.stack);
    if (err.toString().includes('Request to use token, but token was unavailable to the client'))
        process.exit();//restart
});
process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack));
bot.on('message', (message) => {
    /**
     * if locked, reject everything except dm
     */

    new Message({
        messageID: message.id,
        channel: message.channel.id
    }).save();
    if (message.author.bot) return;
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            //  if (message.channel.guild)
            return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else if (message.isMentioned(bot.user)) {
        /**remove mentions and then get params */
        let params = message.cleancontent.trim().replace(bot.user.toString(), "").trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift.trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", async function (member) {
    var user = member.user;
    if (member.guild.id === "184536578654339072") {
        if (member.user.bot) return console.log(member.user.tag + " is a bot who joined " + member.guild.name)
        user.send("Welcome to the Revive Network");
        if (! await refresh(user)) {
            const ma = await bot.channels.get("317859245309689856").send(user.toString() + "Type `accept` to continue. You will be kicked if you don't accept within 1 minute");
            await member.addRole(bot.guilds.get("184536578654339072").roles.get("317854639431221248"));
            // Await !vote messages
            const filter = (message) => {
                if (message.author.id === member.user.id)
                    if (message.content.toLowerCase().includes("accept") && message.member.roles.get("317854639431221248")) {
                        message.member.removeRole("317854639431221248");
                        return message;
                    }
            }
            // Errors: ['time'] treats ending because of the time limit as an error
            bot.channels.get("317859245309689856").awaitMessages(filter, { max: 1, time: 60000, errors: ['time'] })
                .then(collected => {
                    ma.delete();
                    if (collected.size < 1) {
                        member.kick();
                    }
                    return collected;
                })
                .then(collected => collected.map((m) => m.delete()));
        }
    }
});/**
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    process.exit();//force restart
});*/

bot.on('ready', () => {
    console.log("ReviveBot Ready");
});
bot.on("guildMemberUpdate", async function (member, newMem) {
    let user = member.user;
    if (member.guild && (member.guild.id === "184536578654339072")) {
        let oldMem = member;
        if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return;
        if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return;
        if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) {
            await request('http://revive-bot-discord.revive.systems/v0/discord/reverse_link/' + user.id);
        }
    }
});
<|endoftext|>


<commit_before>(function () {
  "use strict";
  angular.module('ledZepplin')
    .controller('AlbumDetails', [
      '$stateParams',
      '$log',
      'albums',
      '$scope',
      'albumResource',
      '_',
      '$timeout',
      '$state',
      '$uibModal',
      '$sce',
        function($stateParams, $log, albums, $scope, albumResource, _, $timeout, $state, $uibModal, $sce){
        var vm = this;
        vm.invalid = false;
        $scope.followingAlbums = [];
          vm.config = {
            sources: [],
            autoPlay: true,
            tracks: [],
            theme: "bower_components/videogular-themes-default/videogular.css",
            plugins: {
              poster: ""
            }
          };

      vm.removeAlbum = function(album) {
          var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'app/modules/albums/templates/deleteModal.template.html',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            windowClass: 'delete-modal',
            resolve: {
              album: function () {
                return album;
              }
            }
          });

          modalInstance.result.then(function (removeAlbum) {
            $scope.removeAlbum = removeAlbum;

            _.remove(vm.albums, $scope.removeAlbum);
            $timeout(function () {
              $state.go('home');
            }, 200);

            console.log($scope.removeAlbum, 'removed this');
          }, function () {
            $log.info('Modal dismissed at: ' + new Date());
          });

      };

      albums.$bindTo($scope, "data").then(function() {
        vm.albums = $scope.data.items;
        vm.album = _.find(vm.albums, {"id": $stateParams.id});

        albumResource.getAlbumTracks(vm.album.id).then(function (result) {
          vm.tracks = result.tracks.items;
          vm.getPlayList();
        },function(err){
          vm.invalid = true;
          console.error(err.data.error.message);
        });
        _.forEach(vm.albums, function(value, key) {
          if(value.following === true) {
            $scope.followingAlbums.push(value);
          }
        });

      });

      vm.getPlayList = function(){
        vm.songs = [];
        if(vm.tracks.length > 0) {
          for (var i = 0; i < vm.tracks.length; i++) {
            vm.track = {
              id: vm.tracks[i].id,
              title: vm.tracks[i].name,
              artist: vm.tracks[i].artists[0].name,
              url: vm.tracks[i].preview_url
            };

            vm.songs.push(vm.track);
          }

        } else {
          console.log("No tracks");
        }
      };

    }]);
}());<commit_msg>update to details controller and styling modal on prev commit<commit_after>(function () {
  "use strict";
  angular.module('ledZepplin')
    .controller('AlbumDetails', [
      '$stateParams',
      '$log',
      'albums',
      '$scope',
      'albumResource',
      '_',
      '$timeout',
      '$state',
      '$uibModal',

        function($stateParams, $log, albums, $scope, albumResource, _, $timeout, $state, $uibModal){
        var vm = this;
        vm.invalid = false;
        $scope.followingAlbums = [];

      vm.removeAlbum = function(album) {
          var modalInstance = $uibModal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'app/modules/albums/templates/deleteModal.template.html',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            windowClass: 'delete-modal',
            resolve: {
              album: function () {
                return album;
              }
            }
          });

          modalInstance.result.then(function (removeAlbum) {
            $scope.removeAlbum = removeAlbum;

            _.remove(vm.albums, $scope.removeAlbum);
            $timeout(function () {
              $state.go('home');
            }, 200);

            console.log($scope.removeAlbum, 'removed this');
          }, function () {
            $log.info('Modal dismissed at: ' + new Date());
          });

      };

      albums.$bindTo($scope, "data").then(function() {
        vm.albums = $scope.data.items;
        vm.album = _.find(vm.albums, {"id": $stateParams.id});

        albumResource.getAlbumTracks(vm.album.id).then(function (result) {
          vm.tracks = result.tracks.items;
          vm.getPlayList();
        },function(err){
          vm.invalid = true;
          console.error(err.data.error.message);
        });
        _.forEach(vm.albums, function(value, key) {
          if(value.following === true) {
            $scope.followingAlbums.push(value);
          }
        });

      });

      vm.getPlayList = function(){
        vm.songs = [];
        if(vm.tracks.length > 0) {
          for (var i = 0; i < vm.tracks.length; i++) {
            vm.track = {
              id: vm.tracks[i].id,
              title: vm.tracks[i].name,
              artist: vm.tracks[i].artists[0].name,
              url: vm.tracks[i].preview_url
            };

            vm.songs.push(vm.track);
          }

        } else {
          console.log("No tracks");
        }
      };

    }]);
}());<|endoftext|>


<commit_before>var init_comode = ""; //This stores active communicatin mode user is using
$(document).ready(function(){
    init_comode = $("input[name='mode']").val();
});

$('textarea#broadcastMsg').keyup(function(event){
    clickedKey = event.keyCode;

    //Trigger key on copy, paste or delete or backspace
    if(clickedKey==88 || clickedKey==86 || clickedKey==8 || clickedKey==9)
        $('textarea#broadcastMsg').trigger('keypress');
})

//button group for contribute and sending
$(".messageActionButton").on('click', function(e){
	target = $(this).attr('id'); //getting the id of clicked button

	//Getting the message
	message = $("#broadcastMsg").val();
    if(message.length<1){
        logFormError("Please provide message")
        return false;
    }

    //Checking reciepients
    recps = $("#dt_tableExport input:checked");
    arr = {};
    recps.each(function(index, data){
        arr[index] = $(data).val();
    });

    comode = $("input[name='mode']").val(); //chose mode for communication

    if(recps.length<1){
        logFormError("Select people to broadcast a message");
        return false;
    }

    //Sending the logic to different function for sending and scheduling
    if(target == 'sendBtn'){
    	//Asking before sending messages
	    confmodal = UIkit.modal("#sendMessageModal");

	    recpcount = checkNRecpts();
	    if(comode == "sms" || comode == "SMS")
	    {
	        smscount = checkSMSCount();
	        ttlSMScount = smscount.msg+""+(smscount.char!=0?1:0);
	        $(".transDet").html("Broadcasting to "+recpcount+" people in "+(smscount.msg == 0?"":smscount.msg)+" msg and "+smscount.char+' characters');
	        $(".transDet").append("
You will be charged for "+ttlSMScount+" SMS costing "+13*ttlSMScount*recpcount+"FRW");
	        oj = confmodal.show();
	        var me = 0;

	        $(".broadcastMsg").on('click', function(){
	            modal = UIkit.modal('#sendMessageModal');
	            modal.hide();
	            $.post('api/msg.php', {act:'save', mode:"sms", message:message, members:arr}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);
	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                        indicateSendProgress();
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })
	    }else if(comode == "app")
	    {

	        $(".transDet").html("Broadcasting to "+recpcount+" App users
Free of Charge!");
	        oj = confmodal.show();
	        var me = 0;

	        $(".broadcastMsg").on('click', function(){
	            modal = UIkit.modal('#sendMessageModal');
	            modal.hide();
	            $.post('api/msg.php', {act:'save', mode:"app", message:message, members:arr}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);

	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                        indicateSendProgress();
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })
	    }else if(comode == "email")
	    {
	        subject = $("#broadcastSubj").val();

	        $(".transDet").html("Broadcasting to "+recpcount+" emails
Free of Charge!");
	        oj = confmodal.show();
	        var me = 0;

	        $(".broadcastMsg").on('click', function(){
	            modal = UIkit.modal('#sendMessageModal');
	            modal.hide();
	            $.post('api/msg.php', {act:'save', mode:"email", subject:subject, message:message, members:arr}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);

	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                        indicateSendProgress();
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })
	    }
    }else if(target == 'scheduleBtn'){
    	//scheduling a message

    	//Asking for time to send the message
    	confmodal = UIkit.modal("#scheduleMessageModal");
    	oj = confmodal.show();

    	//getting schedule details
    	 $("#scheduleMessage").on('submit', function(e){
    	 		e.preventDefault();
    	 		//Date and time when message will be sent
    	 		date = $("#schedDate").val();
    	 		time = $("#schedTime").val();
	            // modal.hide();
	            $.post('api/msg.php', {act:'save', mode:comode, message:message, members:arr, scheduleTime:date+" "+time}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);
	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })

    }else{
    	alert("This could be wrong"+target)
    }
})

$("#comform").on('submit', function(e){
    e.preventDefault();

    message = $("#broadcastMsg").val();
    if(message.length<1){
        logFormError("Please provide message")
        return false;
    }

    //Asking before sending messages
    confmodal = UIkit.modal("#sendMessageModal");

    comode = $("input[name='mode']").val(); //chose mode for communication
    recpcount = checkNRecpts();
    if(comode == "sms" || comode == "SMS")
    {
        smscount = checkSMSCount();
        ttlSMScount = smscount.msg+""+(smscount.char!=0?1:0);
        $(".transDet").html("Broadcasting to "+recpcount+" people in "+(smscount.msg == 0?"":smscount.msg)+" msg and "+smscount.char+' characters');
        $(".transDet").append("
You will be charged for "+ttlSMScount+" SMS costing "+13*ttlSMScount*recpcount+"FRW");
        oj = confmodal.show();
        var me = 0;

        $(".broadcastMsg").on('click', function(){
            modal = UIkit.modal('#sendMessageModal');
            modal.hide();
            $.post('api/msg.php', {act:'save', mode:"sms", message:message, members:arr}, function(data){
               //Parsing return data
               try{
                    ret = JSON.parse(data);
                    if(ret.status){
                        //Preparing the user to see more actions
                        //Indicating the message send progress
                        messageID = ret.messageID;
                        indicateSendProgress();
                    }else{
                        log(ret.data);
                    }
               }catch(err){
                    log('Failed in parsing JSON');
                    log(err);
               }
            })
            return true;
        })
    }else if(comode == "app")
    {

        $(".transDet").html("Broadcasting to "+recpcount+" App users
Free of Charge!");
        oj = confmodal.show();
        var me = 0;

        $(".broadcastMsg").on('click', function(){
            modal = UIkit.modal('#sendMessageModal');
            modal.hide();
            $.post('api/msg.php', {act:'save', mode:"app", message:message, members:arr}, function(data){
               //Parsing return data
               try{
                    ret = JSON.parse(data);

                    if(ret.status){
                        //Preparing the user to see more actions
                        //Indicating the message send progress
                        messageID = ret.messageID;
                        indicateSendProgress();
                    }else{
                        log(ret.data);
                    }
               }catch(err){
                    log('Failed in parsing JSON');
                    log(err);
               }
            })
            return true;
        })
    }else if(comode == "email")
    {
        subject = $("#broadcastSubj").val();

        $(".transDet").html("Broadcasting to "+recpcount+" emails
Free of Charge!");
        oj = confmodal.show();
        var me = 0;

        $(".broadcastMsg").on('click', function(){
            modal = UIkit.modal('#sendMessageModal');
            modal.hide();
            $.post('api/msg.php', {act:'save', mode:"email", subject:subject, message:message, members:arr}, function(data){
               //Parsing return data
               try{
                    ret = JSON.parse(data);

                    if(ret.status){
                        //Preparing the user to see more actions
                        //Indicating the message send progress
                        messageID = ret.messageID;
                        indicateSendProgress();
                    }else{
                        log(ret.data);
                    }
               }catch(err){
                    log('Failed in parsing JSON');
                    log(err);
               }
            })
            return true;
        })
    }

});

$("th.sorthead").on('click', function(){
    selectedText = this.innerText.trim();

    allSortHeads = [];
    $("thead th").each(function(){
        temp = this.innerText.trim();
        allSortHeads.push(temp);
    });

    sortIndex = allSortHeads.indexOf(selectedText);

    //Sorting table according to sortindex
    $("#dt_tableExport tr").sort(function(index, value){
    });
    // var elemIndex = $('.sorthead').indexOf(this)
    // log(elemIndex)
});

$('textarea#broadcastMsg').keypress(function(){
    charcount = $(this).val().length;
    ++charcount;
    messages = charcount%160;
    if(messages < charcount){
        $(".moreSMSview").show();

        $("#msgcount").html(parseInt(charcount /160));
        $("#charcount").html(parseInt(charcount % 160));
    }else{
        $("#msgcount").html(0);
         $(".moreSMSview").hide();
        $("#charcount").html(charcount);
    }
    estimCost();
});

//select all checkboxes
$(".checkCont input[type='checkbox'].controlOption").change(function(){
    var status = this.checked; // "select all" checked status
    clickedElem = $(this).attr('data-target');

    elems = $('.'+clickedElem);

    elems.each(function(){ //iterate all listed checkbox items
        this.checked = status; //change ".checkbox" checked status
    });

    //Changing the receiver count on display --updating
    logRecCount();
});
//Trigerring counter when checkbox changes
$("#dt_tableExport input").on('change', function(){
    logRecCount();
})
$("#membersCont").on("change", function(){
    logRecCount();
})
$(document).ready(function() {
  $('th').each(function(col) {
    $(this).hover(
    function() { $(this).addClass('focus'); },
    function() { $(this).removeClass('focus'); }
  );
    $(this).click(function() {
      if ($(this).is('.asc')) {
        $(this).removeClass('asc');
        $(this).addClass('desc selected');
        sortOrder = -1;
      }
      else {
        $(this).addClass('asc selected');
        $(this).removeClass('desc');
        sortOrder = 1;
      }
      $(this).siblings().removeClass('asc selected');
      $(this).siblings().removeClass('desc selected');
      var arrData = $('table').find('tbody >tr:has(td)').get();
      arrData.sort(function(a, b) {
        var val1 = $(a).children('td').eq(col).text().toUpperCase();
        var val2 = $(b).children('td').eq(col).text().toUpperCase();
        if($.isNumeric(val1) && $.isNumeric(val2))
        return sortOrder == 1 ? val1-val2 : val2-val1;
        else
           return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
      });
      $.each(arrData, function(index, row) {
        $('tbody').append(row);
      });
    });
  });
});

$("#dt_tableExport tbody tr").on('click', function(){
    highlight  = $(this).find("input[type='checkbox']");
    log(highlight)
    highlight.attr('checked', !highlight.attr('checked'));
});

$(".comode li").on("click", function(){
    //Handling communication mode switching

    //Checking if commode is changed
    mode = $(this).attr('data-mode');

    prevmode = $("input[name='mode']").val();
    $("input[name='mode']").val(mode);

    //if communication mode is changed
    if(mode != prevmode){

        switchMode(mode);
        loadUsers(mode);
        logRecCount();
    }

})

comModes = ['sms', 'app', 'email'];

function switchMode(mode){
    for (var i = comModes.length - 1; i >= 0; i--) {
        cmode = comModes[i];
        cmode_elems = "."+cmode+"-elem";
        // alert(cmode+"  == "+ mode);
        if(cmode != mode){

            $(cmode_elems).addClass("uk-hidden"); //Hiding elements
            $("."+mode+"-elem").removeClass("uk-hidden");
        }else
            continue;
    }
    return false;

}
function loadUsers(modeUsers){
    //Function to load the users of a specifi mode
    log(members[modeUsers]);
    if(members[modeUsers])
    {
        // $("#membersCont")
        addMembers = members[modeUsers]; //members to add to table
        $("#membersCont").html("

");
        for(var n=0; n<addMembers.length; n++){
            mem = addMembers[n];
            $("#membersCont").append("
"+(n+1)+"	<input value=\""+mem['id']+"\" class=\"all "+mem['bname']+"\" type='checkbox'/>	"+mem['name']+"	"+mem['bname']+"	"+mem['phone']+"	"+mem['email']+"
");
        }
        log(addMembers);

    }
    else
    {
        alert("Can't find your members with "+modeUsers);
    }
}
function log(data){
    console.log(data)
}<commit_msg>fix double messages<commit_after>var init_comode = ""; //This stores active communicatin mode user is using
$(document).ready(function(){
    init_comode = $("input[name='mode']").val();
});

$('textarea#broadcastMsg').keyup(function(event){
    clickedKey = event.keyCode;

    //Trigger key on copy, paste or delete or backspace
    if(clickedKey==88 || clickedKey==86 || clickedKey==8 || clickedKey==9)
        $('textarea#broadcastMsg').trigger('keypress');
})

// button group for contribute and sending
$(".messageActionButton").on('click', function(e){
    e.preventDefault();
	target = $(this).attr('id'); //getting the id of clicked button

	//Getting the message
	message = $("#broadcastMsg").val();
    if(message.length<1){
        logFormError("Please provide message")
        return false;
    }

    //Checking reciepients
    recps = $("#dt_tableExport input:checked");
    arr = {};
    recps.each(function(index, data){
        arr[index] = $(data).val();
    });

    comode = $("input[name='mode']").val(); //chose mode for communication

    if(recps.length<1){
        logFormError("Select people to broadcast a message");
        return false;
    }

    //Sending the logic to different function for sending and scheduling
    if(target == 'sendBtn'){
    	//Asking before sending messages
	    confmodal = UIkit.modal("#sendMessageModal");

	    recpcount = checkNRecpts();
	    if(comode == "sms" || comode == "SMS")
	    {
	        smscount = checkSMSCount();
	        ttlSMScount = smscount.msg+""+(smscount.char!=0?1:0);
	        $(".transDet").html("Broadcasting to "+recpcount+" people in "+(smscount.msg == 0?"":smscount.msg)+" msg and "+smscount.char+' characters');
	        $(".transDet").append("
You will be charged for "+ttlSMScount+" SMS costing "+13*ttlSMScount*recpcount+"FRW");
	        oj = confmodal.show();
	        var me = 0;

	        $(".broadcastMsg").on('click', function(){
	            modal = UIkit.modal('#sendMessageModal');
	            modal.hide();
	            $.post('api/msg.php', {act:'save', mode:"sms", message:message, members:arr}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);
	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                        indicateSendProgress();
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })
	    }else if(comode == "app")
	    {

	        $(".transDet").html("Broadcasting to "+recpcount+" App users
Free of Charge!");
	        oj = confmodal.show();
	        var me = 0;

	        $(".broadcastMsg").on('click', function(){
	            modal = UIkit.modal('#sendMessageModal');
	            modal.hide();
	            $.post('api/msg.php', {act:'save', mode:"app", message:message, members:arr}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);

	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                        indicateSendProgress();
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })
	    }else if(comode == "email")
	    {
	        subject = $("#broadcastSubj").val();

	        $(".transDet").html("Broadcasting to "+recpcount+" emails
Free of Charge!");
	        oj = confmodal.show();
	        var me = 0;

	        $(".broadcastMsg").on('click', function(){
	            modal = UIkit.modal('#sendMessageModal');
	            modal.hide();
	            $.post('api/msg.php', {act:'save', mode:"email", subject:subject, message:message, members:arr}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);

	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                        indicateSendProgress();
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })
	    }
    }else if(target == 'scheduleBtn'){
    	//scheduling a message

    	//Asking for time to send the message
    	confmodal = UIkit.modal("#scheduleMessageModal");
    	oj = confmodal.show();

    	//getting schedule details
    	 $("#scheduleMessage").on('submit', function(e){
    	 		e.preventDefault();
    	 		//Date and time when message will be sent
    	 		date = $("#schedDate").val();
    	 		time = $("#schedTime").val();
	            // modal.hide();
	            $.post('api/msg.php', {act:'save', mode:comode, message:message, members:arr, scheduleTime:date+" "+time}, function(data){
	               //Parsing return data
	               try{
	                    ret = JSON.parse(data);
	                    if(ret.status){
	                        //Preparing the user to see more actions
	                        //Indicating the message send progress
	                        messageID = ret.messageID;
	                    }else{
	                        log(ret.data);
	                    }
	               }catch(err){
	                    log('Failed in parsing JSON');
	                    log(err);
	               }
	            })
	            return true;
	        })

    }else{
    	alert("This could be wrong"+target)
    }
})

// $("#comform").on('submit', function(e){
//     e.preventDefault();

//     message = $("#broadcastMsg").val();
//     if(message.length<1){
//         logFormError("Please provide message")
//         return false;
//     }

//     //Asking before sending messages
//     confmodal = UIkit.modal("#sendMessageModal");

//     comode = $("input[name='mode']").val(); //chose mode for communication
//     recpcount = checkNRecpts();

//     if(comode == "sms" || comode == "SMS")
//     {
//         smscount = checkSMSCount();
//         ttlSMScount = smscount.msg+""+(smscount.char!=0?1:0);
//         $(".transDet").html("Broadcasting to "+recpcount+" people in "+(smscount.msg == 0?"":smscount.msg)+" msg and "+smscount.char+' characters');
//         $(".transDet").append("
You will be charged for "+ttlSMScount+" SMS costing "+13*ttlSMScount*recpcount+"FRW");
//         oj = confmodal.show();
//         var me = 0;

//         $(".broadcastMsg").on('click', function(){
//             modal = UIkit.modal('#sendMessageModal');
//             modal.hide();
//             $.post('api/msg.php', {act:'save', mode:"sms", message:message, members:arr}, function(data){
//                //Parsing return data
//                try{
//                     ret = JSON.parse(data);
//                     if(ret.status){
//                         //Preparing the user to see more actions
//                         //Indicating the message send progress
//                         messageID = ret.messageID;
//                         indicateSendProgress();
//                     }else{
//                         log(ret.data);
//                     }
//                }catch(err){
//                     log('Failed in parsing JSON');
//                     log(err);
//                }
//             })
//             return true;
//         })
//     }else if(comode == "app")
//     {

//         $(".transDet").html("Broadcasting to "+recpcount+" App users
Free of Charge!");
//         oj = confmodal.show();
//         var me = 0;

//         $(".broadcastMsg").on('click', function(){
//             modal = UIkit.modal('#sendMessageModal');
//             modal.hide();
//             $.post('api/msg.php', {act:'save', mode:"app", message:message, members:arr}, function(data){
//                //Parsing return data
//                try{
//                     ret = JSON.parse(data);

//                     if(ret.status){
//                         //Preparing the user to see more actions
//                         //Indicating the message send progress
//                         messageID = ret.messageID;
//                         indicateSendProgress();
//                     }else{
//                         log(ret.data);
//                     }
//                }catch(err){
//                     log('Failed in parsing JSON');
//                     log(err);
//                }
//             })
//             return true;
//         })
//     }else if(comode == "email")
//     {
//         subject = $("#broadcastSubj").val();

//         $(".transDet").html("Broadcasting to "+recpcount+" emails
Free of Charge!");
//         oj = confmodal.show();
//         var me = 0;

//         $(".broadcastMsg").on('click', function(){
//             modal = UIkit.modal('#sendMessageModal');
//             modal.hide();
//             $.post('api/msg.php', {act:'save', mode:"email", subject:subject, message:message, members:arr}, function(data){
//                //Parsing return data
//                try{
//                     ret = JSON.parse(data);

//                     if(ret.status){
//                         //Preparing the user to see more actions
//                         //Indicating the message send progress
//                         messageID = ret.messageID;
//                         indicateSendProgress();
//                     }else{
//                         log(ret.data);
//                     }
//                }catch(err){
//                     log('Failed in parsing JSON');
//                     log(err);
//                }
//             })
//             return true;
//         })
//     }

//     console.log(confmodal)
//     alert(confmodal)
// });

$("th.sorthead").on('click', function(){
    selectedText = this.innerText.trim();

    allSortHeads = [];
    $("thead th").each(function(){
        temp = this.innerText.trim();
        allSortHeads.push(temp);
    });

    sortIndex = allSortHeads.indexOf(selectedText);

    //Sorting table according to sortindex
    $("#dt_tableExport tr").sort(function(index, value){
    });
    // var elemIndex = $('.sorthead').indexOf(this)
    // log(elemIndex)
});

$('textarea#broadcastMsg').keypress(function(){
    charcount = $(this).val().length;
    ++charcount;
    messages = charcount%160;
    if(messages < charcount){
        $(".moreSMSview").show();

        $("#msgcount").html(parseInt(charcount /160));
        $("#charcount").html(parseInt(charcount % 160));
    }else{
        $("#msgcount").html(0);
         $(".moreSMSview").hide();
        $("#charcount").html(charcount);
    }
    estimCost();
});

//select all checkboxes
$(".checkCont input[type='checkbox'].controlOption").change(function(){
    var status = this.checked; // "select all" checked status
    clickedElem = $(this).attr('data-target');

    elems = $('.'+clickedElem);

    elems.each(function(){ //iterate all listed checkbox items
        this.checked = status; //change ".checkbox" checked status
    });

    //Changing the receiver count on display --updating
    logRecCount();
});
//Trigerring counter when checkbox changes
$("#dt_tableExport input").on('change', function(){
    logRecCount();
})
$("#membersCont").on("change", function(){
    logRecCount();
})
$(document).ready(function() {
  $('th').each(function(col) {
    $(this).hover(
    function() { $(this).addClass('focus'); },
    function() { $(this).removeClass('focus'); }
  );
    $(this).click(function() {
      if ($(this).is('.asc')) {
        $(this).removeClass('asc');
        $(this).addClass('desc selected');
        sortOrder = -1;
      }
      else {
        $(this).addClass('asc selected');
        $(this).removeClass('desc');
        sortOrder = 1;
      }
      $(this).siblings().removeClass('asc selected');
      $(this).siblings().removeClass('desc selected');
      var arrData = $('table').find('tbody >tr:has(td)').get();
      arrData.sort(function(a, b) {
        var val1 = $(a).children('td').eq(col).text().toUpperCase();
        var val2 = $(b).children('td').eq(col).text().toUpperCase();
        if($.isNumeric(val1) && $.isNumeric(val2))
        return sortOrder == 1 ? val1-val2 : val2-val1;
        else
           return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
      });
      $.each(arrData, function(index, row) {
        $('tbody').append(row);
      });
    });
  });
});

$("#dt_tableExport tbody tr").on('click', function(){
    highlight  = $(this).find("input[type='checkbox']");
    log(highlight)
    highlight.attr('checked', !highlight.attr('checked'));
});

$(".comode li").on("click", function(){
    //Handling communication mode switching

    //Checking if commode is changed
    mode = $(this).attr('data-mode');

    prevmode = $("input[name='mode']").val();
    $("input[name='mode']").val(mode);

    //if communication mode is changed
    if(mode != prevmode){

        switchMode(mode);
        loadUsers(mode);
        logRecCount();
    }

})

comModes = ['sms', 'app', 'email'];

function switchMode(mode){
    for (var i = comModes.length - 1; i >= 0; i--) {
        cmode = comModes[i];
        cmode_elems = "."+cmode+"-elem";
        // alert(cmode+"  == "+ mode);
        if(cmode != mode){

            $(cmode_elems).addClass("uk-hidden"); //Hiding elements
            $("."+mode+"-elem").removeClass("uk-hidden");
        }else
            continue;
    }
    return false;

}
function loadUsers(modeUsers){
    //Function to load the users of a specifi mode
    log(members[modeUsers]);
    if(members[modeUsers])
    {
        // $("#membersCont")
        addMembers = members[modeUsers]; //members to add to table
        $("#membersCont").html("

");
        for(var n=0; n<addMembers.length; n++){
            mem = addMembers[n];
            $("#membersCont").append("
"+(n+1)+"	<input value=\""+mem['id']+"\" class=\"all "+mem['bname']+"\" type='checkbox'/>	"+mem['name']+"	"+mem['bname']+"	"+mem['phone']+"	"+mem['email']+"
");
        }
        log(addMembers);

    }
    else
    {
        alert("Can't find your members with "+modeUsers);
    }
}
function log(data){
    console.log(data)
}<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');

var read = require('fs-readdir-recursive');

module.exports = function(options, log) {

	var dialect = process.env.DB_DIALECT || 'nosqldb';

	var dbPath = options.dirname + options.folders.db + '/' + dialect;

	var methods = read(dbPath);

	var db = {};

	_.each(methods, function(path) {

		if (path === 'connect.js') { return; }

		if (path === 'schema.js') {

			if (_.contains(process.argv, '--schema')) {
				try {
					require(dbPath + '/schema.js')(log);
				}
				catch(err) {}
			}

			return;

		}

		var info = path.split('/');

		var table = info[0];

		var method = info[1].replace(/\.js/, '');

		if (!db[table]) { db[table] = {}; }

		db[table][method] = require(dbPath + '/' + path);

	});

	_.each(db, function(methods, table) {

		log('gray', '      db.' + table + ' = {' + _.keys(methods).join(', ') + '}');

	});

	db.connect = require(dbPath + '/connect.js');

	return db;

};
<commit_msg>printing which db dialect is getting used<commit_after>'use strict';

var _ = require('underscore');

var read = require('fs-readdir-recursive');

module.exports = function(options, log) {

	var dialect = process.env.DB_DIALECT || 'nosqldb';

	log('gray', '      Using "' + dialect + '" dialect...');

	var dbPath = options.dirname + options.folders.db + '/' + dialect;

	var methods = read(dbPath);

	var db = {};

	_.each(methods, function(path) {

		if (path === 'connect.js') { return; }

		if (path === 'schema.js') {

			if (_.contains(process.argv, '--schema')) {
				try {
					require(dbPath + '/schema.js')(log);
				}
				catch(err) {}
			}

			return;

		}

		var info = path.split('/');

		var table = info[0];

		var method = info[1].replace(/\.js/, '');

		if (!db[table]) { db[table] = {}; }

		db[table][method] = require(dbPath + '/' + path);

	});

	_.each(db, function(methods, table) {

		log('gray', '      db.' + table + ' = {' + _.keys(methods).join(', ') + '}');

	});

	db.connect = require(dbPath + '/connect.js');

	return db;

};
<|endoftext|>