var swObj = {'textList':[], 'stack':'', 'first':'', 'ready':true, 'block':false, 'out':false};

function showSwText(text)
{
	text = text.split("'").join("&#039;").split("\"").join("&quot;");

	swObj.stack = text;
	if (!swObj.ready)
		return;
	
	if (!text.length)
		return resetSw(true);
	
	swObj.ready = false;
	if (needSwLoad(text)){
		swObj.first = text.substr(0,1);
		swObj.stack = text;
		swObj.textList.length = 0;
		JsHttpRequest.query('/js_sw_names.php',{'txt':text},loadSwEnd,true);
	} else {
		var str = [], ln = text.length;
		
		for(var i=0; i<swObj.textList.length; i++)
			if (ln == 1 || swObj.textList[i].indexOf(text) == 0)
				str[str.length] = '<p onClick="swWord(\''+swObj.textList[i].split("&#039;").join("\\'").split("&quot;").join("\\\"")+'\')"><b>'+text+'</b>'+swObj.textList[i].substr(ln)+'</p>';

		showSwDiv(str.length ? str.join('') : '<p><i>(אין התאמה)</i></p>');
		swObj.stack == text || showSwText(swObj.stack);
		swObj.ready = true;
	}
}

function resetSw(close)
{
	swObj.textList.length = 0;
	swObj.stack = '';
	swObj.first = '';
	swObj.ready = true;
	(close) ? closeSwDiv() : showSwDiv('');
}

function loadSwEnd(res,html)
{
	if(!res || parseInt(res.status))
		return alert('ERROR '+res.status+': '+html);
	swObj.textList = res.names;
	swObj.ready = true;
	showSwText(swObj.stack);
}

function needSwLoad(text)
{
	var f = text.substr(0,1);
	return (swObj.first == '' || swObj.first != f);
}

function showSwDiv(txt)
{
	var d = document.getElementById('swDiv');
	d.innerHTML = txt;
	d.style.display = 'block';
}

function closeSwDiv()
{
	document.getElementById('swDiv').style.display = 'none';
	swObj.out = false
}

function swWord(word)
{
	document.getElementById('cssw').value = word;
	closeSwDiv(false);
}

function swIn()
{
	swObj.block = true;
}

function swOut()
{
	swObj.block = false;
	!swObj.out || closeDiv(false);
}

function swCheck()
{
	swObj.block ? swObj.out = true : closeSwDiv(false);
}
