/*
 * jquery.translationbox.js
 * rev: 2009-09-15 jej
 * 
 * a jQuery plugin to create translation widgets. This plugin was
 * created for a url-proxifying service, where users enter an un-proxied
 * url and then get to see what the proxied url should look like. It
 * could also be used to build things like currency converters or german
 * to english dictionaries.
 * 
 * This plugin uses JSONP to work around the browser's same-origin
 * policy. JSONP doessn't allow javascript access to the server's
 * response codes for error handling so I use a timeout to determine if
 * a service is down or not. 
 * 
 * TO-DO:
 * Is it possible to respond intelligently to server response codes, 
 * when we have access to them? (So if it is able to use XMLHttpRequest,
 * it does. If not, it can use JSONP without the request codes.)
 */

(function($) {
	$.fn.translationbox = function(options) {
		var options = $.extend({
			errormessage: "service temporarily unavailable.",
			html: "<form><input class='proxifyinterfacefrom' type='text'/><input class='proxifyinterfaceto' type='text'/></form>",
			requestdelay: 100,
			selectfrom: ".proxifyinterfacefrom",
			selectto: ".proxifyinterfaceto",
			timeout: 2000,
			url: "",
			urldataparam: "",
			urlotherparams: ""
		}, options);

		return this.each(function() {
			$(this).html(options['html']);

			var from = $(this).find(options['selectfrom']).eq(0);
			var to = $(this).find(options['selectto']).eq(0);

			from.change(update);
			from.keyup(update);

			function possiblyupdate() {
				from.stopTime('proxifyupdate');
				from.oneTime(options['requestdelay'], 'proxifyupdate', update);
			}

			function update() {
				$.ajax({
					data: options['urldataparam'] + '=' + escape(from.val()) + '&' + options['urlotherparams'] + '&jsoncallback=?',
					dataType: 'jsonp',
					error: function() {
						to.html(options['errormessage']);
					},
					success: function(data) {
						to.html(data.raw);
					},
					timeout: options['timeout'],
					type: "GET",
					url: options['url']
				});
			}
		});
	};
})(jQuery);

