var getFunctionsURL="ajax/suggest.php?keyword=";
var synonimMaterialURL="item.php?s=";
var httpRequestKeyword="";
var userKeyword="";
var suggestions=0;
var suggestionsMaxLength=27;
var isKeyUpDownPressed=false;
var autocompletedKeyword="";
var hasResults=false;
var timeoutId=-1;
var position=-1;
var oCache=new Object();
var minVisiblePosition=0;
var maxVisiblePosition=9;
var timerSet=-1;
var xmlHttpS=createXmlHttpRequestObject();
window.onload=initWindow;
function createXmlHttpRequestObject(){
	var xmlHttp;
	try{
	xmlHttp = new XMLHttpRequest();
	}
	catch(e){
		var XmlHttpVersions=new Array("MSXML2.XMLHTTP.6.0",
									"MSXML2.XMLHTTP.5.0",
									"MSXML2.XMLHTTP.4.0",
									"MSXML2.XMLHTTP.3.0",
									"MSXML2.XMLHTTP",
									"Microsoft.XMLHTTP");
		for (var i=0;i < XmlHttpVersions.length && !xmlHttp; i++){
			try{
				xmlHttp=new ActiveXObject(XmlHttpVersions[i]);
			}
			catch(e) {}
		}
	}
	if (!xmlHttp){
	}
	else{
		return xmlHttp;
	}
}
function initWindow(){
	var oKeyword=document.getElementById("keyword");
	if (oKeyword){
		oKeyword.value="";
	}
}

