function WidgetValues (c) { if (c) { this.container = c; this._init (); } } // WidgetValues WidgetValues.prototype._init = function () { var ta = this.container.getElementsByTagName ('textarea')[0]; if (!ta) return; this.name = this.container.getAttribute ('data-widget-name') || ta.name || ''; this.separatorPattern = new RegExp (this.container.getAttribute ('data-widget-separator') || '\\s+'); this.defaultValues = ta.defaultValue.length ? ta.defaultValue.split (this.separatorPattern) : []; this.initialValues = ta.value.length ? ta.value.split (this.separatorPattern) : []; this.clear (); this.appendValues (this.initialValues); }; // _init WidgetValues.prototype._clear = function () { this.firstField = null; this.lastField = null; this.container.innerHTML = ''; }; // _clear WidgetValues.prototype.appendValues = function (values) { var self = this; for (var i = 0; i < values.length; i++) { var field = this.createField (values[i]); field.wvRemove = function () { self._removeField (this) }; field.wvMoveUp = function () { self._moveUpField (this) }; field.wvMoveDown = function () { self._moveDownField (this) }; var parent = this.lastField ? this.lastField.parentNode : null; parent = parent ? parent : this.fieldsParent; parent.insertBefore (field, this.lastField ? this.lastField.nextSibling : null); this.lastField = field; this.firstField = this.firstField || field; } }; // appendValues WidgetValues.prototype.reset = function () { this.clear (); this.appendValues (this.defaultValues); }; // reset WidgetValues.prototype._removeField = function (field) { if (this.firstField == field) { this.firstField = this._getNextField (field); } if (this.lastField == field) { this.lastField = this._getPreviousField (field); } field.parentNode.removeChild (field); }; // _removeField WidgetValues.prototype._moveUpField = function (field) { this._swapFields (field, this._getPreviousField (field)); }; // _moveUpField WidgetValues.prototype._moveDownField = function (field) { this._swapFields (field, this._getNextField (field)); }; // _moveDownField WidgetValues.prototype._swapFields = function (f1, f2) { if (!f1 || !f2) return; var ph = document.createElement (f1.tagName || 'x'); f1.parentNode.replaceChild (ph, f1); f2.parentNode.replaceChild (f1, f2); ph.parentNode.replaceChild (f2, ph); }; // _swapFields WidgetValues.prototype._getNextField = function (field) { var n = field.nextSibling; while (n != null) { if (this.isField (n)) { return n; } n = n.nextSibling; } return null; }; // _getNextField WidgetValues.prototype._getPreviousField = function (field) { var n = field.previousSibling; while (n != null) { if (this.isField (n)) { return n; } n = n.previousSibling; } return null; }; // _getPreviousField WidgetValues.prototype.createButton = function () { var el; try { el = document.createElement ('button'); el.setAttribute('type', 'button'); } catch (e) { el = document.createElement ('