/*
 * This file is part of the MyBB Inline Google Translation plugin.
 *
 * Copyright (c) 2008 The forum.kde.org team <kde-forum@nerdstock.org>
 *
 * More info: http://forum.kde.org
 */

/*
 * TODO
 *
 * - preselect user's prefered language
 * - replace innerHTML with DOM compliant methods
 * - interactively check Google's text length limit
 * - add some debug messages
 * - have Google translate
 *   - alt texts for buttons
 *   - name of language
 *   - error and debug messageѕ
 */

// MyBB should be using ISO639-2 codes, like everyone else.
// Until it does, we'll translate MyBB language names to ISO639-2 here.
var mybb2iso639 = new Array();
mybb2iso639['arabic']		= 'ar';
mybb2iso639['azeri']		= 'az';
mybb2iso639['deutsch_du']	= 'de';
mybb2iso639['deutsch_sie']	= 'de';
mybb2iso639['english']		= 'en';
mybb2iso639['espanol']		= 'es';
mybb2iso639['french']		= 'fr';
mybb2iso639['hungarian']	= 'hu';
mybb2iso639['dutch']		= 'nl';
mybb2iso639['persian']		= 'fa';
mybb2iso639['polish']		= 'pl';
mybb2iso639['russian']		= 'ru';
mybb2iso639['serbian']		= 'hr';
mybb2iso639['turkish']		= 'tr';

google.load("language", "1");

// The languages used for error and debug messages.
var googleTranslationPluginLanguage = 'en';

// Set to true to have Google translate error and debug messages.
var googleTranslateMessages = false;