function init(){
	var oKeyword=document.getElementById("keyword");
	isKeyUpDownPressed=false;
	timerSet=setTimeout("checkForChanges();",200);
}
function addToCache(keyword,values){	if(values){
		oCache[keyword]=new Array();
		for(i=0;i<values.length;i++)
			oCache[keyword][i]=values[i];
	}
}
function checkCache(keyword){
	if (oCache[keyword])
		return true;
	for (i=keyword.length-2; i>=0; i--){
		var currentKeyword=keyword.substring(0,i+1);
		if (oCache[currentKeyword]){
			var cacheResults=oCache[currentKeyword];
			var keywordResults=new Array();
			var keywordResultsSize=0;
			for (j=0;j<cacheResults.length;j++){
				if (cacheResults[j].indexOf(keyword)==0)
					keywordResults[keywordResultsSize++]=cacheResults[j];
			}
			if (keywordResultsSize>0){
				addToCache(keyword,keywordResults);
				return true;
			}
		}
	}
	return false;
}
function getSuggestions(keyword){
	if (keyword!="" && !isKeyUpDownPressed){
		isInCache=checkCache(keyword);
		if (isInCache==true){
			httpRequestKeyword=keyword;
			userKeyword=keyword;
			displayResults(httpRequestKeyword, oCache[keyword]);
		}
		else{
			if (xmlHttpS){
				try{
					if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
						httpRequestKeyword=keyword;
						userKeyword=keyword;
						xmlHttpS.open("GET",getFunctionsURL+encode(keyword),true);
						xmlHttpS.onreadystatechange=handleGettingSuggestions;
						xmlHttpS.send(null);
					}
					else{
						httpRequestKeyword=keyword;
						if (timeoutId!=-1)
						  clearTimeout(timeoutId);
						timeoutId=setTimeout("getSuggestions(userKeyword);",300);
					}
				}
				catch(e){}
			}
		}
	}
}
function xmlToArray(resultsXml){
	var resultsArray=new Array();
	for (i=0; i<resultsXml.length; i++)
		resultsArray[i]=resultsXml[i].firstChild.nodeValue;
	return resultsArray;
}
function handleGettingSuggestions(){
	if (xmlHttpS.readyState==4){
		if (xmlHttpS.status==200){
			try {
				updateSuggestions();
			}
			catch(e){}
		}
		else{
			/*есть проблемы*/
		}
	}
}
function updateSuggestions(){
	var xmlResponse=xmlHttpS.responseXML;
	var responseRoot=xmlResponse.documentElement;
	nameArray=new Array();
	if (responseRoot.childNodes.length){
		nameArray=xmlToArray(responseRoot.getElementsByTagName("name"));
	}
	if ((httpRequestKeyword.toLowerCase())==(userKeyword.toLowerCase())){
		displayResults(userKeyword,nameArray);
	}
	else{
		addToCache(httpRequestKeyword, nameArray);
	}
}
function displayResults(keyword, results_array){
	var div="<table cellpadding=0 cellspacing=0>";
	if (!oCache[keyword] && keyword)
		addToCache(keyword,results_array);
	if (results_array.length==0){
		div+="<tr><td>По ключу <strong>"+keyword+"</strong> нет информации.</td></tr>";
		hasResults=false;
		suggestions=0;
	}
	else{
		position=-1;
		isKeyUpDownPressed=false;
		hasResults=true;
		suggestions=oCache[keyword].length;
		for (i=0;i<oCache[keyword].length; i++){
			crtFunction=oCache[keyword][i];
			crtFunctionLink=crtFunction;
			div+="<tr id='tr"
			  + i
			  + "' onclick='openSuggested(\""+ crtFunctionLink
			  + "\");' onmouseover='handleOnMouseOver(this);' "
			  + "onmousout='handleOnMouseOut(this);'>"
			  + "<td align=left id='a"+i+"'>";
			if (crtFunction.length<=suggestionsMaxLength){
				div+="<b>"+crtFunction.substring(0,keyword.length)+"</b>";
				div+=crtFunction.substring(keyword.length, crtFunction.length)+
				"</td></tr>";
			}
			else{
				if (httpRequestKeyword.length<suggestionsMaxLength){
					div+="<b>"+crtFunction.substring(0,httpRequestKeyword.length)+"</b>";
					div+=crtFunction.substring(httpRequestKeyword.length, suggestionsMaxLength)+
					"</td></tr>";
				}
				else{
					div+="<b>"+ctrFunction.substring(0,suggestionsMaxLength)+
					"</td></tr>";
				}
			}
		}
	}
	div+="</table>";
	var oSuggest=document.getElementById("suggest");
	var oScroll=document.getElementById("scroll");
	oScroll.scrollTop=0;
	oSuggest.innerHTML=div;
	oScroll.style.height="180px";
	oScroll.style.visibility="visible";
	if (results_array.length>0)
		autocompleteKeyword();
}
function checkForChanges(){
	var keyword=document.getElementById("keyword").value;
	if (keyword=="Открываю...") return;
	if (keyword==""){
		hideSuggestions();
		userKeyword="";
		httpRequestKeyword="";
		position=-1;
		autocompletedKeyword='';
		maxVisiblePosition=9;
		minVisiblePosition=0;
	}
	timerSet=setTimeout("checkForChanges()",200);
	if ((userKeyword.toLowerCase())!=(keyword.toLowerCase()) && (autocompletedKeyword.toLowerCase())!=(keyword.toLowerCase()) && (!isKeyUpDownPressed)){
		getSuggestions(keyword);
	}
}

