<element name="td-item" extends="li" attributes="item editing" on-blur="commitAction">
	<link rel="stylesheet" href="td-item.css">
	<template>
		<div class="view {{completed: item.completed; editing: editing}}" hidden?="{{editing}}" on-dblclick="editAction">
			<input type="checkbox" class="toggle" checked="{{item.completed}}" on-click="itemChangeAction">
			<label>{{item.title}}</label>
			<button class="destroy" on-click="destroyAction"></button>
		</div>
		<input id="edit" class="edit" value="{{title}}" hidden?="{{!editing}}" on-keyup="keyAction">
	</template>
	<script>
		var ENTER_KEY = 13;
		var ESC_KEY = 27;
		Polymer.register(this, {
			editing: false,
			keyAction: function(e) {
				switch (e.keyCode) {
					case ESC_KEY:
						this.cancelAction();
						break;
					case ENTER_KEY:
						this.commitAction();
						break;
				}
			},
			editAction: function() {
				this.editing = true;
				this.title = this.item.title;
				// schedule focus for the end of microtask, when the input will be visible
				Platform.flush();
				this.asyncMethod(function() {
					this.$.edit.focus();
				});
			},
			commitAction: function() {
				if (this.editing) {
					this.editing = false;
					this.item.title = this.title.trim();
					if (this.item.title === '') {
						this.destroyAction();
					}
				}
			},
			cancelAction: function() {
				this.editing = false;
			},
			itemChangeAction: function() {
				this.fire('td-item-changed');
			},
			destroyAction: function() {
				this.fire('td-destroy-item', this.item);
			}
		});
	</script>
</element>
