CmdUtils.CreateCommand({
	name: "beo",
	homepage: "http://halcy.de/",
	author: { 
		name: "Lorenz Diener",
		email: "lorenzd@gmail.com"
	},
	contributors: ["Jonas Skovmand"],
	license: "MPL",
	description: "Does German<>English dictionary lookups.",
	help: "Replaces the currently selected word with its german or english counterpart, respectively, by doing a lookup in the BEOLINGUS German<>English dictionary (http://dict.tu-chemnitz.de/)",
	icon: "http://dict.tu-chemnitz.de/favicon.ico",
	takes: {
		"word to look up": noun_arb_text
	},
	preview: "Replace the selected word with it's translation from the BEOLINGUS dictionary.",
	execute: function( word ) {
		var params = {
			type: "GET",
			url: "http://dict.tu-chemnitz.de/dings.cgi",
			data: {
				lang: "de",
				mini: "1",
				count: "10",
				service: "deen",
				query: word.text
			},
			dataType: "html",
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				displayMessage( textStatus );
			},
			success: function( translation ) {

				var tempElement = context.focusedWindow.document.createElement( "html" );
				tempElement.innerHTML = translation;

				var words = jQuery( tempElement );
				var words2 = words.find( ".s1" );
				
				if( words2.length == 0 ) {
					displayMessage( "No translation found." );
					return;
				}

				var german = words2.eq( 0 ).contents().next().eq( 0 );
				var english = words2.eq( 0 ).children( ":last" );
				var eng_to_ger = 0;
				var translated;

				if( english.find( "b" ).length != 0 ) {
					translated = german;
					 eng_to_ger = 1;
				}
				else {
					translated = english;
					eng_to_ger = 0;
				}
				words2.each( function (i) {
					german = jQuery(this).contents().next().eq( 0 );
					english = jQuery(this).children( ":last" );

					var tmp_translated;
					var tmp_test;

					if( eng_to_ger == 1 ) {
						tmp_translated = german;
						tmp_test = english;
					}
					else {
						tmp_translated = english;
						tmp_test = german;
					}

					if(
						jQuery.trim(tmp_test.text()).length == 
						jQuery.trim(word.text).length
					) {
						translated = tmp_translated;
						return( false );
					}
				} );
				var el = context.focusedWindow.document.createElement( "html" );
				var thtml = translated.html();
				thtml = thtml.replace( /<a href="\/[^/]*\/([^.]*).html[^<]*<\/a>/g, '$1' );
				thtml = thtml.replace( /%e4/gi, '&auml;' );
				thtml = thtml.replace( /%f6/gi, '&ouml;' );
				thtml = thtml.replace( /%fc/gi, '&uuml;' );
				thtml = thtml.replace( /%c4/gi, '&Auml;' );
				thtml = thtml.replace( /%d6/gi, '&Ouml;' );
				thtml = thtml.replace( /%dc/gi, '&Uuml;' );
				thtml = thtml.replace( /%df/gi, '&szlig;' );
				el.innerHTML = "<div>" + thtml + "</div>";
				var plainText = el.textContent;
				plainText = jQuery.trim( plainText );
				CmdUtils.setSelection( plainText );
			}
		};
		
		jQuery.ajax( params );
	}
});