function handleKeyUp(e){
	e=(!e)?window.event:e;
	target=(!e.target)?e.srcElement:e.target;
	if (target.nodeType==3)
		target=target.parentNode;
	code=(e.charCode)?e.charCode:((e.keyCode)?e.keyCode:((e.wich)?e.wich:0));
	if (e.type=="keyup"){
		isKeyUpDownPressed=false;
		if ((code<13 && code!=8) ||
			(code>=14 && code<32 && code!=27) ||
			(code>=33 && code<46 && code!=38 && code!=40) ||
			(code>=112 && code<=123)){}
		else
			if (code==8){
				e.cancelBubble=true;
				isKeyUpDownPressed=true;
			}
			else
				if (code==13){
					if (position>=0){
						var crtLink=document.getElementById("a"+position).innerHTML;
						var crtLink1=crtLink.substring(crtLink.indexOf('<')+3,crtLink.length);
						crtLink=crtLink1.substring(0,crtLink1.indexOf('<'))+crtLink1.substring(crtLink1.indexOf('>')+1,crtLink1.length);
						openSuggested(crtLink);
					}
				}
				else
					if (code==40){
						newTR=document.getElementById("tr"+(++position));
						oldTR=document.getElementById("tr"+(--position));
						if (position>=0 && position<suggestions-1)
							oldTR.className="";
						if (position<suggestions -1){
							newTR.className="highlightrow";
							updateKeywordValue(newTR);
							position++;
						}
						e.cancelBubble=true;
						e.returnValue=false;
						isKeyUpDownPressed=true;
						if (position > maxVisiblePosition){
							oScroll=document.getElementById("scroll");
							oScroll.scrollTop+=15;
							maxVisiblePosition+=1;
							minVisiblePosition+=1;
						}
					}
					else
						if (code==38){
							newTR=document.getElementById("tr"+(--position));
							oldTR=document.getElementById("tr"+(++position));
							if (position>0 && position<=suggestions-1)
								oldTR.className="";
							if (position>0){
								newTR.className="highlightrow";
								updateKeywordValue(newTR);
								position--;
							}
							e.cancelBubble=true;
							e.returnValue=false;
							isKeyUpDownPressed=true;
							if (position < minVisiblePosition){
								oScroll=document.getElementById("scroll");
								oScroll.scrollTop-=15;
								maxVisiblePosition-=1;
								minVisiblePosition-=1;
							}
						}
						else
							if (code==27){
								document.getElementById("keyword").value="";
								e.cancelBubble=true;
								e.returnValue=false;
								isKeyUpDownPressed=false;
								hideSuggestions();
								userKeyword="";
								httpRequestKeyword="";
							}
	}
}

function updateKeywordValue(oTr){
	var oKeyword=document.getElementById("keyword");
	var crtLink=document.getElementById("a"+oTr.id.substring(2,oTr.id.length)).innerHTML;
	var crtLink1=crtLink.substring(crtLink.indexOf('<')+3,crtLink.length);
	oKeyword.value=crtLink1.substring(0,crtLink1.indexOf('<'))+crtLink1.substring(crtLink1.indexOf('>')+1,crtLink1.length);
}

function deselectAll(){
	for (i=0;i<suggestions;i++)
	{
		var oCrtTr=document.getElementById("tr"+i);
		oCrtTr.className="";
	}
}

function handleOnMouseOver(oTr){
	deselectAll();
	oTr.className="highlightrow";
	position=oTr.id.substring(2,oTr.id.length);
}

function handleOnMouseOut(oTr){
	oTr.className="";
	position=-1;
}

function encode(uri){
	if (encodeURIComponent){
		return encodeURIComponent(uri);
	}
	if (escape){
		return escape(uri);
	}
}

function hideSuggestions(){
	var oScroll=document.getElementById("scroll");
	oScroll.style.height="2px";
	oScroll.style.visibility="hidden";
}

function selectRange(oText,start,length){
	if (oText.createTextRange){
		//IE
		var oRange=oText.createTextRange();
		oRange.moveStart("character",start);
		oRange.moveEnd("character",length-oText.value.length);
		oRange.select();
	}
	else
		if (oText.setSelectionRange) //FireFox
		{
			oText.setSelectionRange(start,length);
		}
		oText.focus();
}

function autocompleteKeyword(){
	var oKeyword=document.getElementById("keyword");
	position=0;
	deselectAll();
	document.getElementById("tr0").className="highlightrow";
	updateKeywordValue(document.getElementById("tr0"));
	selectRange(oKeyword,httpRequestKeyword.length,oKeyword.value.length);
	autocompletedKeyword=oKeyword.value;

}

function displayError(message){
	alert("Ошибка !");
}

function saveItem(itemcode){
	if (xmlHttpS){
		try{
			if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
				xmlHttpS.open("GET","../order/order.php?materialid="+itemcode,true);
				xmlHttpS.onreadystatechange=displayMaterial;
				xmlHttpS.send(null);
			}
			else{
				if (timeoutId!=-1)
				  clearTimeout(timeoutId);
				timeoutId=setTimeout("saveItem(itemcode);",500);
			}
		}
		catch(e){

		}
	}
}

