// ==UserScript==
// @name Google-Translate
// @author Lex1
// @version 1.7.1
// @description Google translate. Use button with a similar code: "javascript:ujs_google_translate('auto|ru')"
// @ujs:documentation http://ruzanow.ru/index/0-5
// @ujs:download http://ruzanow.ru/userjs/google-translate.js
// ==/UserScript==

if(window.opera)opera.addEventListener('BeforeExternalScript', function(e){
	var s = e.element.src, h = location.href;
	if(s && s.indexOf('http://translate.google.com/translate_static/') == 0 && h.indexOf('&ujs=gtt') == h.length-8){
		e.preventDefault();
		opera.addEventListener('BeforeScript', function(ev){ev.preventDefault()}, false);
		opera.addEventListener('BeforeEventListener.load', function(ev){ev.preventDefault()}, false);
		var c = document.createElement('style');
		c.setAttribute('type', 'text/css');
		c.appendChild(document.createTextNode('img,object,embed{display:none !important}'));
		document.getElementsByTagName('head')[0].appendChild(c);
	}
}, false);

window.addEventListener('load', function(){
	if(location.href.indexOf('http://translate.google.com/translate_n?') == 0 && window.parent != window)parent.document.body.rows = '0,*';
}, false);

document.addEventListener('mouseup', function(e){
	if(e && e.button == 0){
		var lc = navigator.lastClick || (navigator.lastClick = {});
		lc.X = e.clientX;
		lc.Y = e.clientY;
		lc.element = e.target;
	}
}, false);

document.addEventListener('focus', function(e){
	if(e){
		var target = e.target;
		var tag = target.nodeName.toLowerCase();
		if(tag == 'textarea' || (tag == 'input' && target.type == 'text')){
			(navigator.lastClick || (navigator.lastClick = {})).textArea = target;
		}
	}
}, true);


function ujs_createWindow(strContent, strStatus, strTitle, strId, pos, size){
	var wId = 'ujs_window';
	if(strId)wId += strId;
	var win = document.getElementById(wId);
	if(win)win.parentNode.removeChild(win);
	win = document.createElement('div');
	win.setAttribute('style', 'position:fixed;display:block;visibility:hidden;left:0;top:0;width:auto;height:auto;border:1px solid gray;padding:3px;margin:0;z-index:9999;overflow:visible;cursor:move;'+(typeof win.style.borderRadius === 'string' ? 'background-color:#f3f5f7;padding-top:4px;border-radius:4px;box-shadow:0 0 12px rgba(0,0,0,.4);' : 'background:-o-skin("Window Skin");'));
	win.id = wId;
	var img = document.createElement('img');
	img.setAttribute('style', 'display:block;float:right;background:-o-skin("Caption Close Button Skin");width:18px;height:18px;padding:0;margin:0;border:none;cursor:pointer;');
	img.src = 'data:image/gif;base64,R0lGODlhAQABAIABAAAAAP///yH5BAEAAAEALAAAAAABAAEAAAICTAEAOw==';
	img.title = (navigator.language == 'ru') ? '\u0417\u0430\u043A\u0440\u044B\u0442\u044C' : 'Close';
	img.onclick = function(){this.parentNode.parentNode.removeChild(this.parentNode)};
	win.appendChild(img);
	var title = document.createElement('span');
	title.setAttribute('style', 'display:inline;color:#000000;font:16px Times New Roman;width:auto;height:auto;padding:1px 2px;margin:0;');
	title.innerHTML = strTitle || '';
	win.appendChild(title);
	var content = document.createElement('div');
	content.setAttribute('style', 'display:block;border:1px solid #aaaaaa;margin:2px 0 0 0;padding:4px;background-color:#fafcfe;color:#000000;font:14px Times New Roman;width:240px;height:120px;overflow:auto;cursor:text;');
	content.innerHTML = strContent || '';
	win.appendChild(content);
	var status = document.createElement('div');
	status.setAttribute('style', 'display:block;color:#555555;font:10px Times New Roman;width:auto;height:auto;padding:0;margin:1px 2px;cursor:text;');
	status.innerHTML = strStatus || '';
	win.appendChild(status);
	win.addEventListener('mousedown', function(e){
		if(e.target == win){
			e.preventDefault();
			var grabX = e.clientX;
			var grabY = e.clientY;
			var origX = parseInt(win.style.left);
			var origY = parseInt(win.style.top);
			var dnd = function(e){
				win.style.left = origX+e.clientX-grabX+'px';
				win.style.top = origY+e.clientY-grabY+'px';
			};
			document.addEventListener('mousemove', dnd, false);
			document.addEventListener('mouseup', function(){document.removeEventListener('mousemove', dnd, false)}, false);
		}
	}, false);
	document.documentElement.appendChild(win);

	if(size){
		content.style.height = size.height;
		content.style.width = size.width;
	}
	else{
		for(var i = 3; i < 10; i++){
			if(content.scrollHeight > content.offsetHeight || content.scrollWidth > content.offsetWidth){
				content.style.height = 50*i+'px';
				content.style.width = 100*i+'px';
			}
			else break;
		}
	};
	var docEle = (document.compatMode == 'CSS1Compat' && window.postMessage) ? document.documentElement : document.body;
	var mX = docEle.clientWidth-win.offsetWidth;
	var mY = docEle.clientHeight-win.offsetHeight;
	if(mX < 0){content.style.width = parseInt(content.style.width)+mX+'px'; mX = 0};
	if(mY < 0){content.style.height = parseInt(content.style.height)+mY+'px'; mY =0};
	var hW = parseInt(win.offsetWidth/2);
	win.style.left = (pos && pos.X < mX+hW ? (pos.X > hW ? pos.X-hW : 0) : mX)+'px';
	win.style.top = (pos && pos.Y+10 < mY ? pos.Y+10 : mY)+'px';
	win.style.visibility = 'visible';
	document.addEventListener('keypress', function(e){
		if(e.keyCode == 27){this.removeEventListener(e.type, arguments.callee, false); var t = document.getElementById(wId); if(t)t.parentNode.removeChild(t)};
	}, false);
	return win;
};

