<commit_before>/*
 * Author: Ondřej Vodáček <ondrej.vodacek@gmail.com>
 * License: New BSD License
 *
 * Copyright (c) 2011, Ondřej Vodáček
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Ondřej Vodáček nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Ondřej Vodáček BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Sources:
 * http://stackoverflow.com/questions/2208480/jquery-date-picker-to-show-month-year-only
 * http://stackoverflow.com/questions/2224135/can-i-highlight-an-entire-week-in-the-standard-jquery-ui-date-picker
 * http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
 */
(function($) {
	/***************************************************************************
	 * override datepicker formatDate method for week formating support
	 **************************************************************************/
	var proxied = $.datepicker.formatDate;
	$.datepicker.formatDate = function(format, date, settings) {
		// mostly from jquery.ui.datepicker.js
		if (!date)
			return '';

		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		var calculateWeek = (settings ? settings.calculateWeek : null) || this._defaults.calculateWeek;
		var output = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) == "'") {
					literal = false;
				}
				output += format.charAt(iFormat);
			} else {
				switch (format.charAt(iFormat)) {
					case 'w':
						output += formatNumber('w', calculateWeek(date), 2);
						break;
					case "'":
						output += "'";
						literal = true;
						break;
					default:
						output += format.charAt(iFormat);
				}
			}
		};
		arguments[0] = output;
		return proxied.apply(this, arguments);
	}
	/***************************************************************************
	 * date parsing functions
	 **************************************************************************/
	var parseWeek = function(date) {
		// 2011-W05
		if (date.length  != 8) {
			return null;
		}
		var year = parseInt(date.substr(0,4), 10);
		var week = parseInt(date.substr(6,2), 10);

		var correctionDate = new Date(year, 0, 4);
		var correction = correctionDate.getDay();
		if (correction == 0) {
			correction = 7;
		}
		correction += 3;
		// let the Date object do the math for calculating the correct month and day
		var day = new Date(year, 0, (week * 7) + 1 - correction);
		return day;
	}
	var parseTime = function(time) {
		// 12:12[:12]
		if (time.length < 5) {
			return null;
		}
		var d = new Date();
		d.setHours(
			parseInt(time.substr(0, 2), 10), //hour
			parseInt(time.substr(3, 2), 10), //minute
			(time.lengt >= 8) ? parseInt(time.substr(6, 2), 10) : 0 //second
			);
		return d;
	}
	var parseDate = function(datetime) {
		// 2011-05-08
		if (datetime.length < 10) {
			return null;
		}
		return new Date(
			parseInt(datetime.substr(0, 4), 10), //year
			parseInt(datetime.substr(5, 2), 10) - 1, //month
			parseInt(datetime.substr(8, 2), 10) //day
			);
	}
	var parseDateTime = function(datetime) {
		// 2011-05-08T12:12[:12]
		if (datetime.length < 19) {
			return null;
		}
		var date = parseDate(datetime)
		var time = parseTime(datetime.substr(11));
		date.setHours(
			time.getHours(),
			time.getMinutes(),
			time.getSeconds()
			);
		return date;
	}
	var parseMonth = function(date) {
		// 2011-05
		return parseDate(date + '-01');
	}
	var globalSettings = {
		datetime: {
			parseFunction: parseDateTime,
			create: function(object, settings) {
				return object.datetimepicker(settings);
			},
			dateFormat: 'yy-mm-dd',
			timeFormat: 'HH:mm',
			validFormat: '\\d{4}-\\d{2}-\\d{2}'
		},
		date: {
			parseFunction: parseDate,
			create: function(object, settings) {
				return object.datepicker(settings);
			},
			dateFormat: 'yy-mm-dd',
			validFormat: '\\d{4}-\\d{2}-\\d{2}'
		},
		month: {
			parseFunction: parseMonth,
			create: function(object, settings) {
				return object.datepicker(settings);
			},
			dateFormat: 'yy-mm',
			validFormat: '\\d{4}-\\d{2}'
		},
		week: {
			parseFunction: parseWeek,
			create: function(object, settings) {
				return object.datepicker(settings);
			},
			dateFormat: 'yy-Www',
			validFormat: '\\d{4}-W\\d{2}'
		},
		time: {
			parseFunction: parseTime,
			create: function(object, settings) {
				return object.timepicker(settings);
			},
			timeFormat: 'HH:mm',
			validFormat: '\\d{2}:\\d{2}'
		}
	};
	globalSettings['datetime-local'] = globalSettings.datetime;
	globalSettings['datetime-local'].validFormat += '.*'; // timezone

	$.fn.dateinput = function(userSettings) {
		this.each(function() {
			var t = $(this);
			if (t.data('altField')) {
				return;
			}
			var type = t.attr('data-dateinput-type');
			var settings = globalSettings[type];
			userSettings = userSettings || {};
			$.extend(settings, userSettings[type] || {});

			// create alt field
			this.type = 'text';
			var alt = t.clone().removeAttr('id');
			try {
				alt.get(0).type = 'hidden';
			} catch (exception) {
				// fix for: http://webbugtrack.blogspot.com/2007/09/bug-237-type-is-readonly-attribute-in.html
				alt = $(alt.get(0).outerHTML.replace(/ type=(['"]?)[a-z-]+\1/, ' type="hidden"'));
			}
			alt.attr('data-dateinput-type', null);
			t.removeAttr('name');
			t.val(null);
			t.after(alt);
			t.data('altField', alt);

			 var pickerSettings = {
				onClose: function(date, inst) {
					if (date === '') {
						alt.val('');
					}
				}
			};

			// min and max date
			var min = alt.attr('min');
			if (min) {
				pickerSettings['minDate'] = settings.parseFunction(min);
			}
			var max = alt.attr('max');
			if (max) {
				pickerSettings['maxDate'] = settings.parseFunction(max);
			}
			var selectedDate = null;
			var date = alt.val();
			if (date) {
				selectedDate = settings.parseFunction(date);
			}
			if (settings.dateFormat) {
				pickerSettings.dateFormat = settings.dateFormat;
			}
			if (settings.timeFormat) {
				pickerSettings.timeFormat = settings.timeFormat;
				pickerSettings.pickerTimeFormat = settings.timeFormat;
			}

			//
			switch (type) {
				case 'datetime':
				case 'datetime-local':
					$.extend(pickerSettings, {
						altFieldTimeOnly: false,
						altField: alt,
						altFormat: 'yy-mm-dd',
						altSeparator: 'T',
						altTimeFormat: 'HH:mm:ss',
						altTimeSuffix: type === 'datetime' ? 'Z' : '',
						stepHour: 1,
						stepMinute: 1,
						showButtonPanel: true
					});
					break;
				case 'date':
					$.extend(pickerSettings, {
						altField: alt,
						altFormat: 'yy-mm-dd',
						showButtonPanel: true,
						showOtherMonths: true
					});
					break;
				case 'month':
					$.extend(pickerSettings, {
						altField: alt,
						altFormat: 'yy-mm',
						showButtonPanel: true,
						showOtherMonths: true,
						beforeShow: function(input, inst) {
							if (selectedDate) {
								$(this).datepicker('option', 'defaultDate', selectedDate);
								$(this).datepicker('setDate', selectedDate);
							}
						},
						beforeShowDay: function(day) {
							var c = 'ui-datepicker-month';
							if (selectedDate && selectedDate.getFullYear() == day.getFullYear() && selectedDate.getMonth() == day.getMonth()) {
								c += ' ui-datepicker-month-selected';
							}
							var now = new Date();
							if (day.getFullYear() == now.getFullYear() && day.getMonth() == now.getMonth()) {
								c += ' ui-datepicker-month-current';
							}
							return [true, c];
						},
						onSelect: function(day, inst) {
							selectedDate = new Date(inst.selectedYear, inst.selectedMonth, 1);
							t.datepicker('setDate', selectedDate);
							inst.input.blur();
						}
					});
					if (pickerSettings['maxDate']) {
						pickerSettings['maxDate'].setMonth(pickerSettings['maxDate'].getMonth() + 1, 0);
					}
					break;
				case 'week':
					$.extend(pickerSettings, {
						altField: alt,
						altFormat: 'yy-Www',
						showButtonPanel: true,
						showOtherMonths: true,
						showWeek: true,
						beforeShow: function() {
							if (selectedDate) {
								t.datepicker('option', 'defaultDate', selectedDate);
								t.datepicker('setDate', selectedDate);
							}
						},
						beforeShowDay: function(day) {
							var c = 'ui-datepicker-week';
							if (selectedDate && $.datepicker.iso8601Week(selectedDate) == $.datepicker.iso8601Week(day) && selectedDate.getFullYear() == day.getFullYear()) {
								c += ' ui-datepicker-week-selected';
							}
							var now = new Date();
							if ($.datepicker.iso8601Week(day) == $.datepicker.iso8601Week(now) && day.getFullYear() == now.getFullYear()) {
								c += ' ui-datepicker-week-current';
							}
							return [true, c];
						},
						onSelect: function(day, inst) {
							selectedDate = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay);
							// move to monday
							selectedDate.setDate(selectedDate.getDate() - (selectedDate.getDay() + 6) % 7);
							t.datepicker('setDate', selectedDate);
							inst.input.blur();
						}
					});
					if (pickerSettings['maxDate']) {
						pickerSettings['maxDate'].setDate(pickerSettings['maxDate'].getDate() + 6); // move from monday to sunday
					}
					break;
				case 'time':
					$.extend(pickerSettings, {
						altFieldTimeOnly: false,
						altField: alt,
						altFormat: '',
						dateFormat: '',
						altSeparator: '',
						separator: '',
						altTimeFormat: 'HH:mm:ss',
						stepHour: 1,
						stepMinute: 1,
						showButtonPanel: true
					});
					break;
			}

			settings.create(t, pickerSettings);

			if (selectedDate) {
				t.datepicker('setDate', selectedDate);
			}
		});
		return this;
	};

	// Nette validators
	Nette.validators.dateInputValid = function(elem, arg, val) {
		var el = $(elem);
		var type = el.attr('data-dateinput-type');
		var format = globalSettings[type].validFormat;
		val = el.data('altField').val();
		return (new RegExp('^(' + format + ')$')).test(val);
	};
	Nette.validators.dateInputRange = function(elem, arg, val) {
		var el = $(elem);
		val = el.data('altField').val();
		return Nette.isArray(arg) ? ((arg[0] === null || val >= arg[0]) && (arg[1] === null || val <= arg[1])) : null;
	};
})(jQuery);
<commit_msg>fixed some jshint errors<commit_after>/*
 * Author: Ondřej Vodáček <ondrej.vodacek@gmail.com>
 * License: New BSD License
 *
 * Copyright (c) 2011, Ondřej Vodáček
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Ondřej Vodáček nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Ondřej Vodáček BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Sources:
 * http://stackoverflow.com/questions/2208480/jquery-date-picker-to-show-month-year-only
 * http://stackoverflow.com/questions/2224135/can-i-highlight-an-entire-week-in-the-standard-jquery-ui-date-picker
 * http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
 */
(function($, Nette) {
	"use strict";
	/***************************************************************************
	 * override datepicker formatDate method for week formating support
	 **************************************************************************/
	var proxied = $.datepicker.formatDate;
	$.datepicker.formatDate = function(format, date, settings) {
		// mostly from jquery.ui.datepicker.js
		if (!date) {
			return '';
		}

		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
			if (matches) {
				iFormat++;
			}
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match)) {
				while (num.length < len) {
					num = '0' + num;
				}
			}
			return num;
		};
		var calculateWeek = (settings ? settings.calculateWeek : null) || this._defaults.calculateWeek;
		var output = '';
		var literal = false;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) === "'") {
					literal = false;
				}
				output += format.charAt(iFormat);
			} else {
				switch (format.charAt(iFormat)) {
					case 'w':
						output += formatNumber('w', calculateWeek(date), 2);
						break;
					case "'":
						output += "'";
						literal = true;
						break;
					default:
						output += format.charAt(iFormat);
				}
			}
		}
		arguments[0] = output;
		return proxied.apply(this, arguments);
	};
	/* *************************************************************************
	 * date parsing functions
	 **************************************************************************/
	var parseWeek = function(date) {
		// 2011-W05
		if (date.length  !== 8) {
			return null;
		}
		var year = parseInt(date.substr(0,4), 10);
		var week = parseInt(date.substr(6,2), 10);

		var correctionDate = new Date(year, 0, 4);
		var correction = correctionDate.getDay();
		if (correction === 0) {
			correction = 7;
		}
		correction += 3;
		// let the Date object do the math for calculating the correct month and day
		var day = new Date(year, 0, (week * 7) + 1 - correction);
		return day;
	};
	var parseTime = function(time) {
		// 12:12[:12]
		if (time.length < 5) {
			return null;
		}
		var d = new Date();
		d.setHours(
			parseInt(time.substr(0, 2), 10), //hour
			parseInt(time.substr(3, 2), 10), //minute
			(time.lengt >= 8) ? parseInt(time.substr(6, 2), 10) : 0 //second
			);
		return d;
	};
	var parseDate = function(datetime) {
		// 2011-05-08
		if (datetime.length < 10) {
			return null;
		}
		return new Date(
			parseInt(datetime.substr(0, 4), 10), //year
			parseInt(datetime.substr(5, 2), 10) - 1, //month
			parseInt(datetime.substr(8, 2), 10) //day
			);
	};
	var parseDateTime = function(datetime) {
		// 2011-05-08T12:12[:12]
		if (datetime.length < 19) {
			return null;
		}
		var date = parseDate(datetime);
		var time = parseTime(datetime.substr(11));
		date.setHours(
			time.getHours(),
			time.getMinutes(),
			time.getSeconds()
			);
		return date;
	};
	var parseMonth = function(date) {
		// 2011-05
		return parseDate(date + '-01');
	};
	var globalSettings = {
		datetime: {
			parseFunction: parseDateTime,
			create: function(object, settings) {
				return object.datetimepicker(settings);
			},
			dateFormat: 'yy-mm-dd',
			timeFormat: 'HH:mm',
			validFormat: '\\d{4}-\\d{2}-\\d{2}'
		},
		date: {
			parseFunction: parseDate,
			create: function(object, settings) {
				return object.datepicker(settings);
			},
			dateFormat: 'yy-mm-dd',
			validFormat: '\\d{4}-\\d{2}-\\d{2}'
		},
		month: {
			parseFunction: parseMonth,
			create: function(object, settings) {
				return object.datepicker(settings);
			},
			dateFormat: 'yy-mm',
			validFormat: '\\d{4}-\\d{2}'
		},
		week: {
			parseFunction: parseWeek,
			create: function(object, settings) {
				return object.datepicker(settings);
			},
			dateFormat: 'yy-Www',
			validFormat: '\\d{4}-W\\d{2}'
		},
		time: {
			parseFunction: parseTime,
			create: function(object, settings) {
				return object.timepicker(settings);
			},
			timeFormat: 'HH:mm',
			validFormat: '\\d{2}:\\d{2}'
		}
	};
	globalSettings['datetime-local'] = globalSettings.datetime;
	globalSettings['datetime-local'].validFormat += '.*'; // timezone

	$.fn.dateinput = function(userSettings) {
		this.each(function() {
			var t = $(this);
			if (t.data('altField')) {
				return;
			}
			var type = t.attr('data-dateinput-type');
			var settings = globalSettings[type];
			userSettings = userSettings || {};
			$.extend(settings, userSettings[type] || {});

			// create alt field
			this.type = 'text';
			var alt = t.clone().removeAttr('id');
			try {
				alt.get(0).type = 'hidden';
			} catch (exception) {
				// fix for: http://webbugtrack.blogspot.com/2007/09/bug-237-type-is-readonly-attribute-in.html
				alt = $(alt.get(0).outerHTML.replace(/ type=(['"]?)[a-z-]+\1/, ' type="hidden"'));
			}
			alt.attr('data-dateinput-type', null);
			t.removeAttr('name');
			t.val(null);
			t.after(alt);
			t.data('altField', alt);

			var pickerSettings = {
				onClose: function(date) {
					if (date === '') {
						alt.val('');
					}
				}
			};

			// min and max date
			var min = alt.attr('min');
			if (min) {
				pickerSettings.minDate = settings.parseFunction(min);
			}
			var max = alt.attr('max');
			if (max) {
				pickerSettings.maxDate = settings.parseFunction(max);
			}
			var selectedDate = null;
			var date = alt.val();
			if (date) {
				selectedDate = settings.parseFunction(date);
			}
			if (settings.dateFormat) {
				pickerSettings.dateFormat = settings.dateFormat;
			}
			if (settings.timeFormat) {
				pickerSettings.timeFormat = settings.timeFormat;
				pickerSettings.pickerTimeFormat = settings.timeFormat;
			}

			//
			switch (type) {
				case 'datetime':
				case 'datetime-local':
					$.extend(pickerSettings, {
						altFieldTimeOnly: false,
						altField: alt,
						altFormat: 'yy-mm-dd',
						altSeparator: 'T',
						altTimeFormat: 'HH:mm:ss',
						altTimeSuffix: type === 'datetime' ? 'Z' : '',
						stepHour: 1,
						stepMinute: 1,
						showButtonPanel: true
					});
					break;
				case 'date':
					$.extend(pickerSettings, {
						altField: alt,
						altFormat: 'yy-mm-dd',
						showButtonPanel: true,
						showOtherMonths: true
					});
					break;
				case 'month':
					$.extend(pickerSettings, {
						altField: alt,
						altFormat: 'yy-mm',
						showButtonPanel: true,
						showOtherMonths: true,
						beforeShow: function() {
							if (selectedDate) {
								$(this).datepicker('option', 'defaultDate', selectedDate);
								$(this).datepicker('setDate', selectedDate);
							}
						},
						beforeShowDay: function(day) {
							var c = 'ui-datepicker-month';
							if (selectedDate && selectedDate.getFullYear() === day.getFullYear() && selectedDate.getMonth() === day.getMonth()) {
								c += ' ui-datepicker-month-selected';
							}
							var now = new Date();
							if (day.getFullYear() === now.getFullYear() && day.getMonth() === now.getMonth()) {
								c += ' ui-datepicker-month-current';
							}
							return [true, c];
						},
						onSelect: function(day, inst) {
							selectedDate = new Date(inst.selectedYear, inst.selectedMonth, 1);
							t.datepicker('setDate', selectedDate);
							inst.input.blur();
						}
					});
					if (pickerSettings.maxDate) {
						pickerSettings.maxDate.setMonth(pickerSettings.maxDate.getMonth() + 1, 0);
					}
					break;
				case 'week':
					$.extend(pickerSettings, {
						altField: alt,
						altFormat: 'yy-Www',
						showButtonPanel: true,
						showOtherMonths: true,
						showWeek: true,
						beforeShow: function() {
							if (selectedDate) {
								t.datepicker('option', 'defaultDate', selectedDate);
								t.datepicker('setDate', selectedDate);
							}
						},
						beforeShowDay: function(day) {
							var c = 'ui-datepicker-week';
							if (selectedDate && $.datepicker.iso8601Week(selectedDate) === $.datepicker.iso8601Week(day) && selectedDate.getFullYear() === day.getFullYear()) {
								c += ' ui-datepicker-week-selected';
							}
							var now = new Date();
							if ($.datepicker.iso8601Week(day) === $.datepicker.iso8601Week(now) && day.getFullYear() === now.getFullYear()) {
								c += ' ui-datepicker-week-current';
							}
							return [true, c];
						},
						onSelect: function(day, inst) {
							selectedDate = new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay);
							// move to monday
							selectedDate.setDate(selectedDate.getDate() - (selectedDate.getDay() + 6) % 7);
							t.datepicker('setDate', selectedDate);
							inst.input.blur();
						}
					});
					if (pickerSettings.maxDate) {
						pickerSettings.maxDate.setDate(pickerSettings.maxDate.getDate() + 6); // move from monday to sunday
					}
					break;
				case 'time':
					$.extend(pickerSettings, {
						altFieldTimeOnly: false,
						altField: alt,
						altFormat: '',
						dateFormat: '',
						altSeparator: '',
						separator: '',
						altTimeFormat: 'HH:mm:ss',
						stepHour: 1,
						stepMinute: 1,
						showButtonPanel: true
					});
					break;
			}

			settings.create(t, pickerSettings);

			if (selectedDate) {
				t.datepicker('setDate', selectedDate);
			}
		});
		return this;
	};

	// Nette validators
	Nette.validators.dateInputValid = function(elem, arg, val) {
		var el = $(elem);
		var type = el.attr('data-dateinput-type');
		var format = globalSettings[type].validFormat;
		val = el.data('altField').val();
		return (new RegExp('^(' + format + ')$')).test(val);
	};
	Nette.validators.dateInputRange = function(elem, arg, val) {
		var el = $(elem);
		val = el.data('altField').val();
		return Nette.isArray(arg) ? ((arg[0] === null || val >= arg[0]) && (arg[1] === null || val <= arg[1])) : null;
	};
})(jQuery, Nette);
<|endoftext|>


<commit_before>

require(['jquery', 'angular'], function($, angular) {
    require(['Adhocracy',
             'Adhocracy/Util',
             'Adhocracy/Services/Http',
             'Adhocracy/Controllers/DocumentWorkbench',
            ],
            function(Adhocracy,
                     AdhUtil,
                     AdhHttp,
                     AdhDWB) {

$(document).ready(function() {

    var app = angular.module('NGAD', []);

// services

app.factory('adhHttp', ['$http', AdhHttp.factory]);

// controller

app.controller('AdhDocumentTOC', function(adhHttp, $scope) {
    this.path = '/adhocracy';

    adhHttp.get(this.path, ['P.Pool']).then(function(d) {
        var pool = d.data['P.IPool'];

        $scope.directory = [];

        // show paths only.
        // $scope.directory = pool.elements.map(function(d) { return d.path });

        // show names of heads of dags under paths.  this yields a
        // directory in non-deterministic order.  which is ok; we want
        // to change order and filters dynamically anyway.
        //
        // FIXME: write a function that follows references
        // transparently through the data model.  (it takes an array
        // of field names, and follows these fields names down into an
        // object.  each time it hits a reference, the reference is
        // replaced by the referenced object before the path is
        // followed further.)
        pool.elements.map(function(ref) {
            adhHttp.get(ref.path).then(function(dag) {
                var dagPS = dag.data['P.IDAG'];
                if (dagPS.versions.length > 0) {
                    var dagPath = dag.path;
                    var headPath = dagPS.versions[0].path;
                    adhHttp.get(headPath).then(function(doc) {
                        var docPS = doc.data['P.IDocument'];
                        $scope.directory.push([headPath, docPS.title]);
                    });
                } else {
                    $scope.directory.push(undefined);
                }
            });
        });
    });

    function clearDetail() {
        $scope.detail = {};
        $scope.detail_paragraphs = {ref: [], xpath: []};
        $scope.detail_mode = 'display';
    }

    clearDetail();
    this.showDetail = function(path) {
        clearDetail();

        adhHttp.get(path).then(function(data) {
            $scope.detail = data;
            adhHttp.drill(data, ['P.IDocument', ['paragraphs'], 'P.IParagraph'],
                          $scope.detail_paragraphs, true);
        });
    }

    this.showDetailEdit = function() {
        $scope.detail_old = AdhUtil.deepcp($scope.detail);
        $scope.detail_mode = 'edit';
    }

    this.showDetailReset = function() {
        $scope.detail_mode = 'display';
    }

    this.showDetailSave = function() {
        adhHttp.postNewVersion($scope.detail_old.path, $scope.detail, function() {
            $scope.detail_mode = 'display';
        });
    }
});

app.directive('adhDocumentWorkbench', function() {
    return {
        restrict: 'E',
        templateUrl: '/static/templates/P/IDocument/Workbench.html',
    }
});

app.directive('adhDocumentDetail', function() {
    return {
        restrict: 'E',
        templateUrl: '/static/templates/P/IDocument/ViewDetail.html',
    }
});

// filters

app.filter('fDirectoryEntry', [ function() {
    // (dummy filter to show how this works.  originally, i wanted to
    // pull more data asynchronously here, but i'm not sure this is
    // supposed to work.)
    return function(ref) {
        return '[' + ref + ']';
    };
}]);

// get going

angular.bootstrap(document, ['NGAD']);
AdhDWB.run();

});

$(document).load(function() {
    // FIXME: this is never reached.  why?
    console.log('page load complete');
});

            });
});
<commit_msg>fix: revert to unchanged version on reset<commit_after>

require(['jquery', 'angular'], function($, angular) {
    require(['Adhocracy',
             'Adhocracy/Util',
             'Adhocracy/Services/Http',
             'Adhocracy/Controllers/DocumentWorkbench',
            ],
            function(Adhocracy,
                     AdhUtil,
                     AdhHttp,
                     AdhDWB) {

$(document).ready(function() {

    var app = angular.module('NGAD', []);

// services

app.factory('adhHttp', ['$http', AdhHttp.factory]);

// controller

app.controller('AdhDocumentTOC', function(adhHttp, $scope) {
    this.path = '/adhocracy';

    adhHttp.get(this.path, ['P.Pool']).then(function(d) {
        var pool = d.data['P.IPool'];

        $scope.directory = [];

        // show paths only.
        // $scope.directory = pool.elements.map(function(d) { return d.path });

        // show names of heads of dags under paths.  this yields a
        // directory in non-deterministic order.  which is ok; we want
        // to change order and filters dynamically anyway.
        //
        // FIXME: write a function that follows references
        // transparently through the data model.  (it takes an array
        // of field names, and follows these fields names down into an
        // object.  each time it hits a reference, the reference is
        // replaced by the referenced object before the path is
        // followed further.)
        pool.elements.map(function(ref) {
            adhHttp.get(ref.path).then(function(dag) {
                var dagPS = dag.data['P.IDAG'];
                if (dagPS.versions.length > 0) {
                    var dagPath = dag.path;
                    var headPath = dagPS.versions[0].path;
                    adhHttp.get(headPath).then(function(doc) {
                        var docPS = doc.data['P.IDocument'];
                        $scope.directory.push([headPath, docPS.title]);
                    });
                } else {
                    $scope.directory.push(undefined);
                }
            });
        });
    });

    function clearDetail() {
        $scope.detail = {};
        $scope.detail_paragraphs = {ref: [], xpath: []};
        $scope.detail_mode = 'display';
    }

    clearDetail();
    this.showDetail = function(path) {
        clearDetail();

        adhHttp.get(path).then(function(data) {
            $scope.detail = data;
            adhHttp.drill(data, ['P.IDocument', ['paragraphs'], 'P.IParagraph'],
                          $scope.detail_paragraphs, true);
        });
    }

    this.showDetailEdit = function() {
        $scope.detail_old = AdhUtil.deepcp($scope.detail);
        $scope.detail_mode = 'edit';
    }

    this.showDetailReset = function() {
        $scope.detail = AdhUtil.deepcp($scope.detail_old);
        $scope.detail_mode = 'display';
    }

    this.showDetailSave = function() {
        adhHttp.postNewVersion($scope.detail_old.path, $scope.detail, function() {
            $scope.detail_mode = 'display';
        });
    }
});

app.directive('adhDocumentWorkbench', function() {
    return {
        restrict: 'E',
        templateUrl: '/static/templates/P/IDocument/Workbench.html',
    }
});

app.directive('adhDocumentDetail', function() {
    return {
        restrict: 'E',
        templateUrl: '/static/templates/P/IDocument/ViewDetail.html',
    }
});

// filters

app.filter('fDirectoryEntry', [ function() {
    // (dummy filter to show how this works.  originally, i wanted to
    // pull more data asynchronously here, but i'm not sure this is
    // supposed to work.)
    return function(ref) {
        return '[' + ref + ']';
    };
}]);

// get going

angular.bootstrap(document, ['NGAD']);
AdhDWB.run();

});

$(document).load(function() {
    // FIXME: this is never reached.  why?
    console.log('page load complete');
});

            });
});
<|endoftext|>


<commit_before>var express = require('express'),
    credentials = require('../../../modules/credentials.js'),
    randNumber = require('../../../modules/randNumber.js'),
    // isValidDate = require('../../../modules/isValidDate.js'),
    router = express.Router();

router.get('/', function(req, res) {
    var cr = credentials(req.session),
        login = cr.login,
        admin = cr.admin,
        sql;

    if (admin) {
        req.getConnection(function(err, connection) {
            sql = 'SELECT id, name, posters FROM slideshows';
            // Get the user id using username
            connection.query(sql, function(err, match) {
                if (err) {
                    throw err;
                }

                if (match !== '' && match.length > 0) {
                    res.render('admin/slideshows/show', {
                        title: 'Slideshows',
                        rights: {
                            admin: admin,
                            logedin: login
                        },
                        data: match
                    });
                } else {
                    res.render('admin/slideshows/show', {
                        title: 'Slideshows',
                        rights: {
                            admin: admin,
                            logedin: login
                        },
                        error: 'You have no displays jet',
                        data: match
                    });
                }
            });
        });
    } else {
        res.redirect('/admin');
    }
});
router.get('/add', function(req, res) {
    res.redirect('/admin/slideshows/add/' + randNumber());
});
router.get('/add/:slideshowId', function(req, res) {
    var cr = credentials(req.session),
        slideshowId = req.params.slideshowId,
        login = cr.login,
        admin = cr.admin;

    if (login && admin) {
        req.getConnection(function(err, connection) {
            var sqlPosters = 'SELECT filename, type, name, animation, duration, dateStart,dateEnd, id FROM posters';
            connection.query(sqlPosters, function(err, allPosters) {
                if (err) throw err;

                var sqlSlideshows = 'SELECT posters, id, name, discription FROM slideshows WHERE id = ?';
                connection.query(sqlSlideshows, [slideshowId], function(err, slideshowMatch) {
                    if (err) throw err;

                    var displaySql = 'SELECT id, name FROM displays';
                    // Get the user id using username
                    connection.query(displaySql, function(err, displayMatch) {
                        if (err) throw err;

                        if (slideshowMatch !== '' && slideshowMatch.length > 0) {
                            var AllPosters = JSON.parse(slideshowMatch[0].posters),
                                slideshowSettings = {
                                    id: slideshowMatch[0].id,
                                    name: slideshowMatch[0].name,
                                    discription: slideshowMatch[0].discription
                                },
                                usedposters = [];
                            AllPosters.forEach(function(singlePoster) {
                                allPosters.forEach(function(poster) {
                                    if (singlePoster === poster.id) {
                                        usedposters.push(poster);
                                    }
                                });
                            });
                            renderPage(usedposters, allPosters, slideshowSettings, displayMatch);
                        } else {
                            renderPage(null, allPosters, null, displayMatch);
                        }
                    });
                });
            });
        });
    } else {
        res.redirect('/admin');
    }

    function renderPage(usedposters, allPosters, slideshowSettings, displayMatch) {
        res.render('admin/slideshows/add', {
            title: 'Add a poster',
            data: {
                usedposters: usedposters || null,
                allPosters: allPosters,
                displays: displayMatch,
                slideshowSettings: slideshowSettings || null
            },
            rights: {
                admin: admin,
                logedin: login
            },
            navStyle: 'icons-only',
            postUrl: {
                settings: '/admin/slideshows/add',
                posters: '/admin/posters/add',
                displays: '/admin/posters/add'
            },
            error: false

        });
    }
});

router.post('/add/:slideshowId', function(req, res) {
    var cr = credentials(req.session),
        slideshowId = req.params.slideshowId,
        admin = cr.admin,
        email = cr.email,
        // admin = cr.admin,
        body = req.body,
        posters = '[' + body.posters + ']',
        sqlQuery;
    if (admin) {
        req.getConnection(function(err, connection) {
            var sql = 'SELECT id FROM users WHERE email = ?';
            connection.query(sql, [email], function(err, matchUser) {
                if (err) throw err;

                if (matchUser !== '' && matchUser.length > 0) {
                    var sqlSlideshows = 'SELECT id FROM slideshows WHERE id = ?';
                    connection.query(sqlSlideshows, [slideshowId], function(err, match) {
                        if (err) throw err;
                        if (match !== '' && match.length === 0) {
                            var sqlValues = {
                                id: slideshowId,
                                userId: matchUser[0].id,
                                posters: posters
                            };
                            sqlQuery = 'INSERT INTO slideshows SET ?';

                            connection.query(sqlQuery, sqlValues, function(err) {
                                if (err) {
                                    throw err;
                                }
                                res.send('done');
                            });

                        } else {
                            sqlQuery = 'UPDATE slideshows SET posters = ? WHERE id= ?';
                            connection.query(sqlQuery, [posters, match[0].id], function(err) {
                                if (err) throw err;
                                res.send('done');
                            });
                        }
                    });
                }
            });
        });
    } else {
        res.redirect('/admin');
    }
});

module.exports = router;
<commit_msg>add abilaty to update poster name and descriptoin.<commit_after>var express = require('express'),
    credentials = require('../../../modules/credentials.js'),
    randNumber = require('../../../modules/randNumber.js'),
    getData = require('../../../modules/getData.js'),
    getSpecificData = require('../../../modules/getSpecificData.js'),
    insertData = require('../../../modules/insertData.js'),
    renderTemplate = require('../../../modules/renderTemplate.js'),
    // isValidDate = require('../../../modules/isValidDate.js'),
    router = express.Router();

router.get('/', function(req, res) {
    var cr = credentials(req.session),
        general = {
            title: 'Your posters',
            login: cr.login,
            admin: cr.admin,
            email: cr.email
        },
        sql;

    if (general.admin) {

        req.getConnection(function(err, connection) {
            sql = 'SELECT id, slideshow_name FROM slideshows';
            // Get the user id using username
            getData(sql, connection).then(function(rows) {
                var data = {
                    general: rows
                };
                //renderTemplate
                if (rows.length > 0) {
                    renderTemplate(res, 'admin/slideshows/show', data, general, {}, false);
                } else {
                    renderTemplate(res, 'admin/slideshows/show', data, general, {}, 'You don\' have any slideshows.');
                }
                //
            }).catch(function(err) {
                throw err;
            });
        });
    } else {
        res.redirect('/admin');
    }
});

//create unique id and redirect
router.get('/add', function(req, res) {
    var cr = credentials(req.session),
        email = cr.email,
        createSlideshow = 'INSERT INTO slideshows SET id = ?, slideshow_userId = (SELECT id FROM users WHERE email = ?)',
        number = randNumber(1000000);

    req.getConnection(function(err, connection) {
        insertData(createSlideshow, [number, email], connection).then(function() {

            res.redirect('/admin/slideshows/add/' + number);

        }).catch(function(err) {
            throw err;
        });
    });
});

router.get('/add/:slideshowId', function(req, res) {
    var cr = credentials(req.session),
        slideshowId = req.params.slideshowId,
        general = {
            title: 'Your posters',
            login: cr.login,
            admin: cr.admin,
            email: cr.email,
            navStyle: 'icons-only'
        },
        postUrls = {
            settings: '/admin/slideshows/add/settings/' + slideshowId,
            posters: '/admin/posters/edit',
            displays: '/admin/posters/edit'
        };

    if (general.admin) {
        var sql = 'SELECT * FROM posters_In_slideshow T1 LEFT JOIN slideshows T2 ON T1.slideshow_id = T2.id LEFT JOIN posters T3 ON T1.poster_id = T3.id WHERE T1.slideshow_id = ? ORDER BY T1.short ASC';
        var sqlPosters = 'SELECT * FROM posters';

        req.getConnection(function(err, connection) {
            getData(sqlPosters, connection).then(function(posters) {
                getSpecificData(sql, connection, [slideshowId]).then(function(rows) {
                    // if (rows.length > 0) {
                    var data = {
                        general: rows,
                        posters: posters
                    };
                    renderTemplate(res, 'admin/slideshows/add', data, general, postUrls, false);
                    // }
                }).catch(function(err) {
                    throw err;
                });
            }).catch(function(err) {

                throw err;
            });
        });
    } else {
        res.redirect('/admin');
    }
});

router.post('/add/:slideshowId', function(req, res) {
    var cr = credentials(req.session),
        slideshowId = req.params.slideshowId,
        admin = cr.admin,
        // admin = cr.admin,
        body = req.body,
        posters = JSON.parse('[' + body.posters + ']');
    console.log(posters);
    if (admin) {
        req.getConnection(function(err, connection) {
            var sqlQueryInsert = 'INSERT INTO posters_In_slideshow SET poster_id = ?, slideshow_id = ?, short = ?';
            var sqlQueryUpdate = 'UPDATE posters_In_slideshow SET short = ? WHERE poster_id = ? AND slideshow_id = ?';
            var sqlQueryGet = 'SELECT * FROM posters_In_slideshow WHERE poster_id = ? AND slideshow_id = ?';

            posters.forEach(function(poster, index) {
                getSpecificData(sqlQueryGet, connection, [poster, slideshowId]).then(function(rows) {
                    if (rows.length === 0) {
                        insertData(sqlQueryInsert, [poster, slideshowId, index], connection).then(function() {

                        }).catch(function(err) {
                            throw err;
                        });
                    } else {
                        insertData(sqlQueryUpdate, [index, poster, slideshowId], connection).then(function() {

                        }).catch(function(err) {
                            throw err;
                        });
                    }
                }).catch(function(err) {
                    res.send('error', err);
                    throw err;
                });
            });
            res.send('succes');
        });
    } else {
        res.redirect('/admin');
    }
});

router.post('/add/settings/:slideshowId', function(req, res) {
    var cr = credentials(req.session),
        slideshowId = req.params.slideshowId,
        admin = cr.admin,
        // admin = cr.admin,
        body = req.body,
        discription = body.discription,
        name = body.name;

    if (admin) {
        req.getConnection(function(err, connection) {
            var sqlQueryInsert = 'UPDATE slideshows SET slideshow_discription = ?, slideshow_name = ? WHERE id = ?';

            insertData(sqlQueryInsert, [discription, name, slideshowId], connection).then(function() {

                res.redirect('/admin/slideshows/add/' + slideshowId);

            }).catch(function(err) {
                console.log(err);
                res.send('err' + err);
                throw err;
            });
        });
    } else {
        res.redirect('/admin');
    }
});

module.exports = router;
<|endoftext|>


<commit_before>/**
 * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here.
	// For complete reference see:
	// http://docs.ckeditor.com/#!/api/CKEDITOR.config

	// The toolbar groups arrangement, optimized for two toolbar rows.
	config.toolbarGroups = [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
		{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
		{ name: 'links' },
		{ name: 'insert' },
		{ name: 'forms' },
		{ name: 'tools' },
		{ name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
		{ name: 'others' },
		'/',
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
		{ name: 'styles' },
		{ name: 'colors' },
		{ name: 'about' }
	];

	// Remove some buttons provided by the standard plugins, which are
	// not needed in the Standard(s) toolbar.
	config.removeButtons = 'Underline,Subscript,Superscript';

	// Set the most common block elements.
	config.format_tags = 'p;h1;h2;h3;pre';

	// Simplify the dialog windows.
	config.removeDialogTabs = 'image:advanced;link:advanced';
	config.filebrowserBrowseUrl = eldifnder_url;
	// add more plugins
	config.extraPlugins = 'lineutils,widget,codesnippet';

};<commit_msg>add multi language to ckeditor<commit_after>/**
 * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md or http://ckeditor.com/license
 */

CKEDITOR.editorConfig = function( config ) {
	// Define changes to default configuration here.
	// For complete reference see:
	// http://docs.ckeditor.com/#!/api/CKEDITOR.config

	// The toolbar groups arrangement, optimized for two toolbar rows.
	config.toolbarGroups = [
		{ name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
		{ name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
		{ name: 'links' },
		{ name: 'insert' },
		{ name: 'forms' },
		{ name: 'tools' },
		{ name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
		{ name: 'others' },
		'/',
		{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
		{ name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
		{ name: 'styles' },
		{ name: 'colors' },
		{ name: 'about' }
	];

	// Remove some buttons provided by the standard plugins, which are
	// not needed in the Standard(s) toolbar.
	config.removeButtons = 'Underline,Subscript,Superscript';

	// Set the most common block elements.
	config.format_tags = 'p;h1;h2;h3;pre';

	// Simplify the dialog windows.
	config.removeDialogTabs = 'image:advanced;link:advanced';
	config.filebrowserBrowseUrl = eldifnder_url;
	// add more plugins
	config.extraPlugins = 'lineutils,widget,codesnippet';

	config.contentsLangDirection = contentsLangDirection;
	config.contentsLanguage = cke_lang;
	config.language = cke_lang;
	config.dialog_buttonsOrder = contentsLangDirection;

};<|endoftext|>


<commit_before>var assert = require('assert');

var doors = [];

var allDoorsAreClosed = function () {
  var allDoorsClosed = true;
  for (var door in doors) {
    allDoorsClosed = allDoorsClosed && door.closed;
  }

  return allDoorsClosed;
};

var thereAre100Doors = function() {
  var doorCount = 0;
  for (var door in doors) {
    doorCount++;
  }

  return doorCount;
};

var main = function () {
  assert(thereAre100Doors(), "there should be 100 doors");
  assert(allDoorsAreClosed(), "all doors are closed");
};

main();<commit_msg>in a pickle, why aren't there 100 doors?<commit_after>var assert = require('assert');

var createDoors = function() {
  doors = [];
  for (var i=0;i<100;++i) {
    doors.push({});
  }
};

var doors = createDoors();

var allDoorsAreClosed = function () {
  var allDoorsClosed = true;
  for (var door in doors) {
    allDoorsClosed = allDoorsClosed && door.closed;
  }

  return allDoorsClosed;
};

var thereAre100Doors = function() {
  var doorCount = 0;
  for (var door in doors) {
    doorCount++;
  }

  return doorCount;
};

var main = function () {
  assert(thereAre100Doors(), "there should be 100 doors");
  assert(allDoorsAreClosed(), "all doors are closed");
};

main();<|endoftext|>


<commit_before>/**
 * Created by Rafael on 07/09/2015.
 */
angular.module('app').controller('UpdateEventController',["$scope","EventService","$routeParams",
    function($scope,EventService, $routeParams){

    $scope.event = {};
    $scope.updateEvent = function(){
    EventService.updateEvent($scope.event)
        .success(function(data, status, headers, config) {
            toastr.success('Event Update Succesfully');
        }).
    error(function(data, status, headers, config) {
        toastr.error(data);

     });
    };

    $scope.getEvent = function(){
        EventService.getEvent($routeParams.eventId)
        .success(function(data, status, headers, config) {
                $scope.event = data;

                $scope.event.BeginDate = new Date(data.BeginDate);

                $scope.event.EndDate = new Date(data.EndDate);
        }).
    error(function(data, status, headers, config) {
        toastr.error(data);

     });

    };

    $scope.getEvent();

    }]);
<commit_msg>Corrected code style<commit_after>/**
 * Created by Rafael on 07/09/2015.
 */
angular.module('app').controller('UpdateEventController',["$scope","EventService","$routeParams",
    function($scope, EventService, $routeParams){

    $scope.event = {};
    $scope.updateEvent = function(){
    EventService.updateEvent($scope.event)
        .success(function(data, status, headers, config) {
            toastr.success('Event Update Succesfully');
        })
        .error(function(data, status, headers, config) {
            toastr.error(data.Message);
        });
    };

    $scope.getEvent = function(){
        EventService.getEvent($routeParams.eventId)
        .success(function(data, status, headers, config) {
            $scope.event = data;
            $scope.event.BeginDate = new Date(data.BeginDate);
            $scope.event.EndDate = new Date(data.EndDate);
        })
        .error(function(data, status, headers, config) {
            toastr.error(data.Message);
        });
    };

    $scope.getEvent();

}]);
<|endoftext|>


<commit_before>function gameengine() {
}
gameengine.prototype.board = {
	tiles:[],
	hwalls:[],
	vwalls:[]
};

gameengine.prototype.findAllVertWallsOfLen = function(wallarray, walLen) {
	var output = [];
	for(var row=0;row<wallarray.length;row++) {
		for(var col=0;col<wallarray[row].walls.length;col++){
			var include = true;
			for(var t=row;t<row+walLen;t++){
				if(!wallarray[t] || !wallarray[t].walls[col] || wallarray[t].walls[col].blocked) {
					include = false;
					break;
				}
			}
			if(include) {
				output.push({prow:row,pcol:col});
			}
		}
	}
	return output;
};

gameengine.prototype.createRandomVertWalls = function(wallarray, possibles, wallsToBuild) {
	var winner = possibles[Math.floor(Math.random()*possibles.length)];
	for(var w=winner.prow;w<winner.prow+wallsToBuild;w++){
		wallarray[w].walls[winner.pcol].blocked = true;
	}
};

gameengine.prototype.randomWalls = function(wallarray) {
	var wallPercent = 0.2*Math.pow(wallarray.length,2);

	var walLen = 1;
	var walsBuilt = 0;
	while(walsBuilt < wallPercent) {
		var possibles = this.findAllVertWallsOfLen(wallarray, walLen);
		this.createRandomVertWalls(wallarray, possibles, walLen)

		walsBuilt += walLen;
		walLen+=1;
		if(walLen > 3){
			walLen=1;
		}
	}
};

gameengine.prototype.defineBoard = function(sq){
	this.board.tiles = [];
	this.board.hwalls = [];
	this.board.vwalls = [];

	var size = 16;
	this.board.tileSize = size;

	if(sq < 1){
		alert("why you no define larger board?");
		return;
	}

	for(var r=0;r<sq;r++) {
		this.board.tiles.push({rowid:r,columns:[]});
		for(var c=0;c<sq;c++){
			this.board.tiles[r].columns.push({
				colid:c,
				contents:null,
				x:(size*c)+c+1,
				y:(size*r)+r+1
			});
		}
	}

	//(n-1 * n)*2
	for(var rn=0;rn<sq;rn++){
		this.board.vwalls.push({rowid:rn,walls:[]});
		if(rn < sq-1) {
			this.board.hwalls.push({rowid:rn,walls:[]});
		}
		for(var cn=0;cn<sq;cn++) {
			if(rn < sq-1) {
				this.board.hwalls[rn].walls.push({
					walid:cn,
					blocked:false,
					x1:size*cn,
					x2:size*(cn+1),
					y1:(rn+1)*size,
					y2:(rn+1)*size
				});
			}
			if(cn < sq-1) {
				this.board.vwalls[rn].walls.push({
					walid:cn,
					blocked:false,
					x1:size*(1+cn),
					x2:size*(1+cn),
					y1:rn*size,
					y2:(rn+1)*size
				});
			}
		}
	}

	this.randomWalls(this.board.hwalls);
	this.randomWalls(this.board.vwalls);
};

gameengine.prototype.clearBoard = function() {
	this.board.tiles = [];
	this.board.hwalls = [];
	this.board.vwalls = [];
};

gameengine.prototype.drawCanvas = function() {
	var ctx = gamecanvas.getContext("2d");

	ctx.fillStyle = "#cccccc";
	var maxSize = ((this.board.tileSize+1)*(this.board.tiles.length))+1;
	ctx.fillRect(0,0,maxSize,maxSize);

	ctx.fillStyle = "#ffffff";
	for(var r=0; r<this.board.tiles.length; r++) {
		for(var c=0;c<this.board.tiles[r].columns.length;c++){
			var cell = this.board.tiles[r].columns[c];
			ctx.fillRect(cell.x,cell.y,this.board.tileSize,this.board.tileSize);
		}
	}

	ctx.fillStyle = "#000000";

	this.drawWall(ctx, this.board.hwalls);
	this.drawWall(ctx, this.board.vwalls);
};

gameengine.prototype.drawWall = function(ctx, wallarray) {
	for(var wr=0;wr<wallarray.length;wr++) {
		for(var wc=0;wc<wallarray[wr].walls.length;wc++) {
			var wall = wallarray[wr].walls[wc];
			if(wall.blocked) {
				ctx.moveTo(wall.x1,wall.y1);
				ctx.lineTo(wall.x2,wall.y2);
				ctx.stroke();
			}
		}
	}
}

gameengine.prototype.drawBoard = function() {
	this.clearBoard();

	var sq = parseInt(square.value);
	this.defineBoard(sq);

	this.drawCanvas();
};

var game = new gameengine();
playButton.addEventListener("click",game.drawBoard,false);
game.drawBoard();
<commit_msg>lines are in the correct position<commit_after>function gameengine() {
}
gameengine.prototype.board = {
	tiles:[],
	hwalls:[],
	vwalls:[]
};

gameengine.prototype.findAllVertWallsOfLen = function(wallarray, walLen) {
	var output = [];
	for(var row=0;row<wallarray.length;row++) {
		for(var col=0;col<wallarray[row].walls.length;col++){
			var include = true;
			for(var t=row;t<row+walLen;t++){
				if(!wallarray[t] || !wallarray[t].walls[col] || wallarray[t].walls[col].blocked) {
					include = false;
					break;
				}
			}
			if(include) {
				output.push({prow:row,pcol:col});
			}
		}
	}
	return output;
};

gameengine.prototype.createRandomVertWalls = function(wallarray, possibles, wallsToBuild) {
	var winner = possibles[Math.floor(Math.random()*possibles.length)];
	for(var w=winner.prow;w<winner.prow+wallsToBuild;w++){
		wallarray[w].walls[winner.pcol].blocked = true;
	}
};

gameengine.prototype.randomWalls = function(wallarray) {
	var wallPercent = 0.2*Math.pow(wallarray.length,2);

	var walLen = 1;
	var walsBuilt = 0;
	while(walsBuilt < wallPercent) {
		var possibles = this.findAllVertWallsOfLen(wallarray, walLen);
		this.createRandomVertWalls(wallarray, possibles, walLen)

		walsBuilt += walLen;
		walLen+=1;
		if(walLen > 3){
			walLen=1;
		}
	}
};

gameengine.prototype.defineBoard = function(sq){
	this.board.tiles = [];
	this.board.hwalls = [];
	this.board.vwalls = [];

	var size = 16;
	this.board.tileSize = size;

	if(sq < 1){
		alert("why you no define larger board?");
		return;
	}

	for(var r=0;r<sq;r++) {
		this.board.tiles.push({rowid:r,columns:[]});
		for(var c=0;c<sq;c++){
			this.board.tiles[r].columns.push({
				colid:c,
				contents:null,
				x:(size*c)+c+1,
				y:(size*r)+r+1
			});
		}
	}

	//(n-1 * n)*2
	var hy=size+2;
	var vy=1;
	for(var rn=0;rn<sq;rn++){
		this.board.vwalls.push({rowid:rn,walls:[]});
		if(rn < sq-1) {
			this.board.hwalls.push({rowid:rn,walls:[]});
		}
		var hx=1;
		var vx=size+2;
		for(var cn=0;cn<sq;cn++) {
			if(rn < sq-1) {
				this.board.hwalls[rn].walls.push({
					walid:cn,
					blocked:false,
					x1:hx,
					x2:hx+size,
					y1:hy,
					y2:hy
				});
			}
			if(cn < sq-1) {
				this.board.vwalls[rn].walls.push({
					walid:cn,
					blocked:false,
					x1:vx,
					x2:vx,
					y1:vy,
					y2:vy+size
				});
			}
			hx+=(size+1);
			vx+=(size+1);
		}
		vy+=(size+1);
		hy+=(size+1);
	}

	this.randomWalls(this.board.hwalls);
	this.randomWalls(this.board.vwalls);
};

gameengine.prototype.clearBoard = function() {
	this.board.tiles = [];
	this.board.hwalls = [];
	this.board.vwalls = [];
};

gameengine.prototype.drawCanvas = function() {
	var ctx = gamecanvas.getContext("2d");

	ctx.fillStyle = "#cccccc";
	var maxSize = ((this.board.tileSize+1)*(this.board.tiles.length))+1;
	ctx.fillRect(0,0,maxSize,maxSize);

	ctx.fillStyle = "#ffffff";
	for(var r=0; r<this.board.tiles.length; r++) {
		for(var c=0;c<this.board.tiles[r].columns.length;c++){
			var cell = this.board.tiles[r].columns[c];
			ctx.fillRect(cell.x,cell.y,this.board.tileSize,this.board.tileSize);
		}
	}

	ctx.fillStyle = "#000000";

	this.drawWall(ctx, this.board.hwalls);
	this.drawWall(ctx, this.board.vwalls);
};

gameengine.prototype.drawWall = function(ctx, wallarray) {
	for(var wr=0;wr<wallarray.length;wr++) {
		for(var wc=0;wc<wallarray[wr].walls.length;wc++) {
			var wall = wallarray[wr].walls[wc];
			if(wall.blocked) {
				ctx.moveTo(wall.x1,wall.y1);
				ctx.lineTo(wall.x2,wall.y2);
				ctx.stroke();
			}
		}
	}
}

gameengine.prototype.drawBoard = function() {
	this.clearBoard();

	var sq = parseInt(square.value);
	this.defineBoard(sq);

	this.drawCanvas();
};

var game = new gameengine();
playButton.addEventListener("click",game.drawBoard,false);
game.drawBoard();
<|endoftext|>


<commit_before>"use strict";
var $ = document.getElementById.bind(document),
    shownNode, bgLink = $('bgLink'), BG,
    url, type, file;

BG = window.chrome && chrome.extension && chrome.extension.getBackgroundPage();
if (!(BG && BG.Utils && BG.Utils.convertToUrl)) {
  BG = null;
}

function decodeHash() {
  var str, ind;
  type = file = "";
  if (shownNode) {
    shownNode.remove();
    shownNode = null;
  }

  url = location.hash;
  if (url.length < 3) {}
  else if (url.lastIndexOf("#!image", 0) === 0) {
    url = url.substring(8);
    type = "image";
  } else if (url.lastIndexOf("#!url", 0) === 0) {
    url = url.substring(6);
    type = "url";
  }
  if (ind = url.indexOf("&") + 1) {
    if (url.lastIndexOf("download=", 0) === 0) {
      file = decodeURLPart(url.substring(9, ind - 1));
      url = url.substring(ind);
      str = document.querySelector('title').getAttribute('data-title');
      if (BG) {
        str = BG.Utils.createSearch(file.split(/\s+/), { url: str });
      } else {
        str = str.replace(/\$[sS](?:\{[^\}]*\})?/, file && (file + " | "));
      }
      document.title = str;
    }
  }
  if (url.indexOf(":") <= 0) {
    url = decodeURLPart(url).trim();
  }

  switch (type) {
  case "image":
    shownNode = importBody("shownImage");
    shownNode.src = url;
    shownNode.onclick = openByDefault;
    shownNode.onload = showBgLink;
    shownNode.onerror = function() {
      setTimeout(showBgLink, 34);
    };
    break;
  case "url":
    shownNode = importBody("shownText");
    if (BG) {
      ind = url.lastIndexOf("vimium://", 0) === 0 ? 1 : 0;
      str = BG.Utils.convertToUrl(url, null, ind + 0.5);
      if (BG.Utils.lastUrlType !== 5) {}
      else if (str instanceof BG.Promise) {
        str.then(function(arr) {
          showText(arr[1], arr[0] || arr[2]);
        });
        break;
      } else if (str instanceof BG.Array) {
        showText(str[1], str[0]);
        break;
      }
      url = str;
    }
    showText(type, url);
    break;
  default:
    url = "";
    shownNode = importBody("shownImage");
    shownNode.src = "../icons/vimium.png";
    bgLink.style.display = "none";
    break;
  }

  if (shownNode) {
    shownNode.setAttribute("download", file);
    bgLink.onclick = clickShownNode;
  } else {
    bgLink.onclick = openByDefault;
  }
  str = url && url.indexOf(":") === -1 ? chrome.runtime.getURL(url) : url;
  bgLink.setAttribute("data-vim-url", str);
  bgLink.setAttribute("data-vim-text", file);
  bgLink.download = file;
}

window.addEventListener("hashchange", decodeHash);
decodeHash();

window.addEventListener("keydown", function(event) {
  var str;
  if (!(event.ctrlKey || event.metaKey) || event.altKey
    || event.shiftKey || !url) { return; }
  str = String.fromCharCode(event.keyCode);
  if (str === 'S') {
    event.preventDefault();
    clickLink({
      download: file
    }, event);
  } else if (str === "C") {
    if (BG && BG.Clipboard && window.getSelection().type !== "Range") {
      BG.Clipboard.copy(url);
      window.VHUD && VHUD.showCopied(url);
    }
  }
});

function showBgLink() {
  bgLink.style.height = shownNode.scrollHeight + "px";
  bgLink.style.width = shownNode.scrollWidth + "px";
  bgLink.style.display = "";
}

function clickLink(options, event) {
  var a = document.createElement('a'), i;
  for (i in options) {
    a.setAttribute(i, options[i]);
  }
  a.href = url;
  if (window.DomUtils) {
    DomUtils.simulateClick(a, event);
  } else {
    a.click();
  }
}

function decodeURLPart(url) {
  try {
    url = decodeURIComponent(url);
  } catch (e) {}
  return url;
}

function importBody(id) {
  var template = $('bodyTemplate'),
      node = document.importNode(template.content.getElementById(id), true);
  document.body.insertBefore(node, $('bodyTemplate'));
  return node;
}

function openByDefault(event) {
  clickLink(event.altKey ? {
    download: file
  } : {
    target: "_blank"
  }, event);
}

function clickShownNode(event) {
  event.preventDefault();
  if (shownNode.onclick) {
    shownNode.onclick(event);
  }
}

function showText(tip, body) {
  $("textTip").setAttribute("data-tip", tip);
  $("textBody").textContent = body;
  shownNode.onclick = copyUrl;
  showBgLink();
}

function copyUrl() {
  event.preventDefault();
  if (!window.MainPort) { return; }
  MainPort.sendMessage({
    handler: "copyToClipboard",
    data: url
  }, function() {
    VHUD.showCopied(url);
  });
}
<commit_msg>rework show.js: add `startsWith`<commit_after>"use strict";
var $ = document.getElementById.bind(document),
    shownNode, bgLink = $('bgLink'), BG,
    url, type, file;

BG = window.chrome && chrome.extension && chrome.extension.getBackgroundPage();
if (!(BG && BG.Utils && BG.Utils.convertToUrl)) {
  BG = null;
}

function decodeHash() {
  var str, ind;
  type = file = "";
  if (shownNode) {
    shownNode.remove();
    shownNode = null;
  }

  url = location.hash;
  if (url.length < 3) {}
  else if (url.startsWith("#!image")) {
    url = url.substring(8);
    type = "image";
  } else if (url.startsWith("#!url")) {
    url = url.substring(6);
    type = "url";
  }
  if (ind = url.indexOf("&") + 1) {
    if (url.startsWith("download=")) {
      file = decodeURLPart(url.substring(9, ind - 1));
      url = url.substring(ind);
      str = document.querySelector('title').getAttribute('data-title');
      if (BG) {
        str = BG.Utils.createSearch(file.split(/\s+/), { url: str });
      } else {
        str = str.replace(/\$[sS](?:\{[^\}]*\})?/, file && (file + " | "));
      }
      document.title = str;
    }
  }
  if (url.indexOf(":") <= 0) {
    url = decodeURLPart(url).trim();
  }

  switch (type) {
  case "image":
    shownNode = importBody("shownImage");
    shownNode.src = url;
    shownNode.onclick = openByDefault;
    shownNode.onload = showBgLink;
    shownNode.onerror = function() {
      setTimeout(showBgLink, 34);
    };
    break;
  case "url":
    shownNode = importBody("shownText");
    if (BG) {
      ind = url.startsWith("vimium://") ? 1 : 0;
      str = BG.Utils.convertToUrl(url, null, ind + 0.5);
      if (BG.Utils.lastUrlType !== 5) {}
      else if (str instanceof BG.Promise) {
        str.then(function(arr) {
          showText(arr[1], arr[0] || arr[2]);
        });
        break;
      } else if (str instanceof BG.Array) {
        showText(str[1], str[0]);
        break;
      }
      url = str;
    }
    showText(type, url);
    break;
  default:
    url = "";
    shownNode = importBody("shownImage");
    shownNode.src = "../icons/vimium.png";
    bgLink.style.display = "none";
    break;
  }

  if (shownNode) {
    shownNode.setAttribute("download", file);
    bgLink.onclick = clickShownNode;
  } else {
    bgLink.onclick = openByDefault;
  }
  str = url && url.indexOf(":") === -1 ? chrome.runtime.getURL(url) : url;
  bgLink.setAttribute("data-vim-url", str);
  bgLink.setAttribute("data-vim-text", file);
  bgLink.download = file;
}

if (!String.prototype.startsWith) {
String.prototype.startsWith = function(s) {
  return this.lastIndexOf(s, 0) === 0;
};
}
decodeHash();
window.addEventListener("hashchange", decodeHash);

window.addEventListener("keydown", function(event) {
  var str;
  if (!(event.ctrlKey || event.metaKey) || event.altKey
    || event.shiftKey || !url) { return; }
  str = String.fromCharCode(event.keyCode);
  if (str === 'S') {
    event.preventDefault();
    clickLink({
      download: file
    }, event);
  } else if (str === "C") {
    if (BG && BG.Clipboard && window.getSelection().type !== "Range") {
      BG.Clipboard.copy(url);
      window.VHUD && VHUD.showCopied(url);
    }
  }
});

function showBgLink() {
  bgLink.style.height = shownNode.scrollHeight + "px";
  bgLink.style.width = shownNode.scrollWidth + "px";
  bgLink.style.display = "";
}

function clickLink(options, event) {
  var a = document.createElement('a'), i;
  for (i in options) {
    a.setAttribute(i, options[i]);
  }
  a.href = url;
  if (window.DomUtils) {
    DomUtils.simulateClick(a, event);
  } else {
    a.click();
  }
}

function decodeURLPart(url) {
  try {
    url = decodeURIComponent(url);
  } catch (e) {}
  return url;
}

function importBody(id) {
  var template = $('bodyTemplate'),
      node = document.importNode(template.content.getElementById(id), true);
  document.body.insertBefore(node, $('bodyTemplate'));
  return node;
}

function openByDefault(event) {
  clickLink(event.altKey ? {
    download: file
  } : {
    target: "_blank"
  }, event);
}

function clickShownNode(event) {
  event.preventDefault();
  if (shownNode.onclick) {
    shownNode.onclick(event);
  }
}

function showText(tip, body) {
  $("textTip").setAttribute("data-tip", tip);
  $("textBody").textContent = body;
  shownNode.onclick = copyUrl;
  showBgLink();
}

function copyUrl() {
  event.preventDefault();
  if (!window.MainPort) { return; }
  MainPort.sendMessage({
    handler: "copyToClipboard",
    data: url
  }, function() {
    VHUD.showCopied(url);
  });
}
<|endoftext|>


<commit_before>/**
 * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function() {

	OCA.WorkflowEngine = OCA.WorkflowEngine || {};
	OCA.WorkflowEngine.Plugins = OCA.WorkflowEngine.Plugins || {};

	OCA.WorkflowEngine.Plugins.RequestTimePlugin = {
		getCheck: function() {
			return {
				'class': 'OCA\\WorkflowEngine\\Check\\RequestTime',
				'name': t('workflowengine', 'Request time'),
				'operators': [
					{'operator': 'in', 'name': t('workflowengine', 'between')},
					{'operator': '!in', 'name': t('workflowengine', 'not between')}
				]
			};
		},
		render: function(element, check) {
			if (check['class'] !== 'OCA\\WorkflowEngine\\Check\\RequestTime') {
				return;
			}

			var placeholder = '["10:00 Europe\\/Berlin","16:00 Europe\\/Berlin"]'; // FIXME need a time picker JS plugin
			$(element).css('width', '300px')
				.attr('placeholder', placeholder)
				.attr('title', t('workflowengine', 'Example: {placeholder}', {placeholder: placeholder}, undefined, {escape: false}))
				.addClass('has-tooltip')
				.tooltip({
					placement: 'bottom'
				});
		}
	};
})();

OC.Plugins.register('OCA.WorkflowEngine.CheckPlugins', OCA.WorkflowEngine.Plugins.RequestTimePlugin);
<commit_msg>add a UI to render proper time picker<commit_after>/**
 * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function() {

	OCA.WorkflowEngine = OCA.WorkflowEngine || {};
	OCA.WorkflowEngine.Plugins = OCA.WorkflowEngine.Plugins || {};

	OCA.WorkflowEngine.Plugins.RequestTimePlugin = {
		timezones: [
			"Europe/Berlin",
			"Europe/London"
		],
		_$element: null,
		getCheck: function() {
			return {
				'class': 'OCA\\WorkflowEngine\\Check\\RequestTime',
				'name': t('workflowengine', 'Request time'),
				'operators': [
					{'operator': 'in', 'name': t('workflowengine', 'between')},
					{'operator': '!in', 'name': t('workflowengine', 'not between')}
				]
			};
		},
		render: function(element, check) {
			if (check['class'] !== 'OCA\\WorkflowEngine\\Check\\RequestTime') {
				return;
			}

			var startTime = '16:00',
				endTime = '18:00',
				timezone = 'Europe/London',
				$element = $(element);
			if (_.isString(check['value']) && check['value'] !== '') {
				var value = JSON.parse(check['value']),
					splittedStart = value[0].split(' ', 2),
					splittedEnd = value[1].split(' ', 2);

				startTime = splittedStart[0];
				endTime = splittedEnd[0];
				timezone = splittedStart[1];
			}
			var valueJSON = JSON.stringify([startTime + ' ' + timezone, endTime + ' ' + timezone]);
			if (check['value'] !== valueJSON) {
				check['value'] = valueJSON;
				$element.val(valueJSON);
			}

			$element.css('display', 'none');

			$('<input>')
				.attr('type', 'text')
				.attr('placeholder', t('workflowengine', 'Start'))
				.addClass('start')
				.val(startTime)
				.insertBefore($element);
			$('<input>')
				.attr('type', 'text')
				.attr('placeholder', t('workflowengine', 'End'))
				.addClass('end')
				.val(endTime)
				.insertBefore($element);

			var timezoneSelect = $('<select>')
				.addClass('timezone');
			_.each(this.timezones, function(timezoneName){
				var timezoneElement = $('<option>').val(timezoneName).html(timezoneName);

				if (timezoneName === timezone) {
					timezoneElement.attr('selected', 'selected');
				}

				timezoneSelect.append(timezoneElement);
			});
			timezoneSelect.insertBefore($element);

			$element.parent()
				.on('change', '.start', _.bind(this.update, this))
				.on('change', '.end', _.bind(this.update, this))
				.on('change', '.timezone', _.bind(this.update, this));

			this._$element = $element;
		},
		update: function(event) {
			var value = event.target.value,
				key = null;

			for (var i = 0; i < event.target.classList.length; i++) {
				key = event.target.classList[i];
			}

			if (key === null) {
				console.warn('update triggered but element doesn\'t have any class');
				return;
			}

			var data = JSON.parse(this._$element.val()),
				startTime = moment(data[0].split(' ', 2)[0], 'H:m Z'),
				endTime = moment(data[1].split(' ', 2)[0], 'H:m Z'),
				timezone = data[0].split(' ', 2)[1];

			if (key === 'start' || key === 'end') {
				var parsedDate = moment(value, ['H:m', 'h:m a'], true).format('HH:mm');

				if (parsedDate === 'Invalid date') {
					return;
				}

				var indexValue = 0;
				if (key === 'end') {
					indexValue = 1;
				}
				data[indexValue] = parsedDate + ' ' + timezone;
			}

			if (key === 'timezone') {
				data[0] = startTime.format('HH:mm') + ' ' + value;
				data[1] = endTime.format('HH:mm') + ' ' + value;
			}

			this._$element.val(JSON.stringify(data));
		}
	};
})();

OC.Plugins.register('OCA.WorkflowEngine.CheckPlugins', OCA.WorkflowEngine.Plugins.RequestTimePlugin);
<|endoftext|>


<commit_before>var layer = new L.StamenTileLayer("watercolor");
var map = new L.Map("map", {
    center: new L.LatLng(53.7416, -2.0175),
    zoom: 12
});
map.addLayer(layer);

var loadGeoJsonLayer = function(src, options) {
    var xhr = new XMLHttpRequest();

    xhr.open('get', src, true);
    xhr.onreadystatechange = function() {
        var status;
        var data;
        if (xhr.readyState == 4) {
            status = xhr.status;
            console.log("it done!");
            if (status == 200) {
                console.log("it success!");
                data = JSON.parse(xhr.responseText);
                L.geoJson(data, options).addTo(map);
            }

        }
    };
    xhr.send();
};

// loadGeoJsonLayer('./datasets/hx7.geojson', {
//                     style: function (feature) {
//                         return {color: 'red'};
//                     },
//                     onEachFeature: function (feature, layer) {
//                         layer.bindPopup(feature.properties.name);
//                     }
//                 });

var geojsonMarkerOptions = {
    radius: 8,
    // fillColor: "#ff7800",
    color: "#000",
    weight: 1,
    opacity: 1,
    fillOpacity: 0.8
};
loadGeoJsonLayer('./datasets/bizDist.geojson', {
                                style: function (feature) {
                                    return {
                                        color: 'green',
                                        radius: feature.properties.count
                                    };
                                },
                                onEachFeature: function (feature, layer) {
                                    layer.bindPopup(feature.properties.name +'
' + feature.properties.count);
                                },
                                pointToLayer: function (feature, latlng) {
                                    return L.circleMarker(latlng, geojsonMarkerOptions);
                                }
                            });
<commit_msg>Making layers work<commit_after>var layer = new L.StamenTileLayer("watercolor");
var map = new L.Map("map", {
    center: new L.LatLng(53.7416, -2.0175),
    zoom: 12
});
map.addLayer(layer);

var loadGeoJsonLayer = function(src, options) {
    var xhr = new XMLHttpRequest();

    xhr.open('get', src, true);
    xhr.onreadystatechange = function() {
        var status;
        var data;
        if (xhr.readyState == 4) {
            status = xhr.status;
            console.log("it done!");
            if (status == 200) {
                console.log("it success!");
                data = JSON.parse(xhr.responseText);
                L.geoJson(data, options).addTo(map);
            }

        }
    };
    xhr.send();
};

// loadGeoJsonLayer('./datasets/hx7.geojson', {
//                     style: function (feature) {
//                         return {color: 'red'};
//                     },
//                     onEachFeature: function (feature, layer) {
//                         layer.bindPopup(feature.properties.name);
//                     }
//                 });

var geojsonMarkerOptions = {
    radius: 8,
    // fillColor: "#ff7800",
    color: "#000",
    weight: 1,
    opacity: 1,
    fillOpacity: 0.8
};
loadGeoJsonLayer('./layers/bizDist.geojson', {
                                style: function (feature) {
                                    return {
                                        color: 'green',
                                        radius: feature.properties.count
                                    };
                                },
                                onEachFeature: function (feature, layer) {
                                    layer.bindPopup(feature.properties.name +'
' + feature.properties.count);
                                },
                                pointToLayer: function (feature, latlng) {
                                    return L.circleMarker(latlng, geojsonMarkerOptions);
                                }
                            });
<|endoftext|>


<commit_before>import ky from 'ky';
import { useStripes } from './StripesContext';

export default () => {
  const { tenant, token, url } = useStripes().okapi;
  return ky.create({
    prefixUrl: url,
    hooks: {
      beforeRequest: [
        request => {
          request.headers.set('X-Okapi-Tenant', tenant);
          request.headers.set('X-Okapi-Token', token);
        }
      ]
    },
    retry: 0
  });
};
<commit_msg>useOkapiKy: Pass locale via accept-language header (#1071)<commit_after>import ky from 'ky';
import { useStripes } from './StripesContext';

export default () => {
  const { locale = 'en', tenant, token, url } = useStripes().okapi;
  return ky.create({
    prefixUrl: url,
    hooks: {
      beforeRequest: [
        request => {
          request.headers.set('Accept-Language', locale);
          request.headers.set('X-Okapi-Tenant', tenant);
          request.headers.set('X-Okapi-Token', token);
        }
      ]
    },
    retry: 0
  });
};
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react';
import defaultStyles from './styles';
import Header from './header';
import Body from './body';

class ModalView extends Component {

    constructor(props) {
        super(props);
        this.state = {isVisible: props.isVisible || false};
    }

    componentWillUpdate(nextProps, nextState) {

        const {isVisible} = this.state;
        const {beforeOpen, beforeClose} = this.props;

        if (nextState.isVisible && !isVisible && beforeOpen) {
            beforeOpen();
        }

        if (!nextState.isVisible && isVisible && beforeClose) {
            beforeClose();
        }
    }

    componentDidUpdate(prevProps, prevState) {

        const {isVisible} = this.state;
        const {afterOpen, afterClose} = this.props;

        if (!prevState.isVisible && isVisible && afterOpen) {
            afterOpen();
        }

        if (prevState.isVisible && !isVisible && afterClose) {
            afterClose();
        }
    }

    show() {
        this.setState({isVisible: true});
    }

    hide() {
        this.setState({isVisible: false});
    }

    onOverlayClicked() {
        const { hideOnOverlayClicked, onOverlayClicked } = this.props;

        if (hideOnOverlayClicked) {
            this.hide();
        }

        if (onOverlayClicked) {
            onOverlayClicked();
        }
    }

    getStyles() {
        const styleArray = [
            'dialogStyles',
            'overlayStyles',
            'closeButtonStyle',
            'titleStyle',
            'headerStyle',
            'contentStyle'
        ];
        const {styles = {}} = this.props;
        const noStyle = !styles;

        const returnObject = {};

        styleArray.map((item) => {
            returnObject[item] = !noStyle ? Object.assign({}, defaultStyles[item], styles[item]) : {};
        });

        return returnObject;

    }

    getParts(children, part) {
        return React.Children.map(children, (child) => {
            if (child.type instanceof Function && child.type.name === part) {
                return child;
            }
        });
    }

    render() {
        const {isVisible} = this.state;
        //early out
        if (!isVisible) {
            return null;
        }

        let overlay;

        const {
            dialogStyles,
            overlayStyles,
            closeButtonStyle,
            titleStyle,
            contentStyle,
            headerStyle,
            } =  this.getStyles();

        const {
            props: {
                children,
                result = 'info',
                ...rest,
                },
            } = this;

        const head = this.getParts(children, 'Header');
        const body = this.getParts(children, 'Body');

        if (rest.showOverlay) {
            overlay = (
 this.onOverlayClicked()}
                style={overlayStyles}
            >

);
        }

        return (

                {overlay}

                    <div className={`header ${result.toLowerCase()}`} style={headerStyle}>
                         this.hide()}
                           role="button"
                           className="closeButton"
                           style={closeButtonStyle}>×
                        {
                            head && head[0] ? head :
                        }

                        {
                            body ? body[0] : {children}
                        }

        );
    }
}

ModalView.displayName = 'ModalView';

ModalView.propTypes = {
    afterClose: PropTypes.func,
    afterOpen: PropTypes.func,
    beforeClose: PropTypes.func,
    beforeOpen: PropTypes.func,
    body: PropTypes.string,
    children: PropTypes.node,
    hideOnOverlayClicked: PropTypes.bool,
    isVisible: PropTypes.bool,
    onOverlayClicked: PropTypes.func,
    showOverlay: PropTypes.bool,
    styles: React.PropTypes.oneOfType([
        PropTypes.shape({
            closeButtonStyle: PropTypes.object,
            dialogStyles: PropTypes.object,
            overlayStyles: PropTypes.object,
            titleStyle: PropTypes.object
        }),
        PropTypes.bool,
    ]),
    result: PropTypes.string,
    title: PropTypes.string,

};

ModalView.defaultProps = {
    styles: false,
    showOverlay: true,
    hideOnOverlayClicked: false
};

export {
    Body as ModalBody,
    defaultStyles as ModalStyles,
    ModalView,
    Header as ModalHeader,
};
<commit_msg>[UX-234] add support to ModalView to allow animation to play when first displayed<commit_after>import React, {Component, PropTypes} from 'react';
import defaultStyles from './styles';
import Header from './header';
import Body from './body';

class ModalView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isVisible: props.isVisible || false,
            isAnimationReady: false
        };
    }

    componentDidMount() {
        if (this.props.animationClass) {
            // trigger a re-render so the css animation will play
            setTimeout(() => {
                this.setState({
                    isAnimationReady: true
                });
            }, 0);
        }
    }

    componentWillUpdate(nextProps, nextState) {

        const {isVisible} = this.state;
        const {beforeOpen, beforeClose} = this.props;

        if (nextState.isVisible && !isVisible && beforeOpen) {
            beforeOpen();
        }

        if (!nextState.isVisible && isVisible && beforeClose) {
            beforeClose();
        }
    }

    componentDidUpdate(prevProps, prevState) {

        const {isVisible} = this.state;
        const {afterOpen, afterClose} = this.props;

        if (!prevState.isVisible && isVisible && afterOpen) {
            afterOpen();
        }

        if (prevState.isVisible && !isVisible && afterClose) {
            afterClose();
        }
    }

    show() {
        this.setState({isVisible: true});
    }

    hide() {
        this.setState({isVisible: false});
    }

    buildDialogClasses() {
        const { animationClass } = this.props;
        const dialogClasses = ['dialog'];

        if (animationClass) {
            dialogClasses.push(animationClass);
        }

        if (this.state.isAnimationReady) {
            dialogClasses.push('ready');
        }

        return dialogClasses.join(' ');
    }

    onOverlayClicked() {
        const { hideOnOverlayClicked, onOverlayClicked } = this.props;

        if (hideOnOverlayClicked) {
            this.hide();
        }

        if (onOverlayClicked) {
            onOverlayClicked();
        }
    }

    getStyles() {
        const styleArray = [
            'dialogStyles',
            'overlayStyles',
            'closeButtonStyle',
            'titleStyle',
            'headerStyle',
            'contentStyle'
        ];
        const {styles = {}} = this.props;
        const noStyle = !styles;

        const returnObject = {};

        styleArray.map((item) => {
            returnObject[item] = !noStyle ? Object.assign({}, defaultStyles[item], styles[item]) : {};
        });

        return returnObject;

    }

    getParts(children, part) {
        return React.Children.map(children, (child) => {
            if (child.type instanceof Function && child.type.name === part) {
                return child;
            }
        });
    }

    render() {
        const {isVisible} = this.state;
        //early out
        if (!isVisible) {
            return null;
        }

        let overlay;

        const {
            dialogStyles,
            overlayStyles,
            closeButtonStyle,
            titleStyle,
            contentStyle,
            headerStyle,
            } =  this.getStyles();

        const {
            props: {
                children,
                result = 'info',
                ...rest,
                },
            } = this;

        const head = this.getParts(children, 'Header');
        const body = this.getParts(children, 'Body');
        const dialogClasses = this.buildDialogClasses();

        if (rest.showOverlay) {
            overlay = (
 this.onOverlayClicked()}
                style={overlayStyles}
            >

);
        }

        return (

                {overlay}

                    <div className={`header ${result.toLowerCase()}`} style={headerStyle}>
                         this.hide()}
                           role="button"
                           className="closeButton"
                           style={closeButtonStyle}>×
                        {
                            head && head[0] ? head :
                        }

                        {
                            body ? body[0] : {children}
                        }

        );
    }
}

ModalView.displayName = 'ModalView';

ModalView.propTypes = {
    afterClose: PropTypes.func,
    afterOpen: PropTypes.func,
    beforeClose: PropTypes.func,
    beforeOpen: PropTypes.func,
    body: PropTypes.string,
    children: PropTypes.node,
    hideOnOverlayClicked: PropTypes.bool,
    isVisible: PropTypes.bool,
    onOverlayClicked: PropTypes.func,
    showOverlay: PropTypes.bool,
    styles: React.PropTypes.oneOfType([
        PropTypes.shape({
            closeButtonStyle: PropTypes.object,
            dialogStyles: PropTypes.object,
            overlayStyles: PropTypes.object,
            titleStyle: PropTypes.object
        }),
        PropTypes.bool,
    ]),
    animationClass: PropTypes.string,
    result: PropTypes.string,
    title: PropTypes.string,

};

ModalView.defaultProps = {
    styles: false,
    showOverlay: true,
    hideOnOverlayClicked: false
};

export {
    Body as ModalBody,
    defaultStyles as ModalStyles,
    ModalView,
    Header as ModalHeader,
};
<|endoftext|>


<commit_before>var config = require('../../server/config.json');
var path = require('path');

module.exports = function(user) {
  //send verification email after registration
  user.afterRemote('create', function(context, user) {
    console.log('> user.afterRemote triggered');

    var options = {
      type: 'email',
      to: user.email,
      from: 'noreply@loopback.com',
      subject: 'Thanks for registering.',
      template: path.resolve(__dirname, '../../server/views/verify.ejs'),
      redirect: '/verified',
      user: user
    };

    user.verify(options, function(err, response) {
      if (err) {
        next(err);
        return;
      }

      console.log('> verification email sent:', response);

      context.res.render('response', {
        title: 'Signed up successfully',
        content: 'Please check your email and click on the verification link '
          + 'before logging in.',
        redirectTo: '/',
        redirectToLinkText: 'Log in'
      });
    });
  });

  //send password reset link when requested
  user.on('resetPasswordRequest', function(info) {
    var url = 'http://' + config.host + ':' + config.port + '/reset-password';
    var html = 'Click here to reset your password';

    user.app.models.Email.send({
      to: info.email,
      from: info.email,
      subject: 'Password reset',
      html: html
    }, function(err) {
      if (err) return console.log('> error sending password reset email');
      console.log('> sending password reset email to:', info.email);
    });
  });
};
<commit_msg>Update user.js<commit_after>var config = require('../../server/config.json');
var path = require('path');

module.exports = function(user) {
  //send verification email after registration
  user.afterRemote('create', function(context, user, next) {
    console.log('> user.afterRemote triggered');

    var options = {
      type: 'email',
      to: user.email,
      from: 'noreply@loopback.com',
      subject: 'Thanks for registering.',
      template: path.resolve(__dirname, '../../server/views/verify.ejs'),
      redirect: '/verified',
      user: user
    };

    user.verify(options, function(err, response) {
      if (err) {
        next(err);
        return;
      }

      console.log('> verification email sent:', response);

      context.res.render('response', {
        title: 'Signed up successfully',
        content: 'Please check your email and click on the verification link '
          + 'before logging in.',
        redirectTo: '/',
        redirectToLinkText: 'Log in'
      });
    });
  });

  //send password reset link when requested
  user.on('resetPasswordRequest', function(info) {
    var url = 'http://' + config.host + ':' + config.port + '/reset-password';
    var html = 'Click here to reset your password';

    user.app.models.Email.send({
      to: info.email,
      from: info.email,
      subject: 'Password reset',
      html: html
    }, function(err) {
      if (err) return console.log('> error sending password reset email');
      console.log('> sending password reset email to:', info.email);
    });
  });
};
<|endoftext|>


<commit_before>var fs = require('fs'),
	page = require('webpage').create(),
	system = require('system'),
	address, output, size, renderTimeout, disableAnimations;

if (system.args.length !== 8) {
	console.log('Usage: rasterize.js URL filename renderTimeout disableAnimations userAgent width height');
	phantom.exit(1);
} else {
	address = system.args[1];
	output = system.args[2];
	renderTimeout = system.args[3];
	disableAnimations = system.args[4] === 'true';
	page.settings.userAgent = system.args[5];
	page.viewportSize = { width: system.args[6], height: system.args[7] };
	//page.clipRect = { left: 0, top: 0, width: system.args[6], height: system.args[7] };
	page.zoomFactor = 1;
	page.onConsoleMessage = function(msg) { console.log(msg); };
	page.open(address, function (status) {
		if (status !== 'success') {
			console.log('Unable to load the address!');
			phantom.exit(1);
		} else {
			if (disableAnimations) {
				page.evaluate(function() {
					// Disable jQuery animations
					try {
						$.fx.off = true;
					} catch (e) {
						// Fail silently if jQuery is not present
					}

					// Disable CSS animations
					var disableAnimationStyles = '-webkit-transition: none !important;' +
						'-moz-transition: none !important;' +
						'-ms-transition: none !important;' +
						'-o-transition: none !important;' +
						'transition: none !important;'

					var animationStyles = document.createElement('style');
					animationStyles.type = 'text/css';
					animationStyles.innerHTML = '* {' + disableAnimationStyles + '}';
					document.head.appendChild(animationStyles);

					// Disable HTML5 video
					var videoTags = document.getElementsByTagName('video');
					for (var i in videoTags) {
						videoTags[i].pause();
					}
				});
			}

			window.setTimeout(function () {
				page.render(output);
				phantom.exit();
			}, renderTimeout);
		}
	});
}<commit_msg>Improved disabling of animations<commit_after>var fs = require('fs'),
	page = require('webpage').create(),
	system = require('system'),
	address, output, size, renderTimeout, disableAnimations;

if (system.args.length !== 8) {
	console.log('Usage: rasterize.js URL filename renderTimeout disableAnimations userAgent width height');
	phantom.exit(1);
} else {
	address = system.args[1];
	output = system.args[2];
	renderTimeout = system.args[3];
	disableAnimations = system.args[4] === 'true';
	page.settings.userAgent = system.args[5];
	page.viewportSize = { width: system.args[6], height: system.args[7] };
	//page.clipRect = { left: 0, top: 0, width: system.args[6], height: system.args[7] };
	page.zoomFactor = 1;
	page.onConsoleMessage = function(msg) { console.log(msg); };
	page.open(address, function (status) {
		if (status !== 'success') {
			console.log('Unable to load the address!');
			phantom.exit(1);
		} else {
			if (disableAnimations) {
				page.evaluate(function() {
					// Disable jQuery animations
					try {
						$.fx.off = true;
					} catch (e) {
						// Fail silently if jQuery is not present
					}

					// Disable CSS animations
					var disableAnimationStyles = '-webkit-transition: none !important;' +
						'-moz-transition: none !important;' +
						'-ms-transition: none !important;' +
						'-o-transition: none !important;' +
						'transition: none !important;' +
						'-webkit-animation: none !important;' +
						'-moz-animation: none !important;' +
						'-ms-animation: none !important;' +
						'-o-animation: none !important;' +
						'animation: none !important;';

					var animationStyles = document.createElement('style');
					animationStyles.type = 'text/css';
					animationStyles.innerHTML = '* {' + disableAnimationStyles + '}';
					document.head.appendChild(animationStyles);
				});
			}

			window.setTimeout(function () {
				page.render(output);
				phantom.exit();
			}, renderTimeout);
		}
	});
}<|endoftext|>