window.addEvent('domready', function() {
	$$(".tl_nameEmailWidget").each(function (el) {
		new Sortables(el.getElement(".sortable"), {
			contstrain: true,
			opacity: 0.6,
			handle: ".drag-handle",
			clone: false,
			onComplete: function (el) {
				var tbody = el.getParent('tbody'),
					rows = tbody.getChildren('tr'),
					input, i, j;

				for (i = 0; i < rows.length; i++) {
					var childs = rows[i].getChildren();
					for (j = 0; j < childs.length; j++) {
						if (input = childs[j].getFirst('input')) {
							input.name = input.name.replace(/\[[0-9]+\]/g, '[' + i + ']');
						}
					}
				}
			}
		});
	});
});

var NameEmailWidget = {
	doCommand: function (el, command, id) {
		var table = $(id),
			tbody = table.getElement('tbody'),
			parent = $(el).getParent('tr'),
			rows = tbody.getChildren(),
			tabindex = tbody.get('data-tabindex'),
			input, select, childs, a, i, j, inputs, tr;

		Backend.getScrollOffset();

		switch (command) {
			case 'copy':
				tr = new Element('tr');
				childs = parent.getChildren();
				for (i = 0; i < childs.length; i++) {
					var next = childs[i].clone(true).inject(tr, 'bottom');
					next.getChildren('input[type="text"]').each(function (el) {
						el.value = "";
					});
				}
				tr.inject(parent, 'after');
				break;
			case 'up':
				if (tr = parent.getPrevious('tr')) {
					parent.inject(tr, 'before');
				} else {
					parent.inject(tbody, 'bottom');
				}
				break;
			case 'down':
				if (tr = parent.getNext('tr')) {
					parent.inject(tr, 'after');
				} else {
					parent.inject(tbody, 'top');
				}
				break;
			case 'delete':
				if (rows.length > 1) {
					parent.destroy();
				}
				break;
		}

		rows = tbody.getChildren();

		for (i = 0; i < rows.length; i++) {
			childs = rows[i].getChildren();
			for (j = 0; j < childs.length; j++) {
				if (inputs = childs[j].getChildren('input[type="text"]')) {
					for (var k = 0; k < inputs.length; k++) {
						inputs[k].name = inputs[k].name.replace(/\[[0-9]+\]/g, '[' + i + ']');
					}
				}
			}
		}
	}
};
