-
+ 803DA95194D0084856EE96C065D38AF9BC8E1F3185245B87483849C9FD9FBD180349D9F128D750679D7BE26C0F9F581B85DBEBFB7F0842A22D83C0DD4467FEEE
mp-wp/wp-includes/js/scriptaculous/controls.js
(0 . 0)(1 . 965)
107812 // script.aculo.us controls.js v1.8.0, Tue Nov 06 15:01:40 +0300 2007
107813
107814 // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
107815 // (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
107816 // (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
107817 // Contributors:
107818 // Richard Livsey
107819 // Rahul Bhargava
107820 // Rob Wills
107821 //
107822 // script.aculo.us is freely distributable under the terms of an MIT-style license.
107823 // For details, see the script.aculo.us web site: http://script.aculo.us/
107824
107825 // Autocompleter.Base handles all the autocompletion functionality
107826 // that's independent of the data source for autocompletion. This
107827 // includes drawing the autocompletion menu, observing keyboard
107828 // and mouse events, and similar.
107829 //
107830 // Specific autocompleters need to provide, at the very least,
107831 // a getUpdatedChoices function that will be invoked every time
107832 // the text inside the monitored textbox changes. This method
107833 // should get the text for which to provide autocompletion by
107834 // invoking this.getToken(), NOT by directly accessing
107835 // this.element.value. This is to allow incremental tokenized
107836 // autocompletion. Specific auto-completion logic (AJAX, etc)
107837 // belongs in getUpdatedChoices.
107838 //
107839 // Tokenized incremental autocompletion is enabled automatically
107840 // when an autocompleter is instantiated with the 'tokens' option
107841 // in the options parameter, e.g.:
107842 // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
107843 // will incrementally autocomplete with a comma as the token.
107844 // Additionally, ',' in the above example can be replaced with
107845 // a token array, e.g. { tokens: [',', '\n'] } which
107846 // enables autocompletion on multiple tokens. This is most
107847 // useful when one of the tokens is \n (a newline), as it
107848 // allows smart autocompletion after linebreaks.
107849
107850 if(typeof Effect == 'undefined')
107851 throw("controls.js requires including script.aculo.us' effects.js library");
107852
107853 var Autocompleter = { }
107854 Autocompleter.Base = Class.create({
107855 baseInitialize: function(element, update, options) {
107856 element = $(element)
107857 this.element = element;
107858 this.update = $(update);
107859 this.hasFocus = false;
107860 this.changed = false;
107861 this.active = false;
107862 this.index = 0;
107863 this.entryCount = 0;
107864 this.oldElementValue = this.element.value;
107865
107866 if(this.setOptions)
107867 this.setOptions(options);
107868 else
107869 this.options = options || { };
107870
107871 this.options.paramName = this.options.paramName || this.element.name;
107872 this.options.tokens = this.options.tokens || [];
107873 this.options.frequency = this.options.frequency || 0.4;
107874 this.options.minChars = this.options.minChars || 1;
107875 this.options.onShow = this.options.onShow ||
107876 function(element, update){
107877 if(!update.style.position || update.style.position=='absolute') {
107878 update.style.position = 'absolute';
107879 Position.clone(element, update, {
107880 setHeight: false,
107881 offsetTop: element.offsetHeight
107882 });
107883 }
107884 Effect.Appear(update,{duration:0.15});
107885 };
107886 this.options.onHide = this.options.onHide ||
107887 function(element, update){ new Effect.Fade(update,{duration:0.15}) };
107888
107889 if(typeof(this.options.tokens) == 'string')
107890 this.options.tokens = new Array(this.options.tokens);
107891 // Force carriage returns as token delimiters anyway
107892 if (!this.options.tokens.include('\n'))
107893 this.options.tokens.push('\n');
107894
107895 this.observer = null;
107896
107897 this.element.setAttribute('autocomplete','off');
107898
107899 Element.hide(this.update);
107900
107901 Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
107902 Event.observe(this.element, 'keypress', this.onKeyPress.bindAsEventListener(this));
107903 },
107904
107905 show: function() {
107906 if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
107907 if(!this.iefix &&
107908 (Prototype.Browser.IE) &&
107909 (Element.getStyle(this.update, 'position')=='absolute')) {
107910 new Insertion.After(this.update,
107911 '<iframe id="' + this.update.id + '_iefix" '+
107912 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
107913 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
107914 this.iefix = $(this.update.id+'_iefix');
107915 }
107916 if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
107917 },
107918
107919 fixIEOverlapping: function() {
107920 Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
107921 this.iefix.style.zIndex = 1;
107922 this.update.style.zIndex = 2;
107923 Element.show(this.iefix);
107924 },
107925
107926 hide: function() {
107927 this.stopIndicator();
107928 if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
107929 if(this.iefix) Element.hide(this.iefix);
107930 },
107931
107932 startIndicator: function() {
107933 if(this.options.indicator) Element.show(this.options.indicator);
107934 },
107935
107936 stopIndicator: function() {
107937 if(this.options.indicator) Element.hide(this.options.indicator);
107938 },
107939
107940 onKeyPress: function(event) {
107941 if(this.active)
107942 switch(event.keyCode) {
107943 case Event.KEY_TAB:
107944 case Event.KEY_RETURN:
107945 this.selectEntry();
107946 Event.stop(event);
107947 case Event.KEY_ESC:
107948 this.hide();
107949 this.active = false;
107950 Event.stop(event);
107951 return;
107952 case Event.KEY_LEFT:
107953 case Event.KEY_RIGHT:
107954 return;
107955 case Event.KEY_UP:
107956 this.markPrevious();
107957 this.render();
107958 if(Prototype.Browser.WebKit) Event.stop(event);
107959 return;
107960 case Event.KEY_DOWN:
107961 this.markNext();
107962 this.render();
107963 if(Prototype.Browser.WebKit) Event.stop(event);
107964 return;
107965 }
107966 else
107967 if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
107968 (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
107969
107970 this.changed = true;
107971 this.hasFocus = true;
107972
107973 if(this.observer) clearTimeout(this.observer);
107974 this.observer =
107975 setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
107976 },
107977
107978 activate: function() {
107979 this.changed = false;
107980 this.hasFocus = true;
107981 this.getUpdatedChoices();
107982 },
107983
107984 onHover: function(event) {
107985 var element = Event.findElement(event, 'LI');
107986 if(this.index != element.autocompleteIndex)
107987 {
107988 this.index = element.autocompleteIndex;
107989 this.render();
107990 }
107991 Event.stop(event);
107992 },
107993
107994 onClick: function(event) {
107995 var element = Event.findElement(event, 'LI');
107996 this.index = element.autocompleteIndex;
107997 this.selectEntry();
107998 this.hide();
107999 },
108000
108001 onBlur: function(event) {
108002 // needed to make click events working
108003 setTimeout(this.hide.bind(this), 250);
108004 this.hasFocus = false;
108005 this.active = false;
108006 },
108007
108008 render: function() {
108009 if(this.entryCount > 0) {
108010 for (var i = 0; i < this.entryCount; i++)
108011 this.index==i ?
108012 Element.addClassName(this.getEntry(i),"selected") :
108013 Element.removeClassName(this.getEntry(i),"selected");
108014 if(this.hasFocus) {
108015 this.show();
108016 this.active = true;
108017 }
108018 } else {
108019 this.active = false;
108020 this.hide();
108021 }
108022 },
108023
108024 markPrevious: function() {
108025 if(this.index > 0) this.index--
108026 else this.index = this.entryCount-1;
108027 this.getEntry(this.index).scrollIntoView(true);
108028 },
108029
108030 markNext: function() {
108031 if(this.index < this.entryCount-1) this.index++
108032 else this.index = 0;
108033 this.getEntry(this.index).scrollIntoView(false);
108034 },
108035
108036 getEntry: function(index) {
108037 return this.update.firstChild.childNodes[index];
108038 },
108039
108040 getCurrentEntry: function() {
108041 return this.getEntry(this.index);
108042 },
108043
108044 selectEntry: function() {
108045 this.active = false;
108046 this.updateElement(this.getCurrentEntry());
108047 },
108048
108049 updateElement: function(selectedElement) {
108050 if (this.options.updateElement) {
108051 this.options.updateElement(selectedElement);
108052 return;
108053 }
108054 var value = '';
108055 if (this.options.select) {
108056 var nodes = $(selectedElement).select('.' + this.options.select) || [];
108057 if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
108058 } else
108059 value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
108060
108061 var bounds = this.getTokenBounds();
108062 if (bounds[0] != -1) {
108063 var newValue = this.element.value.substr(0, bounds[0]);
108064 var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
108065 if (whitespace)
108066 newValue += whitespace[0];
108067 this.element.value = newValue + value + this.element.value.substr(bounds[1]);
108068 } else {
108069 this.element.value = value;
108070 }
108071 this.oldElementValue = this.element.value;
108072 this.element.focus();
108073
108074 if (this.options.afterUpdateElement)
108075 this.options.afterUpdateElement(this.element, selectedElement);
108076 },
108077
108078 updateChoices: function(choices) {
108079 if(!this.changed && this.hasFocus) {
108080 this.update.innerHTML = choices;
108081 Element.cleanWhitespace(this.update);
108082 Element.cleanWhitespace(this.update.down());
108083
108084 if(this.update.firstChild && this.update.down().childNodes) {
108085 this.entryCount =
108086 this.update.down().childNodes.length;
108087 for (var i = 0; i < this.entryCount; i++) {
108088 var entry = this.getEntry(i);
108089 entry.autocompleteIndex = i;
108090 this.addObservers(entry);
108091 }
108092 } else {
108093 this.entryCount = 0;
108094 }
108095
108096 this.stopIndicator();
108097 this.index = 0;
108098
108099 if(this.entryCount==1 && this.options.autoSelect) {
108100 this.selectEntry();
108101 this.hide();
108102 } else {
108103 this.render();
108104 }
108105 }
108106 },
108107
108108 addObservers: function(element) {
108109 Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
108110 Event.observe(element, "click", this.onClick.bindAsEventListener(this));
108111 },
108112
108113 onObserverEvent: function() {
108114 this.changed = false;
108115 this.tokenBounds = null;
108116 if(this.getToken().length>=this.options.minChars) {
108117 this.getUpdatedChoices();
108118 } else {
108119 this.active = false;
108120 this.hide();
108121 }
108122 this.oldElementValue = this.element.value;
108123 },
108124
108125 getToken: function() {
108126 var bounds = this.getTokenBounds();
108127 return this.element.value.substring(bounds[0], bounds[1]).strip();
108128 },
108129
108130 getTokenBounds: function() {
108131 if (null != this.tokenBounds) return this.tokenBounds;
108132 var value = this.element.value;
108133 if (value.strip().empty()) return [-1, 0];
108134 var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
108135 var offset = (diff == this.oldElementValue.length ? 1 : 0);
108136 var prevTokenPos = -1, nextTokenPos = value.length;
108137 var tp;
108138 for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
108139 tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
108140 if (tp > prevTokenPos) prevTokenPos = tp;
108141 tp = value.indexOf(this.options.tokens[index], diff + offset);
108142 if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
108143 }
108144 return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
108145 }
108146 });
108147
108148 Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
108149 var boundary = Math.min(newS.length, oldS.length);
108150 for (var index = 0; index < boundary; ++index)
108151 if (newS[index] != oldS[index])
108152 return index;
108153 return boundary;
108154 };
108155
108156 Ajax.Autocompleter = Class.create(Autocompleter.Base, {
108157 initialize: function(element, update, url, options) {
108158 this.baseInitialize(element, update, options);
108159 this.options.asynchronous = true;
108160 this.options.onComplete = this.onComplete.bind(this);
108161 this.options.defaultParams = this.options.parameters || null;
108162 this.url = url;
108163 },
108164
108165 getUpdatedChoices: function() {
108166 this.startIndicator();
108167
108168 var entry = encodeURIComponent(this.options.paramName) + '=' +
108169 encodeURIComponent(this.getToken());
108170
108171 this.options.parameters = this.options.callback ?
108172 this.options.callback(this.element, entry) : entry;
108173
108174 if(this.options.defaultParams)
108175 this.options.parameters += '&' + this.options.defaultParams;
108176
108177 new Ajax.Request(this.url, this.options);
108178 },
108179
108180 onComplete: function(request) {
108181 this.updateChoices(request.responseText);
108182 }
108183 });
108184
108185 // The local array autocompleter. Used when you'd prefer to
108186 // inject an array of autocompletion options into the page, rather
108187 // than sending out Ajax queries, which can be quite slow sometimes.
108188 //
108189 // The constructor takes four parameters. The first two are, as usual,
108190 // the id of the monitored textbox, and id of the autocompletion menu.
108191 // The third is the array you want to autocomplete from, and the fourth
108192 // is the options block.
108193 //
108194 // Extra local autocompletion options:
108195 // - choices - How many autocompletion choices to offer
108196 //
108197 // - partialSearch - If false, the autocompleter will match entered
108198 // text only at the beginning of strings in the
108199 // autocomplete array. Defaults to true, which will
108200 // match text at the beginning of any *word* in the
108201 // strings in the autocomplete array. If you want to
108202 // search anywhere in the string, additionally set
108203 // the option fullSearch to true (default: off).
108204 //
108205 // - fullSsearch - Search anywhere in autocomplete array strings.
108206 //
108207 // - partialChars - How many characters to enter before triggering
108208 // a partial match (unlike minChars, which defines
108209 // how many characters are required to do any match
108210 // at all). Defaults to 2.
108211 //
108212 // - ignoreCase - Whether to ignore case when autocompleting.
108213 // Defaults to true.
108214 //
108215 // It's possible to pass in a custom function as the 'selector'
108216 // option, if you prefer to write your own autocompletion logic.
108217 // In that case, the other options above will not apply unless
108218 // you support them.
108219
108220 Autocompleter.Local = Class.create(Autocompleter.Base, {
108221 initialize: function(element, update, array, options) {
108222 this.baseInitialize(element, update, options);
108223 this.options.array = array;
108224 },
108225
108226 getUpdatedChoices: function() {
108227 this.updateChoices(this.options.selector(this));
108228 },
108229
108230 setOptions: function(options) {
108231 this.options = Object.extend({
108232 choices: 10,
108233 partialSearch: true,
108234 partialChars: 2,
108235 ignoreCase: true,
108236 fullSearch: false,
108237 selector: function(instance) {
108238 var ret = []; // Beginning matches
108239 var partial = []; // Inside matches
108240 var entry = instance.getToken();
108241 var count = 0;
108242
108243 for (var i = 0; i < instance.options.array.length &&
108244 ret.length < instance.options.choices ; i++) {
108245
108246 var elem = instance.options.array[i];
108247 var foundPos = instance.options.ignoreCase ?
108248 elem.toLowerCase().indexOf(entry.toLowerCase()) :
108249 elem.indexOf(entry);
108250
108251 while (foundPos != -1) {
108252 if (foundPos == 0 && elem.length != entry.length) {
108253 ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
108254 elem.substr(entry.length) + "</li>");
108255 break;
108256 } else if (entry.length >= instance.options.partialChars &&
108257 instance.options.partialSearch && foundPos != -1) {
108258 if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
108259 partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
108260 elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
108261 foundPos + entry.length) + "</li>");
108262 break;
108263 }
108264 }
108265
108266 foundPos = instance.options.ignoreCase ?
108267 elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
108268 elem.indexOf(entry, foundPos + 1);
108269
108270 }
108271 }
108272 if (partial.length)
108273 ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
108274 return "<ul>" + ret.join('') + "</ul>";
108275 }
108276 }, options || { });
108277 }
108278 });
108279
108280 // AJAX in-place editor and collection editor
108281 // Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
108282
108283 // Use this if you notice weird scrolling problems on some browsers,
108284 // the DOM might be a bit confused when this gets called so do this
108285 // waits 1 ms (with setTimeout) until it does the activation
108286 Field.scrollFreeActivate = function(field) {
108287 setTimeout(function() {
108288 Field.activate(field);
108289 }, 1);
108290 }
108291
108292 Ajax.InPlaceEditor = Class.create({
108293 initialize: function(element, url, options) {
108294 this.url = url;
108295 this.element = element = $(element);
108296 this.prepareOptions();
108297 this._controls = { };
108298 arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
108299 Object.extend(this.options, options || { });
108300 if (!this.options.formId && this.element.id) {
108301 this.options.formId = this.element.id + '-inplaceeditor';
108302 if ($(this.options.formId))
108303 this.options.formId = '';
108304 }
108305 if (this.options.externalControl)
108306 this.options.externalControl = $(this.options.externalControl);
108307 if (!this.options.externalControl)
108308 this.options.externalControlOnly = false;
108309 this._originalBackground = this.element.getStyle('background-color') || 'transparent';
108310 this.element.title = this.options.clickToEditText;
108311 this._boundCancelHandler = this.handleFormCancellation.bind(this);
108312 this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
108313 this._boundFailureHandler = this.handleAJAXFailure.bind(this);
108314 this._boundSubmitHandler = this.handleFormSubmission.bind(this);
108315 this._boundWrapperHandler = this.wrapUp.bind(this);
108316 this.registerListeners();
108317 },
108318 checkForEscapeOrReturn: function(e) {
108319 if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
108320 if (Event.KEY_ESC == e.keyCode)
108321 this.handleFormCancellation(e);
108322 else if (Event.KEY_RETURN == e.keyCode)
108323 this.handleFormSubmission(e);
108324 },
108325 createControl: function(mode, handler, extraClasses) {
108326 var control = this.options[mode + 'Control'];
108327 var text = this.options[mode + 'Text'];
108328 if ('button' == control) {
108329 var btn = document.createElement('input');
108330 btn.type = 'submit';
108331 btn.value = text;
108332 btn.className = 'editor_' + mode + '_button';
108333 if ('cancel' == mode)
108334 btn.onclick = this._boundCancelHandler;
108335 this._form.appendChild(btn);
108336 this._controls[mode] = btn;
108337 } else if ('link' == control) {
108338 var link = document.createElement('a');
108339 link.href = '#';
108340 link.appendChild(document.createTextNode(text));
108341 link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
108342 link.className = 'editor_' + mode + '_link';
108343 if (extraClasses)
108344 link.className += ' ' + extraClasses;
108345 this._form.appendChild(link);
108346 this._controls[mode] = link;
108347 }
108348 },
108349 createEditField: function() {
108350 var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
108351 var fld;
108352 if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
108353 fld = document.createElement('input');
108354 fld.type = 'text';
108355 var size = this.options.size || this.options.cols || 0;
108356 if (0 < size) fld.size = size;
108357 } else {
108358 fld = document.createElement('textarea');
108359 fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
108360 fld.cols = this.options.cols || 40;
108361 }
108362 fld.name = this.options.paramName;
108363 fld.value = text; // No HTML breaks conversion anymore
108364 fld.className = 'editor_field';
108365 if (this.options.submitOnBlur)
108366 fld.onblur = this._boundSubmitHandler;
108367 this._controls.editor = fld;
108368 if (this.options.loadTextURL)
108369 this.loadExternalText();
108370 this._form.appendChild(this._controls.editor);
108371 },
108372 createForm: function() {
108373 var ipe = this;
108374 function addText(mode, condition) {
108375 var text = ipe.options['text' + mode + 'Controls'];
108376 if (!text || condition === false) return;
108377 ipe._form.appendChild(document.createTextNode(text));
108378 };
108379 this._form = $(document.createElement('form'));
108380 this._form.id = this.options.formId;
108381 this._form.addClassName(this.options.formClassName);
108382 this._form.onsubmit = this._boundSubmitHandler;
108383 this.createEditField();
108384 if ('textarea' == this._controls.editor.tagName.toLowerCase())
108385 this._form.appendChild(document.createElement('br'));
108386 if (this.options.onFormCustomization)
108387 this.options.onFormCustomization(this, this._form);
108388 addText('Before', this.options.okControl || this.options.cancelControl);
108389 this.createControl('ok', this._boundSubmitHandler);
108390 addText('Between', this.options.okControl && this.options.cancelControl);
108391 this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
108392 addText('After', this.options.okControl || this.options.cancelControl);
108393 },
108394 destroy: function() {
108395 if (this._oldInnerHTML)
108396 this.element.innerHTML = this._oldInnerHTML;
108397 this.leaveEditMode();
108398 this.unregisterListeners();
108399 },
108400 enterEditMode: function(e) {
108401 if (this._saving || this._editing) return;
108402 this._editing = true;
108403 this.triggerCallback('onEnterEditMode');
108404 if (this.options.externalControl)
108405 this.options.externalControl.hide();
108406 this.element.hide();
108407 this.createForm();
108408 this.element.parentNode.insertBefore(this._form, this.element);
108409 if (!this.options.loadTextURL)
108410 this.postProcessEditField();
108411 if (e) Event.stop(e);
108412 },
108413 enterHover: function(e) {
108414 if (this.options.hoverClassName)
108415 this.element.addClassName(this.options.hoverClassName);
108416 if (this._saving) return;
108417 this.triggerCallback('onEnterHover');
108418 },
108419 getText: function() {
108420 return this.element.innerHTML;
108421 },
108422 handleAJAXFailure: function(transport) {
108423 this.triggerCallback('onFailure', transport);
108424 if (this._oldInnerHTML) {
108425 this.element.innerHTML = this._oldInnerHTML;
108426 this._oldInnerHTML = null;
108427 }
108428 },
108429 handleFormCancellation: function(e) {
108430 this.wrapUp();
108431 if (e) Event.stop(e);
108432 },
108433 handleFormSubmission: function(e) {
108434 var form = this._form;
108435 var value = $F(this._controls.editor);
108436 this.prepareSubmission();
108437 var params = this.options.callback(form, value) || '';
108438 if (Object.isString(params))
108439 params = params.toQueryParams();
108440 params.editorId = this.element.id;
108441 if (this.options.htmlResponse) {
108442 var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
108443 Object.extend(options, {
108444 parameters: params,
108445 onComplete: this._boundWrapperHandler,
108446 onFailure: this._boundFailureHandler
108447 });
108448 new Ajax.Updater({ success: this.element }, this.url, options);
108449 } else {
108450 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
108451 Object.extend(options, {
108452 parameters: params,
108453 onComplete: this._boundWrapperHandler,
108454 onFailure: this._boundFailureHandler
108455 });
108456 new Ajax.Request(this.url, options);
108457 }
108458 if (e) Event.stop(e);
108459 },
108460 leaveEditMode: function() {
108461 this.element.removeClassName(this.options.savingClassName);
108462 this.removeForm();
108463 this.leaveHover();
108464 this.element.style.backgroundColor = this._originalBackground;
108465 this.element.show();
108466 if (this.options.externalControl)
108467 this.options.externalControl.show();
108468 this._saving = false;
108469 this._editing = false;
108470 this._oldInnerHTML = null;
108471 this.triggerCallback('onLeaveEditMode');
108472 },
108473 leaveHover: function(e) {
108474 if (this.options.hoverClassName)
108475 this.element.removeClassName(this.options.hoverClassName);
108476 if (this._saving) return;
108477 this.triggerCallback('onLeaveHover');
108478 },
108479 loadExternalText: function() {
108480 this._form.addClassName(this.options.loadingClassName);
108481 this._controls.editor.disabled = true;
108482 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
108483 Object.extend(options, {
108484 parameters: 'editorId=' + encodeURIComponent(this.element.id),
108485 onComplete: Prototype.emptyFunction,
108486 onSuccess: function(transport) {
108487 this._form.removeClassName(this.options.loadingClassName);
108488 var text = transport.responseText;
108489 if (this.options.stripLoadedTextTags)
108490 text = text.stripTags();
108491 this._controls.editor.value = text;
108492 this._controls.editor.disabled = false;
108493 this.postProcessEditField();
108494 }.bind(this),
108495 onFailure: this._boundFailureHandler
108496 });
108497 new Ajax.Request(this.options.loadTextURL, options);
108498 },
108499 postProcessEditField: function() {
108500 var fpc = this.options.fieldPostCreation;
108501 if (fpc)
108502 $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
108503 },
108504 prepareOptions: function() {
108505 this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
108506 Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
108507 [this._extraDefaultOptions].flatten().compact().each(function(defs) {
108508 Object.extend(this.options, defs);
108509 }.bind(this));
108510 },
108511 prepareSubmission: function() {
108512 this._saving = true;
108513 this.removeForm();
108514 this.leaveHover();
108515 this.showSaving();
108516 },
108517 registerListeners: function() {
108518 this._listeners = { };
108519 var listener;
108520 $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
108521 listener = this[pair.value].bind(this);
108522 this._listeners[pair.key] = listener;
108523 if (!this.options.externalControlOnly)
108524 this.element.observe(pair.key, listener);
108525 if (this.options.externalControl)
108526 this.options.externalControl.observe(pair.key, listener);
108527 }.bind(this));
108528 },
108529 removeForm: function() {
108530 if (!this._form) return;
108531 this._form.remove();
108532 this._form = null;
108533 this._controls = { };
108534 },
108535 showSaving: function() {
108536 this._oldInnerHTML = this.element.innerHTML;
108537 this.element.innerHTML = this.options.savingText;
108538 this.element.addClassName(this.options.savingClassName);
108539 this.element.style.backgroundColor = this._originalBackground;
108540 this.element.show();
108541 },
108542 triggerCallback: function(cbName, arg) {
108543 if ('function' == typeof this.options[cbName]) {
108544 this.options[cbName](this, arg);
108545 }
108546 },
108547 unregisterListeners: function() {
108548 $H(this._listeners).each(function(pair) {
108549 if (!this.options.externalControlOnly)
108550 this.element.stopObserving(pair.key, pair.value);
108551 if (this.options.externalControl)
108552 this.options.externalControl.stopObserving(pair.key, pair.value);
108553 }.bind(this));
108554 },
108555 wrapUp: function(transport) {
108556 this.leaveEditMode();
108557 // Can't use triggerCallback due to backward compatibility: requires
108558 // binding + direct element
108559 this._boundComplete(transport, this.element);
108560 }
108561 });
108562
108563 Object.extend(Ajax.InPlaceEditor.prototype, {
108564 dispose: Ajax.InPlaceEditor.prototype.destroy
108565 });
108566
108567 Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
108568 initialize: function($super, element, url, options) {
108569 this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
108570 $super(element, url, options);
108571 },
108572
108573 createEditField: function() {
108574 var list = document.createElement('select');
108575 list.name = this.options.paramName;
108576 list.size = 1;
108577 this._controls.editor = list;
108578 this._collection = this.options.collection || [];
108579 if (this.options.loadCollectionURL)
108580 this.loadCollection();
108581 else
108582 this.checkForExternalText();
108583 this._form.appendChild(this._controls.editor);
108584 },
108585
108586 loadCollection: function() {
108587 this._form.addClassName(this.options.loadingClassName);
108588 this.showLoadingText(this.options.loadingCollectionText);
108589 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
108590 Object.extend(options, {
108591 parameters: 'editorId=' + encodeURIComponent(this.element.id),
108592 onComplete: Prototype.emptyFunction,
108593 onSuccess: function(transport) {
108594 var js = transport.responseText.strip();
108595 if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
108596 throw 'Server returned an invalid collection representation.';
108597 this._collection = eval(js);
108598 this.checkForExternalText();
108599 }.bind(this),
108600 onFailure: this.onFailure
108601 });
108602 new Ajax.Request(this.options.loadCollectionURL, options);
108603 },
108604
108605 showLoadingText: function(text) {
108606 this._controls.editor.disabled = true;
108607 var tempOption = this._controls.editor.firstChild;
108608 if (!tempOption) {
108609 tempOption = document.createElement('option');
108610 tempOption.value = '';
108611 this._controls.editor.appendChild(tempOption);
108612 tempOption.selected = true;
108613 }
108614 tempOption.update((text || '').stripScripts().stripTags());
108615 },
108616
108617 checkForExternalText: function() {
108618 this._text = this.getText();
108619 if (this.options.loadTextURL)
108620 this.loadExternalText();
108621 else
108622 this.buildOptionList();
108623 },
108624
108625 loadExternalText: function() {
108626 this.showLoadingText(this.options.loadingText);
108627 var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
108628 Object.extend(options, {
108629 parameters: 'editorId=' + encodeURIComponent(this.element.id),
108630 onComplete: Prototype.emptyFunction,
108631 onSuccess: function(transport) {
108632 this._text = transport.responseText.strip();
108633 this.buildOptionList();
108634 }.bind(this),
108635 onFailure: this.onFailure
108636 });
108637 new Ajax.Request(this.options.loadTextURL, options);
108638 },
108639
108640 buildOptionList: function() {
108641 this._form.removeClassName(this.options.loadingClassName);
108642 this._collection = this._collection.map(function(entry) {
108643 return 2 === entry.length ? entry : [entry, entry].flatten();
108644 });
108645 var marker = ('value' in this.options) ? this.options.value : this._text;
108646 var textFound = this._collection.any(function(entry) {
108647 return entry[0] == marker;
108648 }.bind(this));
108649 this._controls.editor.update('');
108650 var option;
108651 this._collection.each(function(entry, index) {
108652 option = document.createElement('option');
108653 option.value = entry[0];
108654 option.selected = textFound ? entry[0] == marker : 0 == index;
108655 option.appendChild(document.createTextNode(entry[1]));
108656 this._controls.editor.appendChild(option);
108657 }.bind(this));
108658 this._controls.editor.disabled = false;
108659 Field.scrollFreeActivate(this._controls.editor);
108660 }
108661 });
108662
108663 //**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
108664 //**** This only exists for a while, in order to let ****
108665 //**** users adapt to the new API. Read up on the new ****
108666 //**** API and convert your code to it ASAP! ****
108667
108668 Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
108669 if (!options) return;
108670 function fallback(name, expr) {
108671 if (name in options || expr === undefined) return;
108672 options[name] = expr;
108673 };
108674 fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
108675 options.cancelLink == options.cancelButton == false ? false : undefined)));
108676 fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
108677 options.okLink == options.okButton == false ? false : undefined)));
108678 fallback('highlightColor', options.highlightcolor);
108679 fallback('highlightEndColor', options.highlightendcolor);
108680 };
108681
108682 Object.extend(Ajax.InPlaceEditor, {
108683 DefaultOptions: {
108684 ajaxOptions: { },
108685 autoRows: 3, // Use when multi-line w/ rows == 1
108686 cancelControl: 'link', // 'link'|'button'|false
108687 cancelText: 'cancel',
108688 clickToEditText: 'Click to edit',
108689 externalControl: null, // id|elt
108690 externalControlOnly: false,
108691 fieldPostCreation: 'activate', // 'activate'|'focus'|false
108692 formClassName: 'inplaceeditor-form',
108693 formId: null, // id|elt
108694 highlightColor: '#ffff99',
108695 highlightEndColor: '#ffffff',
108696 hoverClassName: '',
108697 htmlResponse: true,
108698 loadingClassName: 'inplaceeditor-loading',
108699 loadingText: 'Loading...',
108700 okControl: 'button', // 'link'|'button'|false
108701 okText: 'ok',
108702 paramName: 'value',
108703 rows: 1, // If 1 and multi-line, uses autoRows
108704 savingClassName: 'inplaceeditor-saving',
108705 savingText: 'Saving...',
108706 size: 0,
108707 stripLoadedTextTags: false,
108708 submitOnBlur: false,
108709 textAfterControls: '',
108710 textBeforeControls: '',
108711 textBetweenControls: ''
108712 },
108713 DefaultCallbacks: {
108714 callback: function(form) {
108715 return Form.serialize(form);
108716 },
108717 onComplete: function(transport, element) {
108718 // For backward compatibility, this one is bound to the IPE, and passes
108719 // the element directly. It was too often customized, so we don't break it.
108720 new Effect.Highlight(element, {
108721 startcolor: this.options.highlightColor, keepBackgroundImage: true });
108722 },
108723 onEnterEditMode: null,
108724 onEnterHover: function(ipe) {
108725 ipe.element.style.backgroundColor = ipe.options.highlightColor;
108726 if (ipe._effect)
108727 ipe._effect.cancel();
108728 },
108729 onFailure: function(transport, ipe) {
108730 alert('Error communication with the server: ' + transport.responseText.stripTags());
108731 },
108732 onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
108733 onLeaveEditMode: null,
108734 onLeaveHover: function(ipe) {
108735 ipe._effect = new Effect.Highlight(ipe.element, {
108736 startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
108737 restorecolor: ipe._originalBackground, keepBackgroundImage: true
108738 });
108739 }
108740 },
108741 Listeners: {
108742 click: 'enterEditMode',
108743 keydown: 'checkForEscapeOrReturn',
108744 mouseover: 'enterHover',
108745 mouseout: 'leaveHover'
108746 }
108747 });
108748
108749 Ajax.InPlaceCollectionEditor.DefaultOptions = {
108750 loadingCollectionText: 'Loading options...'
108751 };
108752
108753 // Delayed observer, like Form.Element.Observer,
108754 // but waits for delay after last key input
108755 // Ideal for live-search fields
108756
108757 Form.Element.DelayedObserver = Class.create({
108758 initialize: function(element, delay, callback) {
108759 this.delay = delay || 0.5;
108760 this.element = $(element);
108761 this.callback = callback;
108762 this.timer = null;
108763 this.lastValue = $F(this.element);
108764 Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
108765 },
108766 delayedListener: function(event) {
108767 if(this.lastValue == $F(this.element)) return;
108768 if(this.timer) clearTimeout(this.timer);
108769 this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
108770 this.lastValue = $F(this.element);
108771 },
108772 onTimerEvent: function() {
108773 this.timer = null;
108774 this.callback(this.element, $F(this.element));
108775 }
108776 });