<commit_before>//j// BOF

/*
direct JavaScript Toolbox
All-in-one toolbox for HTML5 presentation and manipulation
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?js;djt

This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can
obtain one at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------------------------
https://www.direct-netware.de/redirect?licenses;mpl2
----------------------------------------------------------------------------
#echo(jsDjtVersion)#
#echo(__FILEPATH__)#
*/

define([ 'jquery', 'Modernizr' ], function($, Modernizr) {
	var tabindex_count = 1;

	function enable_input(id) {
		$("#" + id).removeAttr('disabled');
	}

	function unfocus(id, focused_class) {
		$("#" + id).removeClass(focused_class);
	}

	function XHtml5FormElement(args) {
		if (args === undefined || (!('id' in args)) || (!('type' in args))) {
			throw new Error('Missing required arguments');
		}

		if (!('_djt_XHtml5FormElement_enable_input' in self)) {
			self._djt_XHtml5FormElement_enable_input = enable_input;
		}

		if (!('_djt_XHtml5FormElement_unfocus' in self)) {
			self._djt_XHtml5FormElement_unfocus = unfocus;
		}

		this.id = args.id;
		this.$node = $("#" + args.id);
		this.type = args.type;

		this.focused_class = (('djt_config' in self && 'XHtml5FormElement_focused_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_class : 'djt-ui-XHtml5FormElement-input-focus');
		this.focused_duration = (('djt_config' in self && 'XHtml5FormElement_focused_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_duration : 0);
		this.temporarily_disabled_duration = (('djt_config' in self && 'XHtml5FormElement_temporarily_disabled_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_temporarily_disabled_duration : 3000);

		var _this = this;

		if ($.inArray(this.type, [ 'datepicker', 'form', 'form_section', 'range', 'timepicker' ]) < 0) {
			this.$node.on('focus', function() {
				_this.focus();
			});

			this.tabindex();
		}

		if (this.type == 'button') {
			if (this.$node.attr('type') == 'submit' && !(this.$node.prop('disabled'))) {
				$(this.$node.prop('form')).on('submit', function(event) {
					_this.disable_input_temporarily(event);
				})
			}
		}

		if (this.$node.attr('placeholder') != undefined
		    && (('placeholder' in Modernizr && (!Modernizr.placeholder))
		        || ('input' in Modernizr && (!Modernizr.input.placeholder))
		       )
		   ) {
			require([ 'jquery', 'jquery.placeholder' ], function($, $placeholder) {
				_this.$node.placeholder();
			});
		}
	}

	XHtml5FormElement.prototype.disable_input_temporarily = function(event, duration) {
		var _return = true;

		if (event === undefined) {
			throw new Error('Missing required arguments');
		}

		if (duration === undefined) {
			duration = this.temporarily_disabled_duration;
		}

		if (this.$node.prop('disabled')) {
			_return = false;
		} else {
			this.$node.attr('disabled', 'disabled');
			self.setTimeout('self._djt_XHtml5FormElement_enable_input("' + id + '")', duration);
		}

		if (event == null) {
			return _return;
		} else if (!_return) {
			event.preventDefault();
		}
	}

	XHtml5FormElement.prototype.focus = function(duration) {
		if (duration === undefined) {
			duration = this.focused_duration;
		}

		if (this.$node.addClass(this.focused_class) != null) {
			if (duration > 0) {
				self.setTimeout('self._djt_XHtml5FormElement_unfocus("' + this.id + '", "' + this.focused_class + '")', duration);
			} else {
				var _this = this;

				this.$node.one('focusout', function() {
					unfocus(_this.id, _this.focused_class);
				});
			}
		}
	}

	XHtml5FormElement.prototype.set_focused_class = function(classname) {
		this.focused_class = classname;
	}

	XHtml5FormElement.prototype.set_focused_duration = function(duration) {
		this.focused_duration = duration;
	}

	XHtml5FormElement.prototype.set_temporarily_disabled_duration = function(duration) {
		this.temporarily_disabled_duration = duration;
	}

	XHtml5FormElement.prototype.tabindex = function() {
		this.$node.attr('tabindex', tabindex_count);
		tabindex_count += 1;
	}

	return XHtml5FormElement;
/*
			if (f_type == 'datepicker')
			{
				djs_load_functions([ { file:'ext_djs/djs_html5_datetime.min.js' } ]).done (function ()
				{
					if (!('css_classes' in f_params)) { f_params['css_classes'] = null; }
					if (!('css_classes_replaced' in f_params)) { f_params['css_classes_replaced'] = null; }
					djs_html5_datetime ({ datetime_lang:"<?php echo $direct_local['lang_iso_domain']; ?>",id:f_params.id,onCompleted:{ func:'djs_formbuilder_set_select_css',params:f_params } });
				});
			}

			if (f_type == 'form')
			{
				if (djs_var.basic_formbuilder_form_ready)
				{
					if (!('id_button' in f_params)) { f_params['id_button'] = null; }
					if (!('url' in f_params)) { f_params['url'] = null; }
					jQuery("#" + f_params.id).on ('submit',function () { return djs_formbuilder_submit (f_params.id,f_params.url,f_params.id_button); });
				}
				else
				{
		djs_load_functions ([
		 { file:'swg_AJAX.php.js',block:'djs_swgAJAX_insert' },
		 { file:'ext_jquery/jquery.ui.core.min.js' },
		 { file:'ext_jquery/jquery.ui.effect.min.js' },
		 { file:'ext_jquery/jquery.ui.effect-transfer.min.js' }
		]).done (function ()
		{
			djs_var.basic_formbuilder_form_ready = true;
			djs_formbuilder_init (f_params);
		});
				}
			}

			if (f_type == 'form_sections')
			{
				if (djs_var.basic_formbuilder_accordion_ready)
				{
					jQuery("#" + f_params.id + " > .ui-accordion-header").removeClass ('pagecontenttitle');
					jQuery("#" + f_params.id).accordion({ header:'.ui-accordion-header',heightStyle:'content' }).on ('activate',function (f_event,f_ui) { f_ui.newPanel.find(':input').first().trigger ('focus'); });
				}
				else
				{
		djs_load_functions ([
		 { file:'ext_jquery/jquery.ui.core.min.js' },
		 { file:'ext_jquery/jquery.ui.widget.min.js' },
		 { file:'ext_jquery/jquery.ui.accordion.min.js' }
		]).done (function ()
		{
			djs_var.basic_formbuilder_accordion_ready = true;
			djs_formbuilder_init (f_params);
		});
				}
			}

			if (f_type == 'email')
			{
				var f_data = jQuery ("#" + f_params.id);
				if (!('formNoValidate' in f_data.get (0))) { djs_DOM_replace ({ animate:false,data:(f_data.clone().attr ('type','text')),id:f_params.id,onReplace:{ func:'djs_formbuilder_init',params:{ id:f_params.id } } }); }
			}

			if (f_type == 'range')
			{
				var f_data = jQuery ("#" + f_params.id);

				if (!('stepUp' in f_data.get (0)))
				{
					if (!djs_var.basic_formbuilder_range_ready)
					{
						djs_load_functions ({ file:'swg_formbuilder.php.js',block:'djs_formbuilder_range' });
						djs_load_functions ({ file:'ext_jquery/jquery.ui.core.min.js' });
						djs_load_functions ({ file:'ext_jquery/jquery.ui.widget.min.js' });
						djs_load_functions ({ file:'ext_jquery/jquery.ui.mouse.min.js' });
						djs_load_functions ({ file:'ext_jquery/jquery.ui.slider.min.js' });

						djs_var.basic_formbuilder_range_ready = true;
					}

					f_data.next('br').remove ();

					var f_range_params = { id:f_params.id,max:(parseFloat (f_data.attr ('max'))),min:(parseFloat (f_data.attr ('min'))),value:f_data.val () };
					if (f_range_params.value == '') { f_range_params.value = f_range_params.min; }
					f_data = "

<input type='hidden' name='" + (f_data.attr ("name")) + "' value=\"" + f_range_params.value + "\" id='" + f_params.id + "i' />" + f_range_params.value + "
";

					djs_DOM_replace ({ data:f_data,id:f_params.id,onReplace:{ func:'djs_formbuilder_range',params:f_range_params } });
				}
			}

			if (f_type == 'resizeable')
			{
				if (djs_var.basic_formbuilder_resizeable_ready) { jQuery("#" + f_params.id).wrap("<div style='padding:<?php echo $direct_settings['theme_form_td_padding']; ?>' />").parent().resizable ({ alsoResize:"#" + f_params.id }); }
				else
				{
		djs_load_functions ([
		 { file:'ext_jquery/jquery.ui.core.min.js' },
		 { file:'ext_jquery/jquery.ui.widget.min.js' },
		 { file:'ext_jquery/jquery.ui.mouse.min.js' },
		 { file:'ext_jquery/jquery.ui.resizable.min.js' }
		]).done (function ()
		{
			djs_var.basic_formbuilder_resizeable_ready = true;
			djs_formbuilder_init (f_params);
		});
				}
			}

			if (f_type == 'search')
			{
				var f_data = jQuery ("#" + f_params.id);
				if (!('formNoValidate' in f_data.get (0))) { djs_DOM_replace ({ animate:false,data:(f_data.clone().attr ('type','text')),id:f_params.id,onReplace:{ func:'djs_formbuilder_init',params:{ id:f_params.id } } }); }
			}

			if (f_type == 'tel')
			{
				var f_data = jQuery ("#" + f_params.id);
				if (!('formNoValidate' in f_data.get (0))) { djs_DOM_replace ({ animate:false,data:(f_data.clone().attr ('type','text')),id:f_params.id,onReplace:{ func:'djs_formbuilder_init',params:{ id:f_params.id } } }); }
			}

			if (f_type == 'timepicker')
			{
				djs_load_functions([ { file:'ext_djs/djs_html5_datetime.min.js' } ]).done (function ()
				{
					if (!('css_classes' in f_params)) { f_params['css_classes'] = null; }
					if (!('css_classes_replaced' in f_params)) { f_params['css_classes_replaced'] = null; }
					djs_html5_datetime ({ datetime_lang:"<?php echo $direct_local['lang_iso_domain']; ?>",id:f_params.id,onCompleted:{ func:'djs_formbuilder_set_select_css',params:f_params } });
				});
			}

			if (f_type == 'url')
			{
				var f_data = jQuery ("#" + f_params.id);
				if (!('formNoValidate' in f_data.get (0))) { djs_DOM_replace ({ animate:false,data:(f_data.clone().attr ('type','text')),id:f_params.id,onReplace:{ func:'djs_formbuilder_init',params:{ id:f_params.id } } }); }
			}
		}

		function djs_formbuilder_range (f_params) { f_jquery_object = jQuery("#" + f_params.id + "s").slider(f_params).on ('slide',function (f_event,f_ui) { djs_formbuilder_range_slide (f_params,f_ui.value); }); }

		function djs_formbuilder_range_slide (f_params,f_value)
		{
			jQuery("#" + f_params.id + "i").val (f_value);
			jQuery("#" + f_params.id + "o").text (f_value);
		}

		function djs_formbuilder_set_select_css (f_params)
		{
			if (('css_classes' in f_params)&&('css_classes_replaced' in f_params)&&('id' in f_params)&&(f_params.css_classes !== null)&&(f_params.css_classes_replaced !== null))
			{
				var f_jquery_object = jQuery ("#" + f_params.id);

				if (f_jquery_object.data ('djsHtml5Replaced') == true) { f_jquery_object.find("select").filter(':visible').addClass (f_params.css_classes_replaced); }
				else
				{
					f_jquery_object.addClass (f_params.css_classes);
					djs_formbuilder_tabindex (f_params);
				}
			}
*/
});

//j// EOF<commit_msg>Enhancement: Added support to "file" input elements Change: Generalized module specific "data-*" attribute and CSS naming Trivial: Used short-hand Hammer listener definition<commit_after>//j// BOF

/*
direct JavaScript Toolbox
All-in-one toolbox for HTML5 presentation and manipulation
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?js;djt

This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can
obtain one at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------------------------
https://www.direct-netware.de/redirect?licenses;mpl2
----------------------------------------------------------------------------
#echo(jsDjtVersion)#
#echo(__FILEPATH__)#
*/

define([ 'jquery', 'Hammer', 'Modernizr' ], function($, Hammer, Modernizr) {
	var NEW_INPUT_ATTRIBUTES_COPIED = [ 'id', 'name', 'type', 'size', 'class', 'style', 'multiple', 'tabindex' ];
	var tabindex_count = 1;

	function XHtml5FormElement(args) {
		if (args === undefined || (!('id' in args)) || (!('type' in args))) {
			throw new Error('Missing required arguments');
		}

		this.id = args.id;
		this.$node = $("#" + args.id);
		this.type = args.type;

		this.focused_class = (('djt_config' in self && 'XHtml5FormElement_focused_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_class : 'djt-ui-xhtml5formelement-input-focus');
		this.focused_duration = (('djt_config' in self && 'XHtml5FormElement_focused_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_duration : 0);
		this.selected_file_class = (('djt_config' in self && 'XHtml5FormElement_selected_file_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_selected_file_class : 'djt-ui-xhtml5formelement-input-selected-file');
		this.selected_file_details_class = (('djt_config' in self && 'XHtml5FormElement_selected_file_details_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_selected_file_details_class : 'djt-ui-xhtml5formelement-input-selected-file-details');
		this.temporarily_disabled_duration = (('djt_config' in self && 'XHtml5FormElement_temporarily_disabled_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_temporarily_disabled_duration : 3000);

		var _this = this;

		if ($.inArray(this.type, [ 'datepicker', 'form', 'form_section', 'range', 'timepicker' ]) < 0) {
			this.$node.on('focus', function() {
				_this.focus();
			});

			this.propagate_tabindex();
		}

		if (this.type == 'button') {
			if (this.$node.attr('type') == 'submit' && !(this.$node.prop('disabled'))) {
				$(this.$node.prop('form')).on('submit', function(event) {
					_this.disable_input_temporarily(event);
				})
			}
		}

		if (this.type == 'file') {
			this._init_file_input();
		}

		if (this.$node.attr('placeholder') != undefined
		    && (('placeholder' in Modernizr && (!Modernizr.placeholder))
		        || ('input' in Modernizr && (!Modernizr.input.placeholder))
		       )
		   ) {
			require([ 'jquery', 'jquery.placeholder' ], function($, $placeholder) {
				_this.$node.placeholder();
			});
		}
	}

	XHtml5FormElement.prototype.disable_input_temporarily = function(event, duration) {
		var _return = true;

		if (event === undefined) {
			throw new Error('Missing required arguments');
		}

		if (duration === undefined) {
			duration = this.temporarily_disabled_duration;
		}

		if (this.$node.prop('disabled')) {
			_return = false;
		} else {
			this.$node.attr('disabled', 'disabled');

			self.setTimeout(function() {
				$("#" + id).removeAttr('disabled');
			}, duration);
		}

		if (event == null) {
			return _return;
		} else if (!_return) {
			event.preventDefault();
		}
	}

	XHtml5FormElement.prototype.focus = function(duration) {
		if (duration === undefined) {
			duration = this.focused_duration;
		}

		if (this.$node.addClass(this.focused_class) != null) {
			var _this = this;

			var unfocus_callback = function() {
				$("#" + _this.id).removeClass(_this.focused_class);
			};

			if (duration > 0) {
				self.setTimeout(unfocus_callback, duration);
			} else {
				this.$node.one('focusout', unfocus_callback);
			}
		}
	}

	XHtml5FormElement.prototype._get_cleared_new_input = function($node) {
		var new_input = '<input ';

		var node_attribute_name;
		var node_value;

		for (var i = 0; i < NEW_INPUT_ATTRIBUTES_COPIED.length; i++) {
			node_attribute_name = NEW_INPUT_ATTRIBUTES_COPIED[i];

			node_value = $node.attr(node_attribute_name);
			if (node_value !== undefined) { new_input += " " + node_attribute_name + "=\"" + node_value + "\""; }
		}

		new_input += '></input>';
		var _return = $(new_input);

		node_value = $node.data();
		if (node_value !== undefined) { _return.data(node_value); }

		return _return;
	}

	XHtml5FormElement.prototype._get_file_input_details = function(input_file_data) {
		var _return = input_file_data.name;

		if ('size' in input_file_data) {
			_return += " (" + input_file_data.size + " B)";
		}

		return _return;
	}

	XHtml5FormElement.prototype._init_file_input = function() {
		var _this = this;

		this.$node.on('change', function(event) {
			_this.on_file_input_selected(event);
		});
	}

	XHtml5FormElement.prototype.on_file_input_deselected = function(event, $selected_file_wrapper) {
		if (this.$node.attr('multiple') === undefined) {
			var $old_node = this.$node;
			this.$node = this._get_cleared_new_input($old_node);
			$old_node.remove();

			$selected_file_wrapper.after(this.$node);
			$selected_file_wrapper.remove();

			this.$node.css('display', 'initial');
			this._init_file_input();
		} else {
			$selected_file_wrapper.remove();
		}
	}

	XHtml5FormElement.prototype.on_file_input_selected = function(event) {
		if ('files' in event.target && event.target.files.length > 0) {
			var selected_file_wrapper = "

";
			var selected_files = event.target.files;

			this.$node.wrap(selected_file_wrapper);
			var $selected_file_wrapper = this.$node.parent();

			this.$node.css('display', 'none');

			if (selected_files.length == 1) {
				$selected_file_wrapper.append("" + this._get_file_input_details(selected_files[0]) + "");
			} else {
				var $selected_files_list = $('

');

				for (var i = 0; i < selected_files.length; i++) {
					$selected_files_list.append('
' + this._get_file_input_details(selected_files[i]) + '
');
				}

				$selected_file_wrapper.append($selected_files_list);
			}

			if (this.$node.attr('multiple') !== undefined) {
				var $old_node = this.$node;
				this.$node = this._get_cleared_new_input($old_node);
				$old_node.removeAttr('id');
				$old_node.removeAttr('tabindex');

				$selected_file_wrapper.after(this.$node);

				this.$node.css('display', 'initial');
				this._init_file_input();
			}

			var _this = this;

			Hammer($selected_file_wrapper.get(0)).on('tap', function(event) {
				_this.on_file_input_deselected(event, $selected_file_wrapper);
			});
		}
	}

	XHtml5FormElement.prototype.propagate_tabindex = function() {
		if (this.$node.attr('tabindex') === undefined) {
			this.$node.attr('tabindex', tabindex_count);
			tabindex_count += 1;
		}
	}

	XHtml5FormElement.prototype.set_focused_class = function(classname) {
		this.focused_class = classname;
	}

	XHtml5FormElement.prototype.set_focused_duration = function(duration) {
		this.focused_duration = duration;
	}

	XHtml5FormElement.prototype.set_temporarily_disabled_duration = function(duration) {
		this.temporarily_disabled_duration = duration;
	}

	return XHtml5FormElement;
});

//j// EOF<|endoftext|>


<commit_before>var genfun = require('generate-function')
var genobj = require('generate-object-property')

var a = function(type) {
  switch (type) {
    case 'array':
    case 'object':
    case 'integer':
    return 'an '+type

    default:
    return 'a '+type
  }
}

var formatHelp = function(name, msg) {
  return JSON.stringify(name.replace(/\[[^\]]+\]/g, '.*')+' '+msg)
}

var types = {}

types.null = function() {
  return name+' === null'
}

types.boolean = function(name) {
  return 'typeof '+name+' === "boolean"'
}

types.array = function(name) {
  return 'Array.isArray('+name+')'
}

types.object = function(name) {
  return 'typeof '+name+' === "object" && '+name+' && !Array.isArray('+name+')'
}

types.number = function(name) {
  return 'typeof '+name+' === "number"'
}

types.integer = function(name) {
  return 'typeof '+name+' === "number" && '+name+' | 0 === '+name
}

types.string = function(name) {
  return 'typeof '+name+' === "string"'
}

var unique = function(array) {
  for (var i = 1; i < array.length; i++) {
    if (array.indexOf(array[i]) !== i) return false
  }
  return true
}

var validators = {}

var compile = function(schema) {
  var scope = {unique:unique}

  var vars = ['i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
  var loopVar = function() {
    var v = vars.shift()
    vars.push(v+v[0])
    return v
  }

  var visit = function(name, node) {
    var type = node.type
    var enm = node.enum || (type && type.enum)

    if (node.required) {
      validate()
        ('if (%s === undefined) {', name)
          ('validate.error = %s', formatHelp(name, 'is required'))
          ('return false')
        ('}')
    } else {
      validate()
        ('if (%s !== undefined) {', name)
    }

    if (type) {
      var msg = [].concat(type)
        .map(function(t) {
          return t.type || t
        })
        .map(a)
        .join(' or ')

      var invalid = [].concat(type)
        .map(function(t) {
          return t.type || t
        })
        .map(function(t) {
          return '!('+types[t](name)+')'
        })
        .join(' && ')

      if (!invalid) invalid = 'true'

      validate()
        ('if (%s) {', invalid)
          ('validate.error = %s', formatHelp(name, 'must be '+msg))
          ('return false')
        ('}')
    }

    if (enm) {
      var invalid = enm
        .map(function(e) {
          return name+' !== '+JSON.stringify(e)
        })
        .join(' && ')

      if (!invalid) invalid = 'true'

      validate
        ('if (%s) {', invalid)
          ('validate.error = %s', formatHelp(name, 'must be one of ['+enm.join(', ')+']'))
          ('return false')
        ('}')
    }

    if (node.minimum) {
      validate
        ('if (%s < %d) {', name, node.minimum)
          ('validate.error = %s', formatHelp(name, 'must be more than '+node.minimum))
          ('return false')
        ('}')
    }

    if (node.maximum) {
      validate
        ('if (%s > %d) {', name, node.maximum)
          ('validate.error = %s', formatHelp(name, 'must be less than '+node.maximum))
          ('return false')
        ('}')
    }

    if (node.pattern) {
      var i = Object.keys(scope).length
      var p = new RegExp(node.pattern)
      scope['pattern'+i] = p

      validate
        ('if (!pattern%d.test(%s)) {', i, name)
          ('validate.error = %s', formatHelp(name, 'must match /'+node.pattern+'/'))
          ('return false')
        ('}')
    }

    var items = node.items
    if (items && items[0]) items = items[0] // TODO: this is probably WRONG. investigate

    if (type === 'array') {
      if (node.minItems) {
        validate
          ('if (%s.length < %d) {', name, node.minItems)
            ('validate.error = %s', formatHelp(name, 'must contain at least '+node.minItems+' item(s)'))
          ('}')
      }
      if (node.maxItems) {
        validate
          ('if (%s.length > %d) {', name, node.maxItems)
            ('validate.error = %s', formatHelp(name, 'must contain at most '+node.minItems+' item(s)'))
          ('}')
      }
      if (node.uniqueItems) {
        validate
          ('if (!unique(%s)) {', name)
            ('validate.error = %s', formatHelp(name, 'must only contain unique values'))
            ('return false')
          ('}')
      }

      var i = loopVar()
      validate('for (var '+i+' = 0; '+i+' < %s.length; '+i+'++) {', name)
      visit(name+'['+i+']', items)
      validate('}')
    }

    if (node.additionalProperties === false && node.type === 'object') {
      var i = loopVar()
      var invalid = Object.keys(node.properties)
        .map(function(p) {
          return 'keys['+i+'] !== '+JSON.stringify(p)
        })
        .join(' && ')

      if (!invalid) invalid = 'true'

      validate('var keys = Object.keys(%s)', name)
        ('for (var '+i+' = 0; '+i+' < keys.length; '+i+'++) {')
          ('if (%s) {', invalid)
            ('valid.error = keys['+i+'] + " is not allowed"')
            ('return false')
          ('}')
        ('}')
    }

    if (node.properties) {
      Object.keys(node.properties).forEach(function(n) {
        var pname = genobj(name, n)
        var prop = node.properties[n]
        if (Array.isArray(node.required)) prop.required = node.required.indexOf(n) > -1
        visit(pname, prop)
      })
    }

    if (!node.required) validate('}')
  }

  var validate = genfun()
    ('function validate(data) {')
      ('validate.error = ""')

  schema.required = schema.required !== false
  visit('data', schema)

  validate()
    ('return true')
  ('}')

  validate = validate.toFunction(scope)
  validate.error = ''

  return validate
}

module.exports = compile<commit_msg>add toJSON<commit_after>var genfun = require('generate-function')
var genobj = require('generate-object-property')

var a = function(type) {
  switch (type) {
    case 'array':
    case 'object':
    case 'integer':
    return 'an '+type

    default:
    return 'a '+type
  }
}

var formatHelp = function(name, msg) {
  return JSON.stringify(name.replace(/\[[^\]]+\]/g, '.*')+' '+msg)
}

var types = {}

types.null = function() {
  return name+' === null'
}

types.boolean = function(name) {
  return 'typeof '+name+' === "boolean"'
}

types.array = function(name) {
  return 'Array.isArray('+name+')'
}

types.object = function(name) {
  return 'typeof '+name+' === "object" && '+name+' && !Array.isArray('+name+')'
}

types.number = function(name) {
  return 'typeof '+name+' === "number"'
}

types.integer = function(name) {
  return 'typeof '+name+' === "number" && '+name+' | 0 === '+name
}

types.string = function(name) {
  return 'typeof '+name+' === "string"'
}

var unique = function(array) {
  for (var i = 1; i < array.length; i++) {
    if (array.indexOf(array[i]) !== i) return false
  }
  return true
}

var validators = {}

var compile = function(schema) {
  var scope = {unique:unique}

  var vars = ['i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z']
  var loopVar = function() {
    var v = vars.shift()
    vars.push(v+v[0])
    return v
  }

  var visit = function(name, node) {
    var type = node.type
    var enm = node.enum || (type && type.enum)

    if (node.required) {
      validate()
        ('if (%s === undefined) {', name)
          ('validate.error = %s', formatHelp(name, 'is required'))
          ('return false')
        ('}')
    } else {
      validate()
        ('if (%s !== undefined) {', name)
    }

    if (type) {
      var msg = [].concat(type)
        .map(function(t) {
          return t.type || t
        })
        .map(a)
        .join(' or ')

      var invalid = [].concat(type)
        .map(function(t) {
          return t.type || t
        })
        .map(function(t) {
          return '!('+types[t](name)+')'
        })
        .join(' && ')

      if (!invalid) invalid = 'true'

      validate()
        ('if (%s) {', invalid)
          ('validate.error = %s', formatHelp(name, 'must be '+msg))
          ('return false')
        ('}')
    }

    if (enm) {
      var invalid = enm
        .map(function(e) {
          return name+' !== '+JSON.stringify(e)
        })
        .join(' && ')

      if (!invalid) invalid = 'true'

      validate
        ('if (%s) {', invalid)
          ('validate.error = %s', formatHelp(name, 'must be one of ['+enm.join(', ')+']'))
          ('return false')
        ('}')
    }

    if (node.minimum) {
      validate
        ('if (%s < %d) {', name, node.minimum)
          ('validate.error = %s', formatHelp(name, 'must be more than '+node.minimum))
          ('return false')
        ('}')
    }

    if (node.maximum) {
      validate
        ('if (%s > %d) {', name, node.maximum)
          ('validate.error = %s', formatHelp(name, 'must be less than '+node.maximum))
          ('return false')
        ('}')
    }

    if (node.pattern) {
      var i = Object.keys(scope).length
      var p = new RegExp(node.pattern)
      scope['pattern'+i] = p

      validate
        ('if (!pattern%d.test(%s)) {', i, name)
          ('validate.error = %s', formatHelp(name, 'must match /'+node.pattern+'/'))
          ('return false')
        ('}')
    }

    var items = node.items
    if (items && items[0]) items = items[0] // TODO: this is probably WRONG. investigate

    if (type === 'array') {
      if (node.minItems) {
        validate
          ('if (%s.length < %d) {', name, node.minItems)
            ('validate.error = %s', formatHelp(name, 'must contain at least '+node.minItems+' item(s)'))
          ('}')
      }
      if (node.maxItems) {
        validate
          ('if (%s.length > %d) {', name, node.maxItems)
            ('validate.error = %s', formatHelp(name, 'must contain at most '+node.minItems+' item(s)'))
          ('}')
      }
      if (node.uniqueItems) {
        validate
          ('if (!unique(%s)) {', name)
            ('validate.error = %s', formatHelp(name, 'must only contain unique values'))
            ('return false')
          ('}')
      }

      var i = loopVar()
      validate('for (var '+i+' = 0; '+i+' < %s.length; '+i+'++) {', name)
      visit(name+'['+i+']', items)
      validate('}')
    }

    if (node.additionalProperties === false && node.type === 'object') {
      var i = loopVar()
      var invalid = Object.keys(node.properties)
        .map(function(p) {
          return 'keys['+i+'] !== '+JSON.stringify(p)
        })
        .join(' && ')

      if (!invalid) invalid = 'true'

      validate('var keys = Object.keys(%s)', name)
        ('for (var '+i+' = 0; '+i+' < keys.length; '+i+'++) {')
          ('if (%s) {', invalid)
            ('valid.error = keys['+i+'] + " is not allowed"')
            ('return false')
          ('}')
        ('}')
    }

    if (node.properties) {
      Object.keys(node.properties).forEach(function(n) {
        var pname = genobj(name, n)
        var prop = node.properties[n]
        if (Array.isArray(node.required)) prop.required = node.required.indexOf(n) > -1
        visit(pname, prop)
      })
    }

    if (!node.required) validate('}')
  }

  var validate = genfun()
    ('function validate(data) {')
      ('validate.error = ""')

  schema.required = schema.required !== false
  visit('data', schema)

  validate()
    ('return true')
  ('}')

  validate = validate.toFunction(scope)
  validate.error = ''
  validate.toJSON = function() {
    return schema
  }

  return validate
}

module.exports = compile<|endoftext|>


<commit_before>var util = require('util');
var fs = require('fs');
var http = require('http');
var path = require('path');
var child_process = require('child_process');
var GOLANG_CONSTANTS = require('./golang-constants.json');

//TODO: See if https://forums.aws.amazon.com/message.jspa?messageID=633802
// has been updated with new information
process.env.PATH = process.env.PATH + ':/var/task';

var SPARTA_BINARY_NAME = 'Sparta.lambda.amd64';
var SPARTA_BINARY_PATH = path.join('/tmp', SPARTA_BINARY_NAME);
var MAXIMUM_RESPAWN_COUNT = 5;

var PROXIED_MODULES = ['s3', 'sns', 'apigateway'];

var golangProcess = null;
var failCount = 0;

function makeRequest(path, event, context) {
  var requestBody = {
    event: event,
    context: context
  };

  var stringified = JSON.stringify(requestBody);

  var contentLength = Buffer.byteLength(stringified, 'utf-8');
  var options = {
    host: 'localhost',
    port: 9999,
    path: path,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': contentLength
    }
  };

  var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });
    res.on('end', function() {
      // TODO: Bridge the NodeJS and golang worlds by including the golang
      // HTTP status text in the error response if appropriate.  This enables
      // the API Gateway integration response to use standard golang StatusText regexp
      // matches to manage HTTP status codes.
      var responseData = {};
      responseData.code = res.statusCode;
      responseData.status = GOLANG_CONSTANTS.HTTP_STATUS_TEXT[res.statusCode.toString()];
      responseData.headers = res.headers;
      responseData.error = (res.statusCode >= 400) ? body : undefined;
      responseData.results = responseData.error ? undefined : body;
      try {
        // TODO: Check content-type before parse attempt
        if (responseData.results)
        {
          responseData.results = JSON.parse(responseData.results);
        }
      } catch (e) {
        // NOP
      }
      var err = responseData.error ? new Error(JSON.stringify(responseData)) : null;
      var resp = err ? null : responseData;
      context.done(err, resp);
    });
  });
  req.on('error', function(e) {
    context.done(e, null);
  });
  req.write(stringified);
  req.end();
}

var log = function(obj_or_string)
{
  if (typeof(obj_or_string) !== 'object')
  {
    obj_or_string = {msg: obj_or_string};
  }
  if (obj_or_string.stack)
  {
    console.error();
  }
  else
  {
    console.log(JSON.stringify(obj_or_string));
  }
};

// Move the file to /tmp to temporarily work around
// https://forums.aws.amazon.com/message.jspa?messageID=583910
var ensureGoLangBinary = function(callback)
{
    try
    {
      log('Checking for binary: ' + SPARTA_BINARY_PATH);
      fs.statSync(SPARTA_BINARY_PATH);
      setImmediate(callback, null);
    }
    catch (e)
    {
      log('Copying golang binary');
      var command = util.format('cp ./%s %s; chmod +x %s',
                                SPARTA_BINARY_NAME,
                                SPARTA_BINARY_PATH,
                                SPARTA_BINARY_PATH);
      child_process.exec(command, function (err, stdout) {
        if (err)
        {
          console.error(err);
          process.exit(1);
        }
        else
        {
          log(stdout.toString('utf-8'));
        }
        callback(err, stdout);
      });
    }
};

var createForwarder = function(path) {
  var forwardToGolangProcess = function(event, context)
  {
    if (!golangProcess) {
      ensureGoLangBinary(function() {
        golangProcess = child_process.spawn(SPARTA_BINARY_PATH, ['execute', '--signal', process.pid], {});

        golangProcess.stdout.on('data', function(buf) {
          log(buf.toString('utf-8'));
        });
        golangProcess.stderr.on('data', function(buf) {
          log(buf.toString('utf-8'));
        });

        var terminationHandler = function(eventName) {
          return function(value) {
            console.error(util.format('Sparta %s: %s\n', eventName.toUpperCase(), JSON.stringify(value)));
            failCount += 1;
            if (failCount > MAXIMUM_RESPAWN_COUNT) {
              process.exit(1);
            }
            golangProcess = null;
            forwardToGolangProcess(null, null);
          };
        };
        golangProcess.on('error', terminationHandler('error'));
        golangProcess.on('exit', terminationHandler('exit'));
        process.on('exit', function() {
          if (golangProcess) {
            golangProcess.kill();
          }
        });
        var golangProcessReadyHandler = function() {
          process.removeListener('SIGUSR2', golangProcessReadyHandler);
          forwardToGolangProcess(event, context);
        };
        process.on('SIGUSR2', golangProcessReadyHandler);
      });
    }
    else if (event && context)
    {
      makeRequest(path, event, context);
    }
  };
  return forwardToGolangProcess;
};

var sendResponse = function(event, context, e, results)
{
  try {
    var response = require('cfn-response');
    var data = {
      ERROR: e ? e.toString() : undefined,
      RESULTS: results || undefined
    };
    response.send(event, context, e ? response.FAILED : response.SUCCESS, data);
  }
  catch (eResponse) {
    log('ERROR sending response: ' + eResponse.toString());
  }
};

// CustomResource Configuration exports
PROXIED_MODULES.forEach(function (eachConfig) {
  var exportName = util.format('%sConfiguration', eachConfig);
  exports[exportName] = function(event, context)
  {
    try {
      var AWS = require('aws-sdk');
      var awsConfig = new AWS.Config({});

      // If the stack is in update mode, don't delegate
      var proxyTasks = [];
      proxyTasks.push(function (taskCB) {
        var params = {
          StackName: event.StackId
        };
        var awsConfig = new AWS.Config({});
        awsConfig.logger = console;
        var cloudFormation = new AWS.CloudFormation(awsConfig);
        cloudFormation.describeStacks(params, taskCB);
      });

      // Only delegate to the stack if the update is in progress.
      var onStackDescription = function(e, stackDescriptionResponse) {
        if (e)
        {
          sendResponse(event, context, e, null);
        }
        else {
          var stackDescription = stackDescriptionResponse.Stacks ? stackDescriptionResponse.Stacks[0] : {};
          var stackStatus = stackDescription.StackStatus || "";
          if (stackStatus !== "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS")
          {
            try {
              log(util.format('Delegating [%s] to configurator: %s.\nEvent: %s',
                          event.RequestType, eachConfig,  JSON.stringify(event, null,  ' ')));
              var svc = require(util.format('./%s', eachConfig));
              svc.handler(event, context);
            } catch (e) {
              sendResponse(event, context, e, null);
            }
          } else {
            log('Bypassing configurator execution due to status: ' + stackStatus);
            sendResponse(event, context, e, "NOP");
          }
        }
      };
      // Get the current stack status
      var params = {
        StackName: event.StackId
      };
      var cloudFormation = new AWS.CloudFormation(awsConfig);
      cloudFormation.describeStacks(params, onStackDescription);
    } catch (e) {
      console.error('Failed to load configurator:' + e.toString());
      sendResponse(event, context, e, null);
    }
  };
});

exports.main = createForwarder('/');
// Additional golang handlers to be dynamically appended below
<commit_msg>Cleanup logging for better CloudWatch support<commit_after>var util = require('util');
var fs = require('fs');
var http = require('http');
var path = require('path');
var child_process = require('child_process');
var GOLANG_CONSTANTS = require('./golang-constants.json');

//TODO: See if https://forums.aws.amazon.com/message.jspa?messageID=633802
// has been updated with new information
process.env.PATH = process.env.PATH + ':/var/task';

var SPARTA_BINARY_NAME = 'Sparta.lambda.amd64';
var SPARTA_BINARY_PATH = path.join('/tmp', SPARTA_BINARY_NAME);
var MAXIMUM_RESPAWN_COUNT = 5;

var PROXIED_MODULES = ['s3', 'sns', 'apigateway'];

var golangProcess = null;
var failCount = 0;

function makeRequest(path, event, context) {
  var requestBody = {
    event: event,
    context: context
  };

  var stringified = JSON.stringify(requestBody);

  var contentLength = Buffer.byteLength(stringified, 'utf-8');
  var options = {
    host: 'localhost',
    port: 9999,
    path: path,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': contentLength
    }
  };

  var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    var body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });
    res.on('end', function() {
      // TODO: Bridge the NodeJS and golang worlds by including the golang
      // HTTP status text in the error response if appropriate.  This enables
      // the API Gateway integration response to use standard golang StatusText regexp
      // matches to manage HTTP status codes.
      var responseData = {};
      responseData.code = res.statusCode;
      responseData.status = GOLANG_CONSTANTS.HTTP_STATUS_TEXT[res.statusCode.toString()];
      responseData.headers = res.headers;
      responseData.error = (res.statusCode >= 400) ? body : undefined;
      responseData.results = responseData.error ? undefined : body;
      try {
        // TODO: Check content-type before parse attempt
        if (responseData.results)
        {
          responseData.results = JSON.parse(responseData.results);
        }
      } catch (e) {
        // NOP
      }
      var err = responseData.error ? new Error(JSON.stringify(responseData)) : null;
      var resp = err ? null : responseData;
      context.done(err, resp);
    });
  });
  req.on('error', function(e) {
    context.done(e, null);
  });
  req.write(stringified);
  req.end();
}

var log = function(obj_or_string)
{
  if (typeof(obj_or_string) !== 'object')
  {
    obj_or_string = {msg: obj_or_string};
  }
  if (obj_or_string.stack)
  {
    console.error();
  }
  else
  {
    var xformed = {};
    Object.keys(obj_or_string).forEach(function (eachKey) {
      xformed[eachKey.toUpperCase()] = obj_or_string[eachKey];
    });
    console.log(JSON.stringify(xformed));
  }
};

// Move the file to /tmp to temporarily work around
// https://forums.aws.amazon.com/message.jspa?messageID=583910
var ensureGoLangBinary = function(callback)
{
    try
    {
      log('Checking for binary: ' + SPARTA_BINARY_PATH);
      fs.statSync(SPARTA_BINARY_PATH);
      setImmediate(callback, null);
    }
    catch (e)
    {
      log('Copying golang binary');
      var command = util.format('cp ./%s %s; chmod +x %s',
                                SPARTA_BINARY_NAME,
                                SPARTA_BINARY_PATH,
                                SPARTA_BINARY_PATH);
      child_process.exec(command, function (err, stdout) {
        if (err)
        {
          console.error(err);
          process.exit(1);
        }
        else
        {
          log(stdout.toString('utf-8'));
        }
        callback(err, stdout);
      });
    }
};

var createForwarder = function(path) {
  var forwardToGolangProcess = function(event, context)
  {
    if (!golangProcess) {
      ensureGoLangBinary(function() {
        golangProcess = child_process.spawn(SPARTA_BINARY_PATH, ['execute', '--signal', process.pid], {});

        golangProcess.stdout.on('data', function(buf) {
          log(buf.toString('utf-8'));
        });
        golangProcess.stderr.on('data', function(buf) {
          log(buf.toString('utf-8'));
        });

        var terminationHandler = function(eventName) {
          return function(value) {
            console.error(util.format('Sparta %s: %s\n', eventName.toUpperCase(), JSON.stringify(value)));
            failCount += 1;
            if (failCount > MAXIMUM_RESPAWN_COUNT) {
              process.exit(1);
            }
            golangProcess = null;
            forwardToGolangProcess(null, null);
          };
        };
        golangProcess.on('error', terminationHandler('error'));
        golangProcess.on('exit', terminationHandler('exit'));
        process.on('exit', function() {
          if (golangProcess) {
            golangProcess.kill();
          }
        });
        var golangProcessReadyHandler = function() {
          process.removeListener('SIGUSR2', golangProcessReadyHandler);
          forwardToGolangProcess(event, context);
        };
        process.on('SIGUSR2', golangProcessReadyHandler);
      });
    }
    else if (event && context)
    {
      makeRequest(path, event, context);
    }
  };
  return forwardToGolangProcess;
};

var sendResponse = function(event, context, e, results)
{
  try {
    var response = require('cfn-response');
    var data = {
      ERROR: e ? e.toString() : undefined,
      RESULTS: results || undefined
    };
    response.send(event, context, e ? response.FAILED : response.SUCCESS, data);
  }
  catch (eResponse) {
    log('ERROR sending response: ' + eResponse.toString());
  }
};

// CustomResource Configuration exports
PROXIED_MODULES.forEach(function (eachConfig) {
  var exportName = util.format('%sConfiguration', eachConfig);
  exports[exportName] = function(event, context)
  {
    try {
      var AWS = require('aws-sdk');
      var awsConfig = new AWS.Config({});

      // If the stack is in update mode, don't delegate
      var proxyTasks = [];
      proxyTasks.push(function (taskCB) {
        var params = {
          StackName: event.StackId
        };
        var awsConfig = new AWS.Config({});
        awsConfig.logger = console;
        var cloudFormation = new AWS.CloudFormation(awsConfig);
        cloudFormation.describeStacks(params, taskCB);
      });

      // Only delegate to the stack if the update is in progress.
      var onStackDescription = function(e, stackDescriptionResponse) {
        if (e)
        {
          sendResponse(event, context, e, null);
        }
        else {
          var stackDescription = stackDescriptionResponse.Stacks ? stackDescriptionResponse.Stacks[0] : {};
          var stackStatus = stackDescription.StackStatus || "";
          if (stackStatus !== "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS")
          {
            try {
              log({
                requestType: event.RequestType,
                handler: eachConfig,
                event: event
              });
              var svc = require(util.format('./%s', eachConfig));
              svc.handler(event, context);
            } catch (e) {
              sendResponse(event, context, e, null);
            }
          } else {
            log('Bypassing configurator execution due to status: ' + stackStatus);
            sendResponse(event, context, e, "NOP");
          }
        }
      };
      // Get the current stack status
      var params = {
        StackName: event.StackId
      };
      var cloudFormation = new AWS.CloudFormation(awsConfig);
      cloudFormation.describeStacks(params, onStackDescription);
    } catch (e) {
      console.error('Failed to load configurator:' + e.toString());
      sendResponse(event, context, e, null);
    }
  };
});

exports.main = createForwarder('/');
// Additional golang handlers to be dynamically appended below
<|endoftext|>


<commit_before>//j// BOF

/*
direct JavaScript Toolbox
All-in-one toolbox for HTML5 presentation and manipulation
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?js;djt

This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can
obtain one at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------------------------
https://www.direct-netware.de/redirect?licenses;mpl2
----------------------------------------------------------------------------
#echo(jsDjtVersion)#
#echo(__FILEPATH__)#
*/

/**
 * @module XHtml5FormElement
 */
define([ 'jquery', 'Hammer', 'Modernizr' ], function($, Hammer, Modernizr) {
	/**
	 * While copying an input element the following list of attributes are copied
	 * as well.
	 *
	 * @constant
	 */
	var NEW_INPUT_ATTRIBUTES_COPIED = [ 'id', 'name', 'type', 'size', 'class', 'style', 'multiple', 'tabindex' ];
	/**
	 * "tabindex" applied to the next form field.
	 *
	 * @static
	 */
	var tabindex_count = 1;

	/**
	 * "XHtml5FormElement" provides some fallback and dynamic features to
	 * (X)HTML5 form fields.
	 *
	 * @class XHtml5FormElement
	 *
	 * @param {object} args Arguments to initialize a given XHtml5FormElement
	 */
	function XHtml5FormElement(args) {
		if (args === undefined || (!('type' in args))) {
			throw new Error('Missing required arguments');
		}

		this.$node = null;
		this.type = args.type;

		if ('id' in args) {
			this.$node = $("#" + args.id);
		} else if ('jQnode' in args) {
			this.$node = args.jQnode;
		}

		if (this.$node == null) {
			throw new Error('Missing required arguments');
		}

		this.id = this.$node.attr('id');

		if (this.id === undefined) {
			this.id = ("djt_xhtml5formelement_id_" + Math.random().toString().replace(/\W/,'_'));
			this.$node.attr('id', this.id);
		}

		this.focused_class = (('djt_config' in self && 'XHtml5FormElement_focused_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_class : 'djt-ui-xhtml5formelement-input-focus');
		this.focused_duration = (('djt_config' in self && 'XHtml5FormElement_focused_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_duration : 0);
		this.selected_file_class = (('djt_config' in self && 'XHtml5FormElement_selected_file_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_selected_file_class : 'djt-ui-xhtml5formelement-input-selected-file');
		this.selected_file_details_class = (('djt_config' in self && 'XHtml5FormElement_selected_file_details_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_selected_file_details_class : 'djt-ui-xhtml5formelement-input-selected-file-details');
		this.temporarily_disabled_duration = (('djt_config' in self && 'XHtml5FormElement_temporarily_disabled_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_temporarily_disabled_duration : 3000);

		var _this = this;

		if ($.inArray(this.type, [ 'form', 'form_section' ]) < 0
		    && ((!('init_default_behaviour' in args)) || args.init_default_behaviour)
		   ) {
			this.$node.on('focus', function() {
				_this.on_focus();
			});

			//if ($.inArray(this.type, [ 'date', 'datetime-local', 'month', 'range', 'time', 'week' ]) < 0) {
			this.propagate_tabindex();
			//}
		}

		if (this.type == 'button') {
			if (this.$node.attr('type') == 'submit' && !(this.$node.prop('disabled'))) {
				$(this.$node.prop('form')).on('submit', function(event) {
					_this.disable_input_temporarily(event);
				})
			}
		}

		if (this.type == 'file') {
			this._init_file_input();
		}

		if (this.$node.attr('placeholder') != undefined
		    && (('placeholder' in Modernizr && (!Modernizr.placeholder))
		        || ('input' in Modernizr && (!Modernizr.input.placeholder))
		       )
		   ) {
			require([ 'jquery', 'jquery.placeholder' ], function($, $placeholder) {
				_this.$node.placeholder();
			});
		}
	}

	/**
	 * Disable input for a given amount of time.
	 *
	 * @method
	 *
	 * @param {object} event Event triggering the disabled state
	 * @param {number} duration Duration of the disabled state
	 */
	XHtml5FormElement.prototype.disable_input_temporarily = function(event, duration) {
		var _return = true;

		if (event === undefined) {
			throw new Error('Missing required arguments');
		}

		if (duration === undefined) {
			duration = this.temporarily_disabled_duration;
		}

		if (this.$node.prop('disabled')) {
			_return = false;
		} else {
			this.$node.attr('disabled', 'disabled');

			self.setTimeout(function() {
				$("#" + id).removeAttr('disabled');
			}, duration);
		}

		if (event == null) {
			return _return;
		} else if (!_return) {
			event.preventDefault();
		}
	}

	/**
	 * Returns a clean copy of the input field.
	 *
	 * @method
	 *
	 * @param {object} $node jQuery node to be copied
	 *
	 * @return {object} Copied jQuery node
	 */
	XHtml5FormElement.prototype._get_cleared_new_input = function($node) {
		var new_input = '<input ';

		var node_attribute_name;
		var node_value;

		for (var i = 0; i < NEW_INPUT_ATTRIBUTES_COPIED.length; i++) {
			node_attribute_name = NEW_INPUT_ATTRIBUTES_COPIED[i];

			node_value = $node.attr(node_attribute_name);
			if (node_value !== undefined) { new_input += " " + node_attribute_name + "=\"" + node_value + "\""; }
		}

		new_input += '></input>';
		var _return = $(new_input);

		node_value = $node.data();
		if (node_value !== undefined) { _return.data(node_value); }

		return _return;
	}

	/**
	 * Returns (X)HTML code with details about a given file.
	 *
	 * @method
	 *
	 * @param {object} file_data File data
	 *
	 * @return {string} (X)HTML code with file details
	 */
	XHtml5FormElement.prototype._get_file_input_details = function(file_data) {
		var _return = file_data.name;

		if ('size' in file_data) {
			_return += " (" + file_data.size + " B)";
		}

		return _return;
	}

	/**
	 * Initializes file input fields.
	 *
	 * @method
	 */
	XHtml5FormElement.prototype._init_file_input = function() {
		var _this = this;

		this.$node.on('change', function(event) {
			_this.on_file_input_selected(event);
		});
	}

	/**
	 * Event listener for deselecting a file upload.
	 *
	 * @method
	 *
	 * @param {object} event Event triggering deselection
	 * @param {object} $selected_file_wrapper File upload wrapper to be removed
	 */
	XHtml5FormElement.prototype.on_file_input_deselected = function(event, $selected_file_wrapper) {
		if (this.$node.attr('multiple') === undefined) {
			var $old_node = this.$node;
			this.$node = this._get_cleared_new_input($old_node);
			$old_node.remove();

			$selected_file_wrapper.after(this.$node);
			$selected_file_wrapper.remove();

			this.$node.css('display', 'initial');
			this._init_file_input();
		} else {
			$selected_file_wrapper.remove();
		}
	}

	/**
	 * Event listener for selecting a file upload.
	 *
	 * @method
	 *
	 * @param {object} event Event triggering selection
	 */
	XHtml5FormElement.prototype.on_file_input_selected = function(event) {
		if ('files' in event.target && event.target.files.length > 0) {
			var selected_file_wrapper = "

";
			var selected_files = event.target.files;

			this.$node.wrap(selected_file_wrapper);
			var $selected_file_wrapper = this.$node.parent();

			this.$node.css('display', 'none');

			if (selected_files.length == 1) {
				$selected_file_wrapper.append("" + this._get_file_input_details(selected_files[0]) + "");
			} else {
				var $selected_files_list = $('

');

				for (var i = 0; i < selected_files.length; i++) {
					$selected_files_list.append('
' + this._get_file_input_details(selected_files[i]) + '
');
				}

				$selected_file_wrapper.append($selected_files_list);
			}

			if (this.$node.attr('multiple') !== undefined) {
				var $old_node = this.$node;
				this.$node = this._get_cleared_new_input($old_node);
				$old_node.removeAttr('id');
				$old_node.removeAttr('tabindex');

				$selected_file_wrapper.after(this.$node);

				this.$node.css('display', 'initial');
				this._init_file_input();
			}

			var _this = this;

			Hammer($selected_file_wrapper.get(0)).on('tap', function(event) {
				_this.on_file_input_deselected(event, $selected_file_wrapper);
			});
		}
	}

	/**
	 * Event listener for focusing an input field.
	 *
	 * @method
	 *
	 * @param {number} duration Duration to temporarily apply the focused CSS class
	 */
	XHtml5FormElement.prototype.on_focus = function(duration) {
		if (duration === undefined) {
			duration = this.focused_duration;
		}

		if (this.$node.addClass(this.focused_class) != null) {
			var _this = this;

			var unfocus_callback = function() {
				$("#" + _this.id).removeClass(_this.focused_class);
			};

			if (duration > 0) {
				self.setTimeout(unfocus_callback, duration);
			} else {
				this.$node.one('focusout', unfocus_callback);
			}
		}
	}

	/**
	 * Applies the next "tabindex" number to the input field.
	 *
	 * @method
	 */
	XHtml5FormElement.prototype.propagate_tabindex = function() {
		if (this.$node.attr('tabindex') === undefined) {
			this.$node.attr('tabindex', tabindex_count);
			tabindex_count += 1;
		}
	}

	/**
	 * Sets the focused CSS class used.
	 *
	 * @method
	 *
	 * @param {string} class_name CSS class name
	 */
	XHtml5FormElement.prototype.set_focused_class = function(class_name) {
		this.focused_class = class_name;
	}

	/**
	 * Sets the duration the focused CSS class is applied temporarily.
	 *
	 * @method
	 *
	 * @param {duration} duration Duration to temporarily apply the focused CSS
	 *        class
	 */
	XHtml5FormElement.prototype.set_focused_duration = function(duration) {
		this.focused_duration = duration;
	}

	/**
	 * Sets the duration the input field will be disabled temporarily.
	 *
	 * @method
	 *
	 * @param {duration} duration Duration to temporarily disable the input field
	 */
	XHtml5FormElement.prototype.set_temporarily_disabled_duration = function(duration) {
		this.temporarily_disabled_duration = duration;
	}

	return XHtml5FormElement;
});

//j// EOF<commit_msg>Fix: Fixed "hidden" exception for "id" not defined<commit_after>//j// BOF

/*
direct JavaScript Toolbox
All-in-one toolbox for HTML5 presentation and manipulation
----------------------------------------------------------------------------
(C) direct Netware Group - All rights reserved
https://www.direct-netware.de/redirect?js;djt

This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can
obtain one at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------------------------
https://www.direct-netware.de/redirect?licenses;mpl2
----------------------------------------------------------------------------
#echo(jsDjtVersion)#
#echo(__FILEPATH__)#
*/

/**
 * @module XHtml5FormElement
 */
define([ 'jquery', 'Hammer', 'Modernizr' ], function($, Hammer, Modernizr) {
	/**
	 * While copying an input element the following list of attributes are copied
	 * as well.
	 *
	 * @constant
	 */
	var NEW_INPUT_ATTRIBUTES_COPIED = [ 'id', 'name', 'type', 'size', 'class', 'style', 'multiple', 'tabindex' ];
	/**
	 * "tabindex" applied to the next form field.
	 *
	 * @static
	 */
	var tabindex_count = 1;

	/**
	 * "XHtml5FormElement" provides some fallback and dynamic features to
	 * (X)HTML5 form fields.
	 *
	 * @class XHtml5FormElement
	 *
	 * @param {object} args Arguments to initialize a given XHtml5FormElement
	 */
	function XHtml5FormElement(args) {
		if (args === undefined || (!('type' in args))) {
			throw new Error('Missing required arguments');
		}

		this.$node = null;
		this.type = args.type;

		if ('id' in args) {
			this.$node = $("#" + args.id);
		} else if ('jQnode' in args) {
			this.$node = args.jQnode;
		}

		if (this.$node == null) {
			throw new Error('Missing required arguments');
		}

		this.id = this.$node.attr('id');

		if (this.id === undefined) {
			this.id = ("djt_xhtml5formelement_id_" + Math.random().toString().replace(/\W/,'_'));
			this.$node.attr('id', this.id);
		}

		this.focused_class = (('djt_config' in self && 'XHtml5FormElement_focused_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_class : 'djt-ui-xhtml5formelement-input-focus');
		this.focused_duration = (('djt_config' in self && 'XHtml5FormElement_focused_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_focused_duration : 0);
		this.selected_file_class = (('djt_config' in self && 'XHtml5FormElement_selected_file_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_selected_file_class : 'djt-ui-xhtml5formelement-input-selected-file');
		this.selected_file_details_class = (('djt_config' in self && 'XHtml5FormElement_selected_file_details_class' in self.djt_config) ? self.djt_config.XHtml5FormElement_selected_file_details_class : 'djt-ui-xhtml5formelement-input-selected-file-details');
		this.temporarily_disabled_duration = (('djt_config' in self && 'XHtml5FormElement_temporarily_disabled_duration' in self.djt_config) ? self.djt_config.XHtml5FormElement_temporarily_disabled_duration : 3000);

		var _this = this;

		if ($.inArray(this.type, [ 'form', 'form_section' ]) < 0
		    && ((!('init_default_behaviour' in args)) || args.init_default_behaviour)
		   ) {
			this.$node.on('focus', function() {
				_this.on_focus();
			});

			//if ($.inArray(this.type, [ 'date', 'datetime-local', 'month', 'range', 'time', 'week' ]) < 0) {
			this.propagate_tabindex();
			//}
		}

		if (this.type == 'button') {
			if (this.$node.attr('type') == 'submit' && !(this.$node.prop('disabled'))) {
				$(this.$node.prop('form')).on('submit', function(event) {
					_this.disable_input_temporarily(event);
				})
			}
		}

		if (this.type == 'file') {
			this._init_file_input();
		}

		if (this.$node.attr('placeholder') != undefined
		    && (('placeholder' in Modernizr && (!Modernizr.placeholder))
		        || ('input' in Modernizr && (!Modernizr.input.placeholder))
		       )
		   ) {
			require([ 'jquery', 'jquery.placeholder' ], function($, $placeholder) {
				_this.$node.placeholder();
			});
		}
	}

	/**
	 * Disable input for a given amount of time.
	 *
	 * @method
	 *
	 * @param {object} event Event triggering the disabled state
	 * @param {number} duration Duration of the disabled state
	 */
	XHtml5FormElement.prototype.disable_input_temporarily = function(event, duration) {
		var _return = true;

		if (event === undefined) {
			throw new Error('Missing required arguments');
		}

		if (duration === undefined) {
			duration = this.temporarily_disabled_duration;
		}

		if (this.$node.prop('disabled')) {
			_return = false;
		} else {
			this.$node.attr('disabled', 'disabled');

			self.setTimeout(function() {
				$("#" + this.id).removeAttr('disabled');
			}, duration);
		}

		if (event == null) {
			return _return;
		} else if (!_return) {
			event.preventDefault();
		}
	}

	/**
	 * Returns a clean copy of the input field.
	 *
	 * @method
	 *
	 * @param {object} $node jQuery node to be copied
	 *
	 * @return {object} Copied jQuery node
	 */
	XHtml5FormElement.prototype._get_cleared_new_input = function($node) {
		var new_input = '<input ';

		var node_attribute_name;
		var node_value;

		for (var i = 0; i < NEW_INPUT_ATTRIBUTES_COPIED.length; i++) {
			node_attribute_name = NEW_INPUT_ATTRIBUTES_COPIED[i];

			node_value = $node.attr(node_attribute_name);
			if (node_value !== undefined) { new_input += " " + node_attribute_name + "=\"" + node_value + "\""; }
		}

		new_input += '></input>';
		var _return = $(new_input);

		node_value = $node.data();
		if (node_value !== undefined) { _return.data(node_value); }

		return _return;
	}

	/**
	 * Returns (X)HTML code with details about a given file.
	 *
	 * @method
	 *
	 * @param {object} file_data File data
	 *
	 * @return {string} (X)HTML code with file details
	 */
	XHtml5FormElement.prototype._get_file_input_details = function(file_data) {
		var _return = file_data.name;

		if ('size' in file_data) {
			_return += " (" + file_data.size + " B)";
		}

		return _return;
	}

	/**
	 * Initializes file input fields.
	 *
	 * @method
	 */
	XHtml5FormElement.prototype._init_file_input = function() {
		var _this = this;

		this.$node.on('change', function(event) {
			_this.on_file_input_selected(event);
		});
	}

	/**
	 * Event listener for deselecting a file upload.
	 *
	 * @method
	 *
	 * @param {object} event Event triggering deselection
	 * @param {object} $selected_file_wrapper File upload wrapper to be removed
	 */
	XHtml5FormElement.prototype.on_file_input_deselected = function(event, $selected_file_wrapper) {
		if (this.$node.attr('multiple') === undefined) {
			var $old_node = this.$node;
			this.$node = this._get_cleared_new_input($old_node);
			$old_node.remove();

			$selected_file_wrapper.after(this.$node);
			$selected_file_wrapper.remove();

			this.$node.css('display', 'initial');
			this._init_file_input();
		} else {
			$selected_file_wrapper.remove();
		}
	}

	/**
	 * Event listener for selecting a file upload.
	 *
	 * @method
	 *
	 * @param {object} event Event triggering selection
	 */
	XHtml5FormElement.prototype.on_file_input_selected = function(event) {
		if ('files' in event.target && event.target.files.length > 0) {
			var selected_file_wrapper = "

";
			var selected_files = event.target.files;

			this.$node.wrap(selected_file_wrapper);
			var $selected_file_wrapper = this.$node.parent();

			this.$node.css('display', 'none');

			if (selected_files.length == 1) {
				$selected_file_wrapper.append("" + this._get_file_input_details(selected_files[0]) + "");
			} else {
				var $selected_files_list = $('

');

				for (var i = 0; i < selected_files.length; i++) {
					$selected_files_list.append('
' + this._get_file_input_details(selected_files[i]) + '
');
				}

				$selected_file_wrapper.append($selected_files_list);
			}

			if (this.$node.attr('multiple') !== undefined) {
				var $old_node = this.$node;
				this.$node = this._get_cleared_new_input($old_node);
				$old_node.removeAttr('id');
				$old_node.removeAttr('tabindex');

				$selected_file_wrapper.after(this.$node);

				this.$node.css('display', 'initial');
				this._init_file_input();
			}

			var _this = this;

			Hammer($selected_file_wrapper.get(0)).on('tap', function(event) {
				_this.on_file_input_deselected(event, $selected_file_wrapper);
			});
		}
	}

	/**
	 * Event listener for focusing an input field.
	 *
	 * @method
	 *
	 * @param {number} duration Duration to temporarily apply the focused CSS class
	 */
	XHtml5FormElement.prototype.on_focus = function(duration) {
		if (duration === undefined) {
			duration = this.focused_duration;
		}

		if (this.$node.addClass(this.focused_class) != null) {
			var _this = this;

			var unfocus_callback = function() {
				$("#" + _this.id).removeClass(_this.focused_class);
			};

			if (duration > 0) {
				self.setTimeout(unfocus_callback, duration);
			} else {
				this.$node.one('focusout', unfocus_callback);
			}
		}
	}

	/**
	 * Applies the next "tabindex" number to the input field.
	 *
	 * @method
	 */
	XHtml5FormElement.prototype.propagate_tabindex = function() {
		if (this.$node.attr('tabindex') === undefined) {
			this.$node.attr('tabindex', tabindex_count);
			tabindex_count += 1;
		}
	}

	/**
	 * Sets the focused CSS class used.
	 *
	 * @method
	 *
	 * @param {string} class_name CSS class name
	 */
	XHtml5FormElement.prototype.set_focused_class = function(class_name) {
		this.focused_class = class_name;
	}

	/**
	 * Sets the duration the focused CSS class is applied temporarily.
	 *
	 * @method
	 *
	 * @param {duration} duration Duration to temporarily apply the focused CSS
	 *        class
	 */
	XHtml5FormElement.prototype.set_focused_duration = function(duration) {
		this.focused_duration = duration;
	}

	/**
	 * Sets the duration the input field will be disabled temporarily.
	 *
	 * @method
	 *
	 * @param {duration} duration Duration to temporarily disable the input field
	 */
	XHtml5FormElement.prototype.set_temporarily_disabled_duration = function(duration) {
		this.temporarily_disabled_duration = duration;
	}

	return XHtml5FormElement;
});

//j// EOF<|endoftext|>


<commit_before>define(['app/shared/router', 'knockout', 'crossroads', 'hasher'], function(router, ko, crossroads, hasher) {
    'use strict';

    function ViewContainer() {
        this.component = ko.observable();

        var redirectCount = 1,
            maxRedirect = 10;

        crossroads.routed.add(function(location, data) {
            var $routeInfo = data.route.$definition,
                routeParams = {};

            // Clear current view
            this.component(undefined);

            data.route._paramsIds.forEach(function(paramId, index) {
                if (data.params[index] !== undefined) {
                    routeParams[paramId] = data.params[index];
                }
            });

            if ($routeInfo.redirectTo) {
                redirectCount++;

                if (redirectCount > maxRedirect) {
                    redirectCount = 1;
                    throw new Error('Maximum redirection count reached.');
                }
                hasher.replaceHash($routeInfo.redirectTo);
                return;
            }

            var componentInfo = {
                name: $routeInfo.$component
            };

            redirectCount = 1;

            if (!componentInfo.name) {
                if ($routeInfo.template) {
                    componentInfo.template = $routeInfo.template;
                }
                else if ($routeInfo.templateUrl) {
                    componentInfo.template = { require: $routeInfo.templateUrl };
                }

                if ($routeInfo.viewModel) {
                    switch (typeof $routeInfo.viewModel) {
                        case 'function':
                            componentInfo.viewModel = $routeInfo.viewModel;
                            break;

                        case 'string':
                            componentInfo.viewModel = { require: $routeInfo.viewModelUrl };
                            break;
                    }
                }
                else if ($routeInfo.viewModelUrl) {
                    componentInfo.viewModel = { require: $routeInfo.viewModelUrl };
                }

                if (!componentInfo.name) {
                    componentInfo.name = $routeInfo.$component = 'c' + (+new Date());
                    ko.components.register(componentInfo.name, componentInfo);
                }
            }

            this.component({ name: componentInfo.name, params: routeParams });
        }, this);

        crossroads.bypassed.add(function(location) {
            if (router._missingRouteOptions) {
                this.component(undefined);
                hasher.replaceHash(router._missingRouteOptions.redirectTo);
            }
        }, this);

        hasher.init();
    }

    return {
        viewModel: ViewContainer,
        template: '

'
    };
});
<commit_msg>feat($router): simplify a bit route definition<commit_after>define(['app/shared/router', 'knockout', 'crossroads', 'hasher'], function(router, ko, crossroads, hasher) {
    'use strict';

    function ViewContainer() {
        this.component = ko.observable();

        var redirectCount = 1,
            maxRedirect = 10;

        crossroads.routed.add(function(location, data) {
            var $routeInfo = data.route.$definition,
                routeParams = {};

            // Clear current view
            this.component(undefined);

            data.route._paramsIds.forEach(function(paramId, index) {
                if (data.params[index] !== undefined) {
                    routeParams[paramId] = data.params[index];
                }
            });

            if ($routeInfo.redirectTo) {
                redirectCount++;

                if (redirectCount > maxRedirect) {
                    redirectCount = 1;
                    throw new Error('Maximum redirection count reached.');
                }
                hasher.replaceHash($routeInfo.redirectTo);
                return;
            }

            var componentInfo = {
                name: $routeInfo.$component
            };

            redirectCount = 1;

            if (!componentInfo.name) {
                if ($routeInfo.template) {
                    componentInfo.template = $routeInfo.template;
                }
                else if ($routeInfo.templateUrl) {
                    componentInfo.template = { require: $routeInfo.templateUrl };
                }

                if ($routeInfo.viewModel) {
                    componentInfo.viewModel = $routeInfo.viewModel;
                }
                else if ($routeInfo.viewModelUrl) {
                    componentInfo.viewModel = { require: $routeInfo.viewModelUrl };
                }

                if (!componentInfo.name) {
                    componentInfo.name = $routeInfo.$component = 'c' + (+new Date());
                    ko.components.register(componentInfo.name, componentInfo);
                }
            }

            this.component({ name: componentInfo.name, params: routeParams });
        }, this);

        crossroads.bypassed.add(function(location) {
            if (router._missingRouteOptions) {
                this.component(undefined);
                hasher.replaceHash(router._missingRouteOptions.redirectTo);
            }
        }, this);

        hasher.init();
    }

    return {
        viewModel: ViewContainer,
        template: '

'
    };
});
<|endoftext|>


<commit_before>
require( [ 'jquery', 'ip-subnet-calculator' ],

function( $, IpSubnetCalculator )
{
	'use strict';

	var showResult = function( elementName, msg )
	{
		$( '#' + elementName ).html( msg );
		$( '#' + elementName ).slideDown( 'fast' );
	};

	$( '#ip_calculate_range_button' ).click(
			function()
			{
				var result = IpSubnetCalculator.calculate(
						$( '#ip_calculate_range_start_ip' ).val(),
						$( '#ip_calculate_range_end_ip' ).val()
					);

				if( result === null )
				{
					showResult( 'ip_calculate_range_result', 'Please enter IP range in the fields above' );
				}
				else
				{
					var i;
					var msg = '
Result
' +
								'
' +
								'

IP	Prefix	Subnet Mask

' +
								'

IP	Prefix	Subnet Mask

';

					for( i = 0; i < result.length; i++ )
					{
						msg += '
' +
									'' + result[ i ].ipLowStr + '	' +
									'' + '/' + result[ i ].prefixSize + '	' +
									'' + result[ i ].prefixMaskStr + '	' +
									"
\n";
					}

					msg += "

\n";

					showResult( 'ip_calculate_range_result', msg );
				}
			}
		);

	$( '#ip_calculate_cidr_mask_button' ).click(
			function()
			{
				var result = IpSubnetCalculator.calculateSubnetMask(
						$( '#ip_calculate_cidr_mask_ip' ).val(),
						$( '#ip_calculate_cidr_mask_mask' ).val()
					);

				if( result === null )
				{
					showResult( 'ip_calculate_cidr_mask_result', 'Please enter IP range in the fields above' );
				}
				else
				{
					var msg = '
Result
' +
								'
' +
								'

Address Range	Subnet Mask	Prefix Size

' +
								'
' +
								'
' +
									'' + result.ipLowStr + ' - ' + result.ipHighStr + '	' +
									'' + result.prefixMaskStr + '	' +
									'' + result.prefixSize + '	' +
								'
' +
								'

';

					showResult( 'ip_calculate_cidr_mask_result', msg );
				}
			}
		);

	$( '#ip_calculate_mask_button' ).click(
			function()
			{
				var result = IpSubnetCalculator.calculateCIDRPrefix(
						$( '#ip_calculate_mask_ip' ).val(),
						$( '#ip_calculate_mask_mask' ).val()
					);

				if( result === null )
				{
					showResult( 'ip_calculate_mask_result', 'Please enter IP range in the fields above' );
				}
				else
				{
					var msg = '
Result
' +
								'
' +
								'

Address Range	Subnet Mask	Prefix Size

' +
								'
' +
								'
' +
									'' + result.ipLowStr + ' - ' + result.ipHighStr + '	' +
									'' + result.prefixMaskStr + '	' +
									'' + result.prefixSize + '	' +
								'
' +
								'

';

					showResult( 'ip_calculate_mask_result', msg );
				}
			}
		);

} );

<commit_msg>updated<commit_after>
require( [ 'jquery', 'ip-subnet-calculator' ],

function( $, IpSubnetCalculator )
{
	'use strict';

	var showResult = function( elementName, msg )
	{
		$( '#' + elementName ).html( msg );
		$( '#' + elementName ).slideDown( 'fast' );
	};

	$( '#ip_calculate_range_button' ).click(
			function()
			{
				var result = IpSubnetCalculator.calculate(
						$( '#ip_calculate_range_start_ip' ).val(),
						$( '#ip_calculate_range_end_ip' ).val()
					);

				if( result === null )
				{
					showResult( 'ip_calculate_range_result', 'Please enter IP range in the fields above' );
				}
				else
				{
					var i;
					var msg = '
Resultat
' +
								'
' +
								'

IP	Préfixe	Masque de sous-réseau

' +
								'

IP	Préfixe	Masque de sous-réseau

';

					for( i = 0; i < result.length; i++ )
					{
						msg += '
' +
									'' + result[ i ].ipLowStr + '	' +
									'' + '/' + result[ i ].prefixSize + '	' +
									'' + result[ i ].prefixMaskStr + '	' +
									"
\n";
					}

					msg += "

\n";

					showResult( 'ip_calculate_range_result', msg );
				}
			}
		);

	$( '#ip_calculate_cidr_mask_button' ).click(
			function()
			{
				var result = IpSubnetCalculator.calculateSubnetMask(
						$( '#ip_calculate_cidr_mask_ip' ).val(),
						$( '#ip_calculate_cidr_mask_mask' ).val()
					);

				if( result === null )
				{
					showResult( 'ip_calculate_cidr_mask_result', 'Please enter IP range in the fields above' );
				}
				else
				{
					var msg = '
Resultat
' +
								'
' +
								'

Plage d' adresses	Masque de sous-réseau	Taille de préfixe

' +
								'
' +
								'
' +
									'' + result.ipLowStr + ' - ' + result.ipHighStr + '	' +
									'' + result.prefixMaskStr + '	' +
									'' + result.prefixSize + '	' +
								'
' +
								'

';

					showResult( 'ip_calculate_cidr_mask_result', msg );
				}
			}
		);

	$( '#ip_calculate_mask_button' ).click(
			function()
			{
				var result = IpSubnetCalculator.calculateCIDRPrefix(
						$( '#ip_calculate_mask_ip' ).val(),
						$( '#ip_calculate_mask_mask' ).val()
					);

				if( result === null )
				{
					showResult( 'ip_calculate_mask_result', 'Please enter IP range in the fields above' );
				}
				else
				{
					var msg = '
Resultat
' +
								'
' +
								'

Plage d' adresses	Masque de sous-réseau	Taille de préfixe

' +
								'
' +
								'
' +
									'' + result.ipLowStr + ' - ' + result.ipHighStr + '	' +
									'' + result.prefixMaskStr + '	' +
									'' + result.prefixSize + '	' +
								'
' +
								'

';

					showResult( 'ip_calculate_mask_result', msg );
				}
			}
		);

} );
<|endoftext|>


<commit_before>define(
  'ephox.alloy.construct.ComponentDom',

  [
    'ephox.alloy.dom.DomModification',
    'ephox.alloy.util.ObjIndex',
    'ephox.alloy.util.PrioritySort',
    'ephox.boulder.api.Objects',
    'ephox.compass.Arr',
    'ephox.compass.Obj',
    'ephox.numerosity.api.JSON',
    'ephox.peanut.Fun',
    'ephox.perhaps.Option',
    'ephox.perhaps.Options',
    'ephox.perhaps.Result'
  ],

  function (DomModification, ObjIndex, PrioritySort, Objects, Arr, Obj, Json, Fun, Option, Options, Result) {
    var behaviourDom = function (name, modification) {
      return {
        name: Fun.constant(name),
        modification: modification
      };
    };

    var anyOrderConcat = function (chain, aspect) {
      console.log('chain', chain);
      var values = Arr.bind(chain, function (c) {
        return c.modification().getOr([ ]);
      });
      var x = Result.value(
        Objects.wrap(aspect, values)
      );
      console.log('x', values);
      return x;
    };

    var onlyOne = function (chain, aspect, order) {
      console.log('chain', chain);
      if (chain.length > 1) return Result.error('Only one can specify');
      else if (chain.length === 0) return  Result.value({ });
      else return Result.value(
        chain[0].modification().fold(function () {
          return { };
        }, function (m) {
          return Objects.wrap(aspect, m);
        })
      );
    };

    var mergeInOrder = function (chain, aspect) {
      var y = Arr.foldl(chain, function (acc, c) {
        var obj = c.modification().getOr({});
        return acc.bind(function (accRest) {
          console.log('accRest', accRest);

          var ps = Obj.mapToArray(obj, function (v, k) {
            return accRest[k] !== undefined ? Result.error('Duplicate: ' + k) :
              Result.value(Objects.wrap(k, v));
          });
          console.log("ps", ps);

          return Objects.consolidate(ps, accRest);
        });
      }, Result.value({}));

      return y.map(function (yValue) {
        console.log('y.log', yValue);
        return Objects.wrap(aspect, yValue);
      });
    };

    var mergeTypes = {
      classes: anyOrderConcat,
      attributes: mergeInOrder,
      styles: mergeInOrder,

      // Group these together somehow
      domChildren: onlyOne,
      defChildren: onlyOne,
      innerHtml: onlyOne,

      value: onlyOne
    };

    var combine = function (info, behaviours, base) {
      // Get the Behaviour DOM modifications
      var behaviourDoms = { };
      Arr.each(behaviours, function (behaviour) {
        behaviourDoms[behaviour.name()] = behaviour.exhibit(info, base);
      });

      console.log('behaviourDoms', behaviourDoms);
      var byAspect = ObjIndex.byInnerKey(behaviourDoms, behaviourDom);

      console.log('byAspect', byAspect);

      var usedAspect = Obj.map(byAspect, function (values, aspect) {
        return Arr.bind(values, function (value) {
          return value.modification().fold(function () {
            return [ ];
          }, function (v) {
            return [ value ];
          });
        });
      });

      console.log('usedAspect', usedAspect);

      // Now, with all of these APIs, we need to get a list of behaviours

      // Now, with this API index, we need to combine things. Sort them in order.
      var modifications = Obj.mapToArray(usedAspect, function (values, aspect) {
        // TODO: Use hasOwnProperty.
        if (mergeTypes[aspect] !== undefined) return mergeTypes[aspect](values, aspect);
        else return Result.error('Unknown field type: ' + aspect);
      });

      var consolidated = Objects.consolidate(modifications, {});
      console.log('consolidated', consolidated.getOr('<none>'));
      return consolidated.map(DomModification.nu);
    };

    return {
      combine: combine
    };
  }
);<commit_msg>VAN-1: slight cleanup<commit_after>define(
  'ephox.alloy.construct.ComponentDom',

  [
    'ephox.alloy.dom.DomModification',
    'ephox.alloy.util.ObjIndex',
    'ephox.alloy.util.PrioritySort',
    'ephox.boulder.api.Objects',
    'ephox.compass.Arr',
    'ephox.compass.Obj',
    'ephox.numerosity.api.JSON',
    'ephox.peanut.Fun',
    'ephox.perhaps.Option',
    'ephox.perhaps.Options',
    'ephox.perhaps.Result'
  ],

  function (DomModification, ObjIndex, PrioritySort, Objects, Arr, Obj, Json, Fun, Option, Options, Result) {
    var behaviourDom = function (name, modification) {
      return {
        name: Fun.constant(name),
        modification: modification
      };
    };

    var anyOrderConcat = function (chain, aspect) {
      console.log('chain', chain);
      var values = Arr.bind(chain, function (c) {
        return c.modification().getOr([ ]);
      });
      var x = Result.value(
        Objects.wrap(aspect, values)
      );
      console.log('x', values);
      return x;
    };

    var onlyOne = function (chain, aspect, order) {
      console.log('chain', chain);
      if (chain.length > 1) return Result.error('Only one can specify');
      else if (chain.length === 0) return  Result.value({ });
      else return Result.value(
        chain[0].modification().fold(function () {
          return { };
        }, function (m) {
          return Objects.wrap(aspect, m);
        })
      );
    };

    var mergeInOrder = function (chain, aspect) {
      var y = Arr.foldl(chain, function (acc, c) {
        var obj = c.modification().getOr({});
        return acc.bind(function (accRest) {
          console.log('accRest', accRest);

          var ps = Obj.mapToArray(obj, function (v, k) {
            return accRest[k] !== undefined ? Result.error('Duplicate: ' + k) :
              Result.value(Objects.wrap(k, v));
          });
          console.log("ps", ps);

          return Objects.consolidate(ps, accRest);
        });
      }, Result.value({}));

      return y.map(function (yValue) {
        console.log('y.log', yValue);
        return Objects.wrap(aspect, yValue);
      });
    };

    var mergeTypes = {
      classes: anyOrderConcat,
      attributes: mergeInOrder,
      styles: mergeInOrder,

      // Group these together somehow
      domChildren: onlyOne,
      defChildren: onlyOne,
      innerHtml: onlyOne,

      value: onlyOne
    };

    var combine = function (info, behaviours, base) {
      // Get the Behaviour DOM modifications
      var behaviourDoms = { };
      Arr.each(behaviours, function (behaviour) {
        behaviourDoms[behaviour.name()] = behaviour.exhibit(info, base);
      });

      var byAspect = ObjIndex.byInnerKey(behaviourDoms, behaviourDom);

      var usedAspect = Obj.map(byAspect, function (values, aspect) {
        return Arr.bind(values, function (value) {
          return value.modification().fold(function () {
            return [ ];
          }, function (v) {
            return [ value ];
          });
        });
      });

      var modifications = Obj.mapToArray(usedAspect, function (values, aspect) {
        // TODO: Use hasOwnProperty.
        return Objects.readOptFrom(mergeTypes, aspect).fold(function () {
          return Result.error('Unknown field type: ' + aspect);
        }, function (merger ){
          return merger(values, aspect);
        });
      });

      var consolidated = Objects.consolidate(modifications, {});
      return consolidated.map(DomModification.nu);
    };

    return {
      combine: combine
    };
  }
);<|endoftext|>


<commit_before>(function(app) {
  'use strict';

  var helper = {};

  helper.randomString = function(len) {
    var s = [];
    for (var i = 0, n = Math.ceil(len / 7); i < n; i++) {
      s.push(Math.random().toString(36).slice(-7));
    }
    return s.join('').slice(-len);
  };

  helper.encodePath = function(str) {
    return str.split('/').map(function(s) {
      return encodeURIComponent(s);
    }).join('/');
  };

  helper.clamp = function(number, lower, upper) {
    return Math.min(Math.max(number, lower), upper);
  };

  helper.inherits = function(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true,
      },
    });
    return ctor;
  };

  helper.identity = function(value) {
    return value;
  };

  helper.equal = function(a, b) {
    if (a === b) {
      return true;
    }
    if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
      return (a === b);
    }
    var keys = Object.keys(a);
    if (keys.length !== Object.keys(b).length) {
      return false;
    }
    return keys.every(function(key) {
      return (b.hasOwnProperty(key) && helper.equal(a[key], b[key]));
    });
  };

  helper.toArray = function(value) {
    return Array.prototype.slice.call(value);
  };

  helper.extend = function(obj, src) {
    Object.keys(src).forEach(function(key) {
      obj[key] = src[key];
    });
    return obj;
  };

  helper.clone = function(obj) {
    return helper.extend({}, obj);
  };

  helper.pick = function(obj, keys) {
    return keys.reduce(function(ret, key) {
      if (obj.hasOwnProperty(key)) {
        ret[key] = obj[key];
      }
      return ret;
    }, {});
  };

  helper.dig = function() {
    return helper.toArray(arguments).reduce(function(obj, key) {
      return (typeof obj === 'object') ? obj[key] : null;
    });
  };

  helper.sortBy = function(array, iteratee) {
    var isCallback = (typeof iteratee === 'function');
    return array.sort(function(a, b) {
      var l = (isCallback ? iteratee(a) : a[iteratee]);
      var r = (isCallback ? iteratee(b) : b[iteratee]);
      if (l < r) {
        return -1;
      }
      if (l > r) {
        return 1;
      }
      return 0;
    });
  };

  helper.removeAt = function(array, index) {
    if (index < 0 || index >= array.length) {
      throw new RangeError('Invalid index');
    }
    array.splice(index, 1);
  };

  helper.remove = function(array, item) {
    helper.removeAt(array, array.indexOf(item));
  };

  helper.moveToBack = function(array, item) {
    helper.remove(array, item);
    array.push(item);
  };

  helper.findIndex = function(array, callback) {
    for (var i = 0, len = array.length; i < len; i++) {
      if (callback(array[i], i, array)) {
        return i;
      }
    }
    return -1;
  };

  helper.findLastIndex = function(array, callback) {
    for (var i = array.length - 1; i >= 0; i--) {
      if (callback(array[i], i, array)) {
        return i;
      }
    }
    return -1;
  };

  helper.find = function(array, callback) {
    var index = helper.findIndex(array, callback);
    return (index !== -1 ? array[index] : null);
  };

  helper.findLast = function(array, callback) {
    var index = helper.findLastIndex(array, callback);
    return (index !== -1 ? array[index] : null);
  };

  helper.flatten = function(array) {
    return Array.prototype.concat.apply([], array);
  };

  helper.wrapper = function() {
    var Wrapper = function(self, wrapper) {
      return Object.defineProperty(wrapper, 'unwrap', {
        value: Wrapper.unwrap.bind(self),
      });
    };

    Wrapper.unwrap = function(key) {
      if (key === Wrapper.KEY) {
        return this;
      }
    };

    Wrapper.KEY = {};

    return Wrapper;
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = helper;
  } else {
    app.helper = helper;
  }
})(this.app || (this.app = {}));
<commit_msg>Refactor 'Wrapper.unwrap' method<commit_after>(function(app) {
  'use strict';

  var helper = {};

  helper.randomString = function(len) {
    var s = [];
    for (var i = 0, n = Math.ceil(len / 7); i < n; i++) {
      s.push(Math.random().toString(36).slice(-7));
    }
    return s.join('').slice(-len);
  };

  helper.encodePath = function(str) {
    return str.split('/').map(function(s) {
      return encodeURIComponent(s);
    }).join('/');
  };

  helper.clamp = function(number, lower, upper) {
    return Math.min(Math.max(number, lower), upper);
  };

  helper.inherits = function(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true,
      },
    });
    return ctor;
  };

  helper.identity = function(value) {
    return value;
  };

  helper.equal = function(a, b) {
    if (a === b) {
      return true;
    }
    if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
      return (a === b);
    }
    var keys = Object.keys(a);
    if (keys.length !== Object.keys(b).length) {
      return false;
    }
    return keys.every(function(key) {
      return (b.hasOwnProperty(key) && helper.equal(a[key], b[key]));
    });
  };

  helper.toArray = function(value) {
    return Array.prototype.slice.call(value);
  };

  helper.extend = function(obj, src) {
    Object.keys(src).forEach(function(key) {
      obj[key] = src[key];
    });
    return obj;
  };

  helper.clone = function(obj) {
    return helper.extend({}, obj);
  };

  helper.pick = function(obj, keys) {
    return keys.reduce(function(ret, key) {
      if (obj.hasOwnProperty(key)) {
        ret[key] = obj[key];
      }
      return ret;
    }, {});
  };

  helper.dig = function() {
    return helper.toArray(arguments).reduce(function(obj, key) {
      return (typeof obj === 'object') ? obj[key] : null;
    });
  };

  helper.sortBy = function(array, iteratee) {
    var isCallback = (typeof iteratee === 'function');
    return array.sort(function(a, b) {
      var l = (isCallback ? iteratee(a) : a[iteratee]);
      var r = (isCallback ? iteratee(b) : b[iteratee]);
      if (l < r) {
        return -1;
      }
      if (l > r) {
        return 1;
      }
      return 0;
    });
  };

  helper.removeAt = function(array, index) {
    if (index < 0 || index >= array.length) {
      throw new RangeError('Invalid index');
    }
    array.splice(index, 1);
  };

  helper.remove = function(array, item) {
    helper.removeAt(array, array.indexOf(item));
  };

  helper.moveToBack = function(array, item) {
    helper.remove(array, item);
    array.push(item);
  };

  helper.findIndex = function(array, callback) {
    for (var i = 0, len = array.length; i < len; i++) {
      if (callback(array[i], i, array)) {
        return i;
      }
    }
    return -1;
  };

  helper.findLastIndex = function(array, callback) {
    for (var i = array.length - 1; i >= 0; i--) {
      if (callback(array[i], i, array)) {
        return i;
      }
    }
    return -1;
  };

  helper.find = function(array, callback) {
    var index = helper.findIndex(array, callback);
    return (index !== -1 ? array[index] : null);
  };

  helper.findLast = function(array, callback) {
    var index = helper.findLastIndex(array, callback);
    return (index !== -1 ? array[index] : null);
  };

  helper.flatten = function(array) {
    return Array.prototype.concat.apply([], array);
  };

  helper.wrapper = function() {
    var Wrapper = function(self, wrapper) {
      return Object.defineProperty(wrapper, 'unwrap', {
        value: Wrapper.unwrap.bind(self),
      });
    };

    Wrapper.unwrap = function(key) {
      return (key === Wrapper.KEY) ? this : null;
    };

    Wrapper.KEY = {};

    return Wrapper;
  };

  if (typeof module !== 'undefined' && module.exports) {
    module.exports = helper;
  } else {
    app.helper = helper;
  }
})(this.app || (this.app = {}));
<|endoftext|>


<commit_before>function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function parse()
{
   var lines = document.getElementById('deckIn').value.split('\n');

   var target = "";
   var badLine = false;

   for(var i = 0;i < lines.length;i++){

   	  if (lines[i].includes("on -"))
   	  {
      		target = "pokemon";
      		badLine = true;
   	  }
   	  else if (lines[i].includes("Trainer Cards -"))
   	  {
   	  		target = "trainers"
   	  		badLine = true;
   	  }
   	  else if (lines[i].includes("Energy -"))
   	  {
   	  		target = "energy"
   	  		badLine = true;
   	  }
   	  else if (lines[i].includes("Total Cards"))
   	  {
   	  		badLine = true;
   	  }
   	  else
   	  	badLine = false;

      if (lines[i][0] != '*' && lines[i] != "" && !badLine)
      {
      	var num = lines[i][0];
      	var j;
      	lines[i] = lines[i].slice(2);

      	for (j = 0; j < num; j++)
      	{
      		deck.push(lines[i]);

      		if (target == "pokemon")
      			pokemon.push(lines[i]);
      		else if (target == "trainers")
      			trainers.push(lines[i]);
      		else if (target == "energy")
      			energy.push(lines[i]);
      	}
	  }
   }
   deck = shuffle(deck);
   document.getElementById("sometext").innerHTML = deck;
}
<commit_msg>huge updates<commit_after>function parse()
{
   var lines = document.getElementById('deckIn').value.split('\n');

   var target = "";
   var badLine = false;

   var totalCount = 0;

   for(var i = 0;i < lines.length;i++){

   	  if (lines[i].includes("on -"))
   	  {
      		target = "pokemon";
      		badLine = true;
   	  }
   	  else if (lines[i].includes("Trainer Cards -"))
   	  {
   	  		target = "trainers"
   	  		badLine = true;
   	  }
   	  else if (lines[i].includes("Energy -"))
   	  {
   	  		target = "energy"
   	  		badLine = true;
   	  }
   	  else if (lines[i].includes("Total Cards"))
   	  {
   	  		badLine = true;
   	  }
   	  else
   	  	badLine = false;

      if (lines[i][0] != '*' && lines[i] != "" && !badLine)
      {
      	var num = lines[i].substr(0, lines[i].indexOf(' '));
      	var j;
      	lines[i] = lines[i].slice(2);

      	for (j = 0; j < num; j++)
      	{
      		if (target == "pokemon")
      			var tempCard = new card(lines[i], "pokemon");
      		else if (target == "trainers")
      			var tempCard = new card(lines[i], "trainer");
      		else if (target == "energy")
      			var tempCard = new card(lines[i], "energy");

          totalCount++;
          deck.push(tempCard);
      	}
	  }
   }
   deck = shuffle(deck);
   document.getElementById("sometext").innerHTML = deck[i].recallName() + " " + deck[i].recallType();
}
<|endoftext|>