var Cookie = {
	set: function( name, value, nDays )
	{
		var today = new Date();
		var expire = new Date();
		if ( ! nDays )
			nDays = 7;
		expire.setTime( today.getTime() + nDays * 24 * 3600 * 1000 );
		document.cookie = name + "=" + escape(value) + ";expires=" + expire.toGMTString() + ";";
	}
};

function getOptions()
{
	var optionsFlags = [];
	optionsFlags.push({id: "ijekek", flag: "e"});
	optionsFlags.push({id: "ekijek", flag: "i"});
	optionsFlags.push({id: "repairIjek", flag: "r"});
	optionsFlags.push({id: "crosr", flag: "s"});
	optionsFlags.push({id: "srcro", flag: "h"});
	optionsFlags.push({id: "latinize", flag: "l"});
	optionsFlags.push({id: "asciiize", flag: "O"});
	optionsFlags.push({id: "cyrillize", flag: "c"});
	optionsFlags.push({id: "transcr", flag: "t"});
	optionsFlags.push({id: "detranscr", flag: "d"});
	optionsFlags.push({id: "futur", flag: "f"});
	optionsFlags.push({id: "bold", flag: "b"});
	optionsFlags.push({id: "convert", flag: "u"});
	optionsFlags.push({id: "ambig", flag: "a"});
	optionsFlags.push({id: "wiki", flag: "w"});
	optionsFlags.push({id: "subt", flag: "p"});
	optionsFlags.push({id: "osisana", flag: "o"});

	var options = "", i;
	for (i = 0; i < optionsFlags.length; i++)
		if (document.getElementById(optionsFlags[i].id) && document.getElementById(optionsFlags[i].id).checked)
			options += optionsFlags[i].flag;

	if (options == "") {
		alert("Није изабрана ниједна опција превођења. Молимо изаберите врсту/врсте превођења.");
		return null;
	}
	return options;
}

function loopCancelButton(ajax)
{
	gearsStart = new Date().getTime();
	document.body.style.backgroundImage = "url(/images/gears-bg.gif)";
	var translateButton = document.getElementById("translateButton");
	translateButton.value = "Откажи";
	translateButton.onclick = function()
	{
		ajax.abort();
		setTimeout("document.body.style.backgroundImage = 'url(/images/gears-bg-still.gif)';", 800-(new Date().getTime() - gearsStart)%800);
		translateButton.onclick = translateText;
		translateButton.value = "Преведи";
	};
}

function translateUrl()
{
	var options = getOptions();
	if (options === null)
		return false;
	var url = document.getElementById("url").value;
	if (url == "" || url.length < 4) {
		alert("Унесите адресу жељене странице.");
		return false;
	}
	document.getElementById("t").value = options;
	return true;
}

function translateText()
{
	var options = getOptions();
	if (options === null)
		return;
	var text = document.getElementById("original").value;
	if (text.length == 0)
		return;
	var ajax = AJAX.getAJAXHandler();
	ajax.open("POST", "t.cgi?t=" + options, true);
	ajax.onreadystatechange = function()
	{
		receiveText(ajax);
	}
	ajax.send(text);
	loopCancelButton(ajax);
}

function fnSelect(objId)
{
	if (document.selection) {
		var range = document.body.createTextRange();
		range.moveToElementText(document.getElementById(objId));
		range.select();
	} else if (window.getSelection) {
		var range = document.createRange();
		range.selectNode(document.getElementById(objId));
		window.getSelection().addRange(range);
	}
}

function receiveText(ajax)
{
	if (ajax.readyState == 4) {
		var container = document.getElementById("translation");
		setTimeout("document.body.style.backgroundImage = 'url(/images/gears-bg-still.gif)';", 800-(new Date().getTime() - gearsStart)%800);
		container.innerHTML = "<iframe frameborder='0' scrolling='no' style='border: none; width: 100%; height: 0px' src='poll.php' id='ikiMeFrame'></iframe>\n<div id='translationResult'>" + ajax.responseText + "</div>";
		var translateButton = document.getElementById("translateButton");
		translateButton.onclick = translateText;
		translateButton.value = "Преведи";
		fnSelect("translationResult");
	}
}

function wikiTitles(target)
{
	var wiki = document.getElementById("wiki");
	var subt = document.getElementById("subt");
	if (target == "wiki" && wiki.checked && subt.checked)
		subt.checked = false;
	else if ( target == "subt" && subt.checked && wiki.checked)
		wiki.checked = false;
}