window.addEventListener('message', function(e){
	if(e.data == 'google-translate'){
		var result = '', status = '';
		if(location.hostname == 'translate.google.com'){
			var r = document.getElementById('result_box');
			var d = document.getElementById('dict');
			var s = document.getElementById('source');
			var h = document.getElementById('headingtext');
			if(r){
				var p = r.getElementsByTagName('span');
				for(var i = 0, n; n = p[i]; i++){
					n.removeAttribute('onmouseover');
					n.removeAttribute('onmouseout');
					n.setAttribute('style', 'background-color:inherit;color:inherit;font-size:inherit;');
				};
				result = r.innerHTML;
			};
			if(s && d && d.innerText){
				var a = d.getElementsByTagName('*');
				for(var i = 0, n; n = a[i]; i++){
					switch(n.nodeName.toLowerCase()){
						case 'td': n.setAttribute('style', 'padding:5px 15px;margin:0;vertical-align:top;font:12px Arial;'); break;
						case 'li':
						case 'ol': n.setAttribute('style', 'padding:0;margin:0;list-style-position:inside;font:12px Arial;'); break;
						case 'a':
						case 'p': n.parentNode.removeChild(n); break;
					}
				};
				result = '<b><q>'+s.value+'</q></b>'+d.innerHTML;
			};
			if(h && h.innerText)status = h.innerText.replace(/^.*: /, '').toLowerCase();
		};
		if(location.hostname == 'm.translate.ru'){
			var v = document.getElementsByTagName('div');
			for(var i = 0, n; n = v[i]; i++){
				if(n.className == 'tblue')status = n.nextSibling.nodeValue.slice(0, -1)+' (PROMT)';
				if(n.className == 'tres')result = n.innerHTML;
			}
		};
		if(result || status)e.source.postMessage('google_translate'+encodeURI(result)+'|'+encodeURI(status)+'|'+encodeURI(location.href), '*');
	};
	if(e.data && e.data.indexOf('google_translate') == 0){
		var origin = e.origin || 'http://'+e.domain;
		if(origin == 'http://translate.google.com' || origin == 'http://m.translate.ru'){
			var msg = e.data.slice(16).split('|');
			ujs_createWindow(decodeURI(msg[0]), decodeURI(msg[1]), '<a href="'+decodeURI(msg[2])+'" target="_blank" style="display:inline;padding:0;margin:0;text-decoration:none;border:none;color:#000099;font:16px Times New Roman;">Google Translate</a>', '_gt', navigator.lastClick);
			var f = document.getElementById('ujs_googletranslateframe');
			if(f)f.parentNode.removeChild(f);
		}
	}
}, false);

