var ElementPageAlias = qs.createObject(); ElementPageAlias.prototype = { _sources: {}, _alias: null, _pattern: /^[-_a-zA-Z0-9\.]+$/, _parentVal: '', initialize: function (element, sources) { var that = this, defaultLang = qs.constant('DEFAULT_LANGUAGE'); sources = sources || ['title']; sources = $.isArray(sources) ? sources : [sources]; if (!(this._alias = document.getElementById(element))) { throw new Error('Element with id "source" not found !'); } this._sources = {}; _.forEach(sources, function (id) { var handle; if ((handle = (document.getElementById(id) || document.getElementById(id + '-' + id + '_' + defaultLang)))) { that._sources[id] = handle; that._addEvent(handle, 'blur', function () {that._onSourceBlur()}); } else { throw new Error('Element with id "' + id + '" not found !'); } }); this._addEvent(this._alias, 'keypress', function () {that._onAliasKeypress()}); this._addEvent(this._alias, 'keyup', function () {that._onAliasKeyup()}); }, _buildAlias: function (value) { if (!value || value == '') { return ''; } return value.replace(/^\s+/, "").replace(/\s+$/, "").replace(/&+/, "-and-") .replace(/[^\sA-Za-z0-9_\.-]/g, "").replace(/\s+/g, "-").toLowerCase(); }, _getSourceValue: function () { var id, value = []; for (id in this._sources) { if (this._sources.hasOwnProperty(id)) { /* ящо хоча б одне поле з "sources" порожнє, то аліас формуватись немає (QSF-7 пункт 14) */ if ('' == _.str.trim(this._sources[id].value)) { return ''; } value.push(this._sources[id].value); } } return value.join(' '); }, _onSourceBlur: function () { var source = this._getSourceValue(); if (source != '' && this._alias.value == '') { this._alias.value = this._buildAlias(source); } }, _onAliasKeyup: function() { if (this._alias.value !== '' && !this._alias.value.match(this._pattern)) { this._alias.value = this._parentVal; } }, _onAliasKeypress: function() { if (this._alias.value == '' || this._alias.value.match(this._pattern)) { this._parentVal = this._alias.value; } }, _addEvent: function (obj, type, func) { if ('object' != typeof obj && !(obj = document.getElementById(obj))) { return; } if (obj.addEventListener) { obj.addEventListener(type, func, false); } else if (obj.attachEvent) { var f = function(e) {func.call(obj, e);}; obj.attachEvent('on' + type, f); } } };