function switchToSerbian()
{
	Cookie.set("language", "s");
	location.reload(true);
}

function switchToEnglish()
{
	Cookie.set("language", "e");
	location.reload(true);
}

function switchToCroatian()
{
	Cookie.set("language", "h");
	location.reload(true);
}

function getNewRow(newText, obj, menu, title)
{
	var row = document.createElement("tr");
	var cell = document.createElement("td");
	cell.onclick = (function(newText, obj, menu)
	{
		return function()
		{
			obj.innerHTML = newText;
			menu.style.display = "none";
		}
	})(newText, obj, menu);
	cell.onmouseover = (function(cell)
	{
		return function()
		{
			cell.className = "multipleChoiceHover";
		}
	})(cell);
	cell.onmouseout = (function(cell)
	{
		return function()
		{
			cell.className = "multipleChoice";
		}
	})(cell);
	cell.appendChild(document.createTextNode(title));
	row.appendChild(cell);
	return row;
}

function showMultipleChoiceMenu(arr, obj)
{
	var i;
	var menu = document.getElementById("multipleChoiceMenu");
	var table = document.createElement("table");
	table.className = "multipleChoiceMenu";
	table.cellPadding = 0;
	table.cellSpacing = 0;
	var title = "";
	for (i = 0; i < arr.length; i++) {
		if (arr[i].indexOf('#') >= 0) {
			title = arr[i].substr(0, arr[i].indexOf('#'));
			arr[i] = arr[i].replace('#', ' (') + ')';
		} else
			title = arr[i];
		var newRow = getNewRow(title, obj, menu, arr[i]);
		table.appendChild(newRow);
	}
	var newRow;
	if (arr[0].indexOf(' (') >= 0)
		newRow = getNewRow(arr[0].substr(0, arr[0].indexOf(' (')), obj, menu, "<првобитни избор>");
	else
		newRow = getNewRow(arr[0], obj, menu, "<првобитни избор>");
	table.appendChild(newRow);

	var coordinates = objectCoords(obj);
	menu.innerHTML = "";
/*	  for ( i = menu.childNodes.length; i >= 0; i--)
 *		  menu.removeChild(menu.childNodes[i]); //ili menu.innerHTML = "...";*/
	menu.appendChild(table);
	menu.style.display = "block";

	if (coordinates.x + menu.clientWidth > screen.width)

	coordinates.x -= menu.clientWidth;
	if (coordinates.y + obj.clientHeight + menu.clientHeight > screen.height)
	coordinates.y -= menu.clientHeight;

	menu.style.top = (coordinates.y + obj.clientHeight) + "px";
	menu.style.left = coordinates.x + "px";
}

function objectCoords( htmlObject )
{
//	if ( htmlObject.calculatedPos )
//		return htmlObject.calculatedPos;
	var left = 0;
	var top  = 0;
	var originalObject = htmlObject;

	while ( htmlObject.offsetParent ) {
		left += htmlObject.offsetLeft;
		top += htmlObject.offsetTop;
		htmlObject = htmlObject.offsetParent;
	}
	left += htmlObject.offsetLeft;
	top  += htmlObject.offsetTop;
	originalObject.calculatedPos = { x:left, y:top };
	return originalObject.calculatedPos;
}

var currentQuery = null;
var currentStart = null;
var poolTimerId = null;
var gearsStart = null;

function doSearch(x)
{
	if ((window.event?window.event.keyCode:x.which) != 13)
		return;
	setNewUrl(0);
}

function setNewUrl(start, useCurrent)
{
	var q;
	if (useCurrent === true)
		q = currentQuery;
	else
		q = document.getElementById("q").value;
	var cl = "" + window.location;
	if (cl.indexOf("#") >= 0)
		cl = cl.substr(0, cl.indexOf("#"));
	cl = cl + "#" + encodeURIComponent(q) + "#" + start;
	window.location = cl;
	currentQuery = null;
/*	if (poolTimerId !== null) {
		clearTimeout(poolTimerId);
		pollTimerId = null;
	}*/
}

function getUrlArgs()
{
	var cl = "" + window.location;
	var els = cl.split("#");
	if (els.length == 1)
		return null;
	return {
		q: decodeURIComponent(els[1]).replace("+", " "),
		s: (els.length==3?(parseInt(els[2])?parseInt(els[2]):0):0)
	};
}