// Don't bother users not using JavaScript with something
// they can't use anyway; add buttons dynamically.
function googleTranslationInit() {
	// No need to set all this up if Google can't translate it anyway.
	if (! google.language.isTranslatable(plugins['googletranslation']['boardlanguage'])) {
		googleDebug("The language you\'ve set as the default ('" + plugins['googletranslation']['boardlanguage'] + "') cannot be translated by Google.\n\nGo to the AdminCP to set a different language.");
		return false;
	}

	// The maximum length of the post (Google enforces a 5000 char limit).
	//////FIXME
	// This limit should be checked with Google when this script loads,
	// so I don't have to manually change this when Google increases it.
	var googleMaxLength = 5000;

	// Get all divs with post ids.
	var allDivs = document.getElementsByTagName('div');
	var myDivs = new Array();
	var pidreg = /^pid_\d+$/;
	for (var i = 0; i < allDivs.length; i++) {
		if (allDivs[i].id.match(pidreg)) {
			myDivs[myDivs.length] = allDivs[i];
		}
	}

	// Add the tools to the posts.
	for (var i = 0; i < myDivs.length; i++) {
		// The post id.
		var myIdBase = myDivs[i].id;

		// The post's parent node.
		var myParent = myDivs[i].parentNode;

		// Check length of post.
		var tooLong = (myDivs[i].innerHTML.length > googleMaxLength ? true : false);

		// Put it all in 1 div.
		var myGoogleDiv = document.createElement('div');
		myGoogleDiv.id = myIdBase + '_googlediv';
		myGoogleDiv.className = 'googlediv';

		if (! tooLong) {
			// The original text.
			var myOrigDiv = document.createElement('div');
			myOrigDiv.id = myIdBase + '_googleorig';
			myOrigDiv.innerHTML = myDivs[i].innerHTML;
			myOrigDiv.style.display = 'none';	// This should NOT be in a stylesheet.
			myGoogleDiv.appendChild(myOrigDiv);
		}

		// The div with the 'Translate' button.
		var myTransBtnDiv = document.createElement('div');
		myTransBtnDiv.id = myIdBase + '_googletransbtn';
		myTransBtnDiv.className = 'googletransbtn';

		if (tooLong) {
			myTransBtnDiv.innerHTML = "This post is too long to be translated.<br />Google enforces a " + googleMaxLength + "&nbsp;character limit (including HTML).<br />Please <a href=\"http://code.google.com/p/google-ajax-apis/issues/detail?id=18\" target=\"_blank\">vote here</a> to have this limit increased.";
		}
		else {
			// The dropdown.
			var myTransBtnSelect = document.createElement('select');
			myTransBtnSelect.id = myIdBase + '_googlelang';
			myTransBtnSelect.className = 'googlelang';
			googleFillDropdown(myTransBtnSelect, false, true);
			myTransBtnDiv.appendChild(myTransBtnSelect);

			// The button.
			var myTransBtnImg = document.createElement('img');
			myTransBtnImg.id = myIdBase + '_googletransbtnimg';
			myTransBtnImg.className = 'googletransbtnimg';
			myTransBtnImg.src = '/images/' + plugins['googletranslation']['imagelanguage'] + '/googletranslation.png';
			myTransBtnImg.alt = 'Google translation';
			myTransBtnImg.title = '';
			if (myTransBtnImg.addEventListener) {
				myTransBtnImg.addEventListener('click', googleTranslate, false);
			}
			else {
				myTransBtnImg.attachEvent('onclick', googleTranslate);
			}
			myTransBtnDiv.appendChild(myTransBtnImg);
		}

		// Append to the Google div.
		myGoogleDiv.appendChild(myTransBtnDiv);

		if (! tooLong) {
			// The div with the 'Original' button.
			var myOrigBtnDiv = document.createElement('div');
			myOrigBtnDiv.id = myIdBase + '_googleorigbtn';
			myOrigBtnDiv.className = 'googleorigbtn';
			myOrigBtnDiv.style.display = 'none';	// This should NOT be in a stylesheet.

			// The name of the language (or Google's error message)
			var myOrigBtnSpan = document.createElement('span');
			myOrigBtnSpan.id = myIdBase + '_googlelangname';
			myOrigBtnSpan.className = 'googlelangname';
			myOrigBtnDiv.appendChild(myOrigBtnSpan);

			// The 'Original button.
			var myOrigBtnImg = document.createElement('img');
			myOrigBtnImg.id = myIdBase + '_googleorigbtnimg';
			myOrigBtnImg.className = 'googleorigbtnimg';
			myOrigBtnImg.src = '/images/' + plugins['googletranslation']['imagelanguage'] + '/googleoriginal.png';
			myOrigBtnImg.alt = 'Original language';
			myOrigBtnImg.title = '';
			if (myOrigBtnImg.addEventListener) {
				myOrigBtnImg.addEventListener('click', googleOriginal, false);
			}
			else {
				myOrigBtnImg.attachEvent('onclick', googleOriginal);
			}
			myOrigBtnDiv.appendChild(myOrigBtnImg);

			// Append to the Google div.
			myGoogleDiv.appendChild(myOrigBtnDiv);
		}

		// Prepend the whole thing to the post.
		myParent.insertBefore(myGoogleDiv, myParent.firstChild);

		if (tooLong && googleTranslateMessages) {
			var myGoogleDivId = myIdBase + '_googletransbtn';
			if (mybb2iso639[plugins['googletranslation']['userlanguage']] != googleTranslationPluginLanguage) {
				google.language.translate(document.getElementById(myGoogleDivId).innerHTML, googleTranslationPluginLanguage, mybb2iso639[plugins['googletranslation']['userlanguage']], function(result) {
					if (result.translation) {
						document.getElementById(myGoogleDivId).innerHTML = result.translation;
					}
					else if (plugins['googletranslation']['boardlanguage'] != googleTranslationPluginLanguage) {
						google.language.translate(document.getElementById(myGoogleDivId).innerHTML, googleTranslationPluginLanguage, plugins['googletranslation']['boardlanguage'], function(result) {
							if (result.translation) {
								document.getElementById(myGoogleDivId).innerHTML = result.translation;
							}
						});
					}
				});
			}
		}

	}
}

function googleTranslationAdminInit() {
	var myDropdown = document.getElementById('setting_googletranslationboardlanguage');
	if (myDropdown) {
		myDropdown.options.length = 0;
		googleFillDropdown(myDropdown, plugins['googletranslation']['boardlanguage']);
	}
}