function displayMaterial(){
	if (xmlHttpS.readyState==4){
		if (xmlHttpS.status==200){
			textResponse=xmlHttpS.responseText;
			if (textResponse){
				if  (textResponse.substring(0,1)=='N'){
					textResponse=textResponse.substring(1,textResponse.length);
					alert('Отмеченные позиции вносятся в Ваш лист заказов.\nПосмотреть и отредактировать его можно позже,\nнажав на ссылку "Заказы" в заголовке страницы');
				}
				matElement=document.getElementById(textResponse).innerHTML;
				document.getElementById(textResponse).innerHTML='<span style="background: #FFFF10;">'+matElement+'</span>';
			}
		}
	}

}

function openSection(sectionName, sectionSub){
	if (sectionName=='bill' && sectionSub==0){
		if (billCache){
			sectionInfo(billCache);
			return;
		}
		else sect=0;
	}
	if (xmlHttpS){
		try{
			if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
				if (sectionSub==6){
					var oDate=encode(document.getElementById('oDate').value);
					var oPhone=encode(document.getElementById('oPhone').value);
					var oContactWith=encode(document.getElementById('oContactWith').value);
					sectionInfo("Передача заказа в Хорсс...");
					xmlHttpS.open("GET","../order/order_section.php?Date="+(oDate)+"&Phone="+oPhone+"&ContactWith="+oContactWith,true);
					xmlHttpS.onreadystatechange=displaySection;
					xmlHttpS.send(null);
					orderSaved=true;
				}
				else{
					sectionInfo("Загрузка опций...");
					xmlHttpS.open("GET","../order/order_section.php?section="+(sectionName)+"&sectionSub="+sectionSub+"&saved="+(orderSaved?1:0),true);
					xmlHttpS.onreadystatechange=displaySection;
					xmlHttpS.send(null);
				}
			}
			else{
				if (timeoutId!=-1)
				clearTimeout(timeoutId);
				timeoutId=setTimeout("openSection(sectionName, sectionSub);",500);
			}
		}
		catch(e){

		}
	}
}

function sectionInfo(txt){
	txt1="<table width=99% style='margin: 2px; background: #edecde' class=tdItem border=0 cellpadding=1 cellspacing=0><tr><td>";
	txt2="</td></tr></table>";
	sectionElement=document.getElementById('opening');
	sectionElement.innerHTML=txt1+txt+txt2;
	sectionElement.style.height='auto';
	sectionElement.style.visibility='visible';
}

function displaySection(){
	if (xmlHttpS.readyState==4){
		if (xmlHttpS.status==200){
			textResponse=xmlHttpS.responseText;
			if (textResponse){
				sectionInfo(textResponse);
				if (sect==0 && !(billCache))
					billCache=textResponse;
			}
			else
				sectionInfo('');
		}
	}

}

function savePriceCode(priceCode,itemcode,quant){
	if (xmlHttpS){
		try{
			if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
				xmlHttpS.open("GET","../order/order.php?materialid="+itemcode+"&priceid="+priceCode+"&quant="+quant,true);
				xmlHttpS.onreadystatechange=isnull;
				xmlHttpS.send(null);
			}
			else{
				if (timeoutId!=-1)
				clearTimeout(timeoutId);
				timeoutId=setTimeout("savePriceCode(priceCode,itemcode,quant);",500);
			}
		}
		catch(e){

		}
	}
}

function displayNone(){
	if (xmlHttp.readyState==4){
		if (xmlHttp.status==200){
			textResponse=xmlHttp.responseText;
			if (textResponse){
				document.getElementById('addPos').innerHTML=textResponse;
			}
		}
	}
}

