// Copyright (c) 2005 Dirk Steins (http://www.dirksteins.de)
//
// This is an extension for a live preview for textpattern
// based on scriptaculous (http://script.aculo.us, http://mir.aculo.us)
// and prototype.js (http://prototype.conio.net/)


Element.LiveUpdateObserver = Class.create();
Element.LiveUpdateObserver.prototype = Object.extend(Element, {
		initialize: function(source, container, url, param, options) {
				this.containers = {
					success: container.success ? $(container.success) : $(container),
					failure: container.failure ? $(container.failure) :
						(container.success ? null : $(container)),
					source: $(source)
				}
				this.setOptions(options);

				var onLiveUpdate = this.options.onLiveUpdate || Prototype.emptyFunction;
				this.options.onLiveUpdate = (function(object, value) {
						if (value == null || value.length == 0)
						{
								Element.hide(this.containers.success);
								return;
						}
						Element.show(this.containers.success);
						// this.options.parameters = this.param + escape(value);
						this.options.parameters = this.param + encodeURIComponent(value);
						var myAjax = new Ajax.Updater(this.containers, this.queryUrl, this.options);
				}).bind(this);

				this.queryUrl = url;
				this.param = param;
				if (this.containers.success)
				{
					Element.hide(this.containers.success);
				}
				if (this.containers.source)
				{
					this.observer = new Form.Element.Observer(this.containers.source, 0.5, this.options.onLiveUpdate);
				}
		},
		setOptions: function(options) {
			this.options = {
				method:       'post',
				asynchronous: true,
				parameters:   ''
			}
			Object.extend(this.options, options || {});
		}
});