function googleFillDropdown(thisDropdown, selectedLanguage, skipBoardLanguage) {
	for (var x in google.language.Languages) {
		if (x != 'UNKNOWN' && ((skipBoardLanguage && google.language.Languages[x] != plugins['googletranslation']['boardlanguage']) || ! skipBoardLanguage) && google.language.isTranslatable(google.language.Languages[x])) {
			var text = x.charAt(0) + x.substr(1).toLowerCase();
			var tmp = text.split('_');
			text = (tmp.length > 1 ? tmp[0] + ' (' + tmp[1] + ')' : tmp[0]);
			thisDropdown.options[thisDropdown.length] = new Option(text, google.language.Languages[x], (google.language.Languages[x] == selectedLanguage ? true : false), (google.language.Languages[x] == selectedLanguage ? true : false));
		}
	}
}

function googleTranslate(e) {
	e = (e ? e : window.event);
	var thisTarget = (e.target ? e.target : e.srcElement);
	if (thisTarget.nodeType == 3) {
		thisTarget = thisTarget.parentNode;
	}
	var myIdBase = thisTarget.id.replace('_googletransbtnimg', '');
	var langBox = document.getElementById(myIdBase + '_googlelang');
	google.language.translate(document.getElementById(myIdBase + '_googleorig').innerHTML, plugins['googletranslation']['boardlanguage'], langBox.options[langBox.selectedIndex].value.toString(), function(result) {
		if (result.status.code != 200) {
			document.getElementById(myIdBase + '_googlelangname').innerHTML = 'Google could not translate this post. (Google response: <em>' + result.status.message + '</em>)';
		}
		else if (result.translation) {
			document.getElementById(myIdBase).innerHTML = result.translation;
			var myBranding = document.createElement('div');
			myBranding.id = 'googleBranding';
			document.getElementById(myIdBase).appendChild(myBranding);
			google.language.getBranding('googleBranding', {type:'vertical'});
			document.getElementById(myIdBase + '_googlelangname').innerHTML = '(' + langBox.options[langBox.selectedIndex].text + ')';
		}
		document.getElementById(myIdBase + '_googletransbtn').style.display = 'none';
		document.getElementById(myIdBase + '_googleorigbtn').style.display = 'block';
	});
}

function googleOriginal(e) {
	e = (e ? e : window.event);
	var thisTarget = (e.target ? e.target : e.srcElement);
	if (thisTarget.nodeType == 3) {
		thisPost = thisPost.parentNode;
	}
	var myIdBase = thisTarget.id.replace('_googleorigbtnimg', '');
	document.getElementById(myIdBase).innerHTML = document.getElementById(myIdBase + '_googleorig').innerHTML;
	document.getElementById(myIdBase + '_googleorigbtn').style.display = 'none';
	document.getElementById(myIdBase + '_googletransbtn').style.display = 'block';
}

function googleDebug(message) {
	if (plugins['googletranslation']['debug']) {
		if (mybb2iso639[plugins['googletranslation']['userlanguage']] != googleTranslationPluginLanguage && googleTranslateMessages) {
			google.language.translate(message, googleTranslationPluginLanguage, mybb2iso639[plugins['googletranslation']['userlanguage']], function(result) {
				if (result.translation) {
					alert(result.translation);
				}
				else if (plugins['googletranslation']['boardlanguage'] != googleTranslationPluginLanguage) {
					google.language.translate(message, googleTranslationPluginLanguage, plugins['googletranslation']['boardlanguage'], function(result) {
						if (result.translation) {
							alert(result.translation);
						}
						else {
							alert(message);
						}
					});
				}
				else {
					alert(message);
				}
			});
		}
		else {
			alert(message);
		}
	}
}

function googleDisabled() {
	googleDebug('The InlineGoogleTranslation plugin is currently disabled.\n\nGo to the AdminCP to enable the plugin or disable debugging.');
}

if (typeof(plugins['googletranslation']) == 'object') {
	if (plugins['googletranslation']['inadmincp']) {
		google.setOnLoadCallback(googleTranslationAdminInit);
	}
	else if (plugins['googletranslation']['enable']) {
		google.setOnLoadCallback(googleTranslationInit);
	}
	else {
		google.setOnLoadCallback(googleDisabled);
	}
}
else {
	alert('The InlineGoogleTranslation plugin has not been (un)installed correctly.\n\nSee readme.txt for instructions.');
}

/*
 * Hey Google people!
 * You see that? Readable code!
 * Cool, isn't it?
 * You should try that some time...
 */