function deleteOrderLine(horssCode){
if (xmlHttpS){
	try{
		if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
			xmlHttpS.open("GET","../order/order.php?deletecode="+(horssCode),true);
			xmlHttpS.onreadystatechange=updateOrderTableRequest;
			xmlHttpS.send(null);
		}
		else{
			if (timeoutId!=-1)
				clearTimeout(timeoutId);
			timeoutId=setTimeout("deleteOrderLine(horssCode);",500);
		}
	}
	catch(e){
	}
}
}
function openSuggested(what){
	if (document.location.pathname=='/order/order.php'){
		if (xmlHttpS){
			try{
				if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
					document.getElementById('addPos').innerHTML='Добавление...';
					xmlHttpS.open("GET","../order/order_add.php?add="+encode(what),true);
					xmlHttpS.onreadystatechange=handleAddPosition;
					xmlHttpS.send(null);
				}
				else{
					if (timeoutId!=-1)
					clearTimeout(timeoutId);
					timeoutId=setTimeout("openSuggested(what);",500);
				}
			}
			catch(e){
			}
		}
	}
	else
		document.getElementById("keyword").value="Открываю...";
	if(what.indexOf('+')>1){
	  what=what.substring(0,what.indexOf('+'))+"%2B"+what.substring(what.indexOf('+')+1,what.length);
	  }
	location.href=synonimMaterialURL+what;
}

function  handleAddPosition(){
	if (xmlHttpS.readyState==4){
		if (xmlHttpS.status==200){
			addResponse=xmlHttpS.responseText;
			if (addResponse){
				if (parseInt(addResponse.substring(0,4),10)>0){
						var what=addResponse;
						addResponse='&larr; Добавьте позицию здесь, если Вы знаете шифр.';
						xmlHttp.open("GET","../order/order.php?materialid="+what,true);
						xmlHttp.onreadystatechange=updateOrderTableRequest;
						xmlHttp.send(null);
				}
				else{
					addResponse+='<br><br>&larr; Добавьте позицию здесь, если Вы знаете шифр.'
				}
				initWindow();
				document.getElementById('addPos').innerHTML=addResponse;
			}
		}
	}
}

function addPosition(itemcode){
	if (xmlHttpS){
		try{
			if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
				xmlHttpS.open("GET","../order/order.php?materialid="+itemcode,true);
				xmlHttpS.onreadystatechange=handleAddPosition;
				xmlHttpS.send(null);
			}
			else{
				if (timeoutId!=-1)
				  clearTimeout(timeoutId);
				timeoutId=setTimeout("addPosition(itemcode);",500);
			}
		}
		catch(e){

		}
	}
}

function updateOrderTableRequest(){
if (xmlHttpS.readyState==4){
		if (xmlHttpS.status==200){
			if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
				xmlHttpS.open("GET","../orderlist.php?code=UTF-8",true);
				xmlHttpS.onreadystatechange=updateOrderTable;
				xmlHttpS.send(null);
			}
			else{
				if (timeoutId!=-1)
				  clearTimeout(timeoutId);
				timeoutId=setTimeout("updateOrderTableRequest();",500);
			}
		}
	}
}

function updateOrderTable(){
		if (xmlHttpS.readyState==4){
		if (xmlHttpS.status==200){
  		orderResponse=xmlHttpS.responseText;
  		if (orderResponse){
  			document.getElementById('orderTable').innerHTML=orderResponse;
				document.getElementById('markCount').innerHTML='<br><b>СТАТУС: составление заказа.</b><br>&nbsp;&nbsp;';
				recalcT();
        hideOpening();
  		}
		}
	}
}

function openSaved(num){
if (xmlHttpS.readyState==4){
		if (xmlHttpS.status==200){
			if (xmlHttpS.readyState==4 || xmlHttpS.readyState==0){
				sectionInfo('Загрузка...');
				xmlHttpS.open("GET","order_open.php?order="+num,true);
				xmlHttpS.onreadystatechange=updateOrderTableRequest;
				xmlHttpS.send(null);
			}
			else{
				if (timeoutId!=-1)
				  clearTimeout(timeoutId);
				timeoutId=setTimeout("openSaved(num);",500);
			}
		}
	}

}

function isnull()
{

}