function ujs_google_translate(dir){
	var selText = function(w){var t; return w ? w.document.getSelection() || (t = w.navigator.lastClick && w.navigator.lastClick.textArea) && t.value.substring(t.selectionStart, t.selectionEnd) : ''};
	var selWin = function(w){if(selText(w))return w; for(var i = 0, f, r; f = w.frames[i]; i++){try{if(r = arguments.callee(f))return r}catch(e){}}};
	var winWait = function(w, lng){w.ujs_createWindow('', (lng == 'ru' ? '\u041F\u0435\u0440\u0435\u0432\u043E\u0434\u0438\u043C' : 'Translating')+'\u2026', 'Google Translate', '_gt', w.navigator.lastClick)};
	var createFrame = function(w, src){
		var fId = 'ujs_googletranslateframe';
		var f = w.document.getElementById(fId);
		if(f)f.parentNode.removeChild(f);
		f = w.document.createElement('iframe');
		f.width = 0;
		f.height = 0;
		f.frameBorder = 'no';
		f.scrolling = 'no';
		f.id = fId;
		f.name = fId;
		f.onload = function(){(window.postMessage ? f.contentWindow : f.contentDocument).postMessage('google-translate', '*')};
		w.document.documentElement.appendChild(f);
		if(src)f.src = src;
	};
	var createForm = function(w, action, name, value){
		var f = w.document.createElement('form');
		f.action = action;
		f.method = 'POST';
		f.acceptCharset = 'UTF-8';
		f.target = 'ujs_googletranslateframe';
		f.style.display = 'none';
		var t = w.document.createElement('textarea');
		t.name = name;
		t.value = value;
		f.appendChild(t);
		w.document.documentElement.appendChild(f);
		f.submit();
		f.parentNode.removeChild(f);
	};

	var w = selWin(window.top);
	var txt = selText(w);
	var encTxt = encodeURIComponent(txt);
	var lng = navigator.language;
	var url = escape(location.href);
	if(dir.indexOf('|') != -1){
		if(w && w.location.hostname != 'translate.google.com'){
			winWait(w, lng);
			if(encTxt.length < 1900){
				createFrame(w, 'http://translate.google.com/translate_t?text='+encTxt+'&hl='+lng+'&langpair='+dir+'&eotf=0&tbb=1&ujs=gtt');
			}
			else{
				var l = dir.split('|');
				createFrame(w, '');
				createForm(w, 'http://translate.google.com/?sl='+l[0]+'&tl='+l[1]+'&hl='+lng+'&eotf=0&ujs=gtt', 'text', txt);
			}
		}
		else{
			window.open('http://translate.google.com/translate?u='+url+'&hl='+lng+'&langpair='+dir+'&tbb=1'+(document.charset ? '&ie='+document.charset : ''));
		}
	}
	else{
		if(w && w.location.hostname != 'm.translate.ru'){
			winWait(w, lng);
			createFrame(w, 'http://m.translate.ru/translator/result/?text='+encodeURIComponent(txt.slice(0, 600))+'&dirCode='+dir);
		}
		else{
			window.open('http://www.translate.ru/url/tran_url.asp?direction='+dir+'&template=General&autotranslate=true&url='+url);
		}
	}
};