function drawMoreResults()
{
	var stats = document.getElementById("stats");
	if (stats) {
		var resultCount = parseInt(document.getElementById("stats").childNodes.item(1).nodeValue.replace('.', ''));
		var moreResultTemplate = document.getElementById("moreResultTemplate");
		var moreResults = document.getElementById("moreResults");
	//	moreResults.childNodes.length = 0; // try, it might work :) [or it might not]
		while (moreResults.childNodes.length > 0)
			moreResults.removeChild(moreResults.childNodes.item(0));
		moreResults.appendChild(moreResultTemplate);
		var i;
		for (i = 0; i < 30 && resultCount - i*10 > 0; i++) {
			var moreResultCopy = moreResultTemplate.cloneNode(true);
			if (i != currentStart) {
				moreResultCopy.className = "moreResult";
				moreResultCopy.href = "?search#" + encodeURIComponent(currentQuery) + "#" + i;
	//			{
	//				setNewUrl(i, true);
	//			};
			} else
				moreResultCopy.className = "moreResultCurrent";
			moreResultCopy.removeAttribute("id", 2);
			moreResultCopy.appendChild(document.createTextNode((i+1)+""));
			moreResults.appendChild(moreResultCopy);
		}
	}
}

function poolQuery()
{
//	window.status = window.status + ".";
	var urlArgs = getUrlArgs();
	if (urlArgs && (currentQuery === null || currentQuery != urlArgs.q || currentStart === null || currentStart != urlArgs.s)) {
		currentQuery = urlArgs.q;
		currentStart = urlArgs.s;
		startTranslate();
	}
	poolTimerId = setTimeout(poolQuery, 200);
}

function startTranslate()
{
	var request = AJAX.getAJAXHandler();
	if (currentQuery == null || currentStart === null)
		return;
	//alert("u.cgi?option=google&t=cosetfu&url=http%3A%2F%2Fwww.google.com%2Fsearch%3Fhl%3Dsr%26lr%3Dlang_sr%26safe%3Doff%26ie%3DUTF8%26q%3D" + encodeURIComponent(currentQuery).replace(/%/g, "%25") + "%26start%3D" + (currentStart*10));
	request.open("GET", "u.cgi?option=google&t=frostu" + document.getElementById("dialect").value + document.getElementById("letter").value + "&url=http%3A%2F%2Fwww.google.com%2Fsearch%3Fhl%3Dsr%26lr%3Dlang_sr%26safe%3Doff%26ie%3DUTF8%26q%3D" + encodeURIComponent(currentQuery).replace(/%/g, "%25") + "%26start%3D" + (currentStart*10), true);
	request.onreadystatechange = (function(ajax)
	{
		return function()
		{
			if (ajax.readyState == 4) {
//				document.getElementById("waitSensor").style.visibility = "hidden";
				setTimeout("document.body.style.backgroundImage = 'url(/images/gears-bg-still.gif)';", 800-(new Date().getTime() - gearsStart)%800);
				var resultContainer = document.getElementById("r");
				var stats = document.getElementById("stats");
				if (resultContainer) {
					resultContainer.innerHTML = ajax.responseText;
					resultContainer.className = "r";
				}
				var statsElem = document.getElementById("stats");
				if (statsElem) {
					statsElem.insertBefore(document.createTextNode("Око "), statsElem.firstChild);
					statsElem.appendChild(document.createTextNode(" резултата"));
				}
				drawMoreResults();
			}
		};
	})(request);
	request.send(null);
//	document.getElementById("waitSensor").style.visibility = "visible";
	gearsStart = new Date().getTime();
	document.body.style.backgroundImage = "url(/images/gears-bg.gif)";
	window.scroll(0, 0);
}

function fixateBackground()
{
	var backgroundImage = new Image();
	backgroundImage.src = '/images/gears-bg-still.gif';
	delete backgroundImage;
	setTimeout("document.body.style.backgroundImage = 'url(/images/gears-bg-still.gif)';", 1000);
	document.body.style.backgroundImage = "url(/images/gears-bg-still.gif)";
}

if (window.addEventListener)
	window.addEventListener("load", fixateBackground, false);
else
	window.onload = fixateBackground;

