//----- для ajax
function getHTTPObject() {
	var isDOM = document.getElementById;
	var isO   = isO5 = window.opera && isDOM;
	var isIE  = document.all && document.all.item && !isO;
	var isIE5 = isIE && isDOM;
	try {
		var control = (isIE5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';
		xmlhttp = new ActiveXObject(control);
	} catch (e) {
		xmlhttp = false;
	}
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = null;
		}
	}
	return xmlhttp;
}

//----- получение селектов для формы поиска
var searchProducer = '';
var searchCustomer = '';
var t = window.setTimeout(searchSel, 500);
function searchSel(){
	// производители
	var prodTD = document.getElementById('producerTD');
	if(prodTD){
		var mydate = new Date();
		var xmlhttp = getHTTPObject();
		var producerID = searchProducer;
		if(!searchProducer){ producerID = formValue('producer'); }
		xmlhttp.open("GET", "/search/select.p3?type=producer&uniq=" + mydate.valueOf() + "&producer=" + producerID, true);
		xmlhttp.onreadystatechange = function() {
			if(xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					//prodTD.innerHTML = xmlhttp.responseText;
					fillSelect('producer',xmlhttp.responseText);
					// makeSelect(xmlhttp.responseText);
					// TODO: на сделанный селект повесить функцию загрузки списка кодов выбранного производителя
				};
			}
		}
		xmlhttp.send(null);
	}
	// покупатели
	var custTD = document.getElementById('customerTD');
	var custTR = document.getElementById('customerTR');
	if(custTD){
		var mydate = new Date();
		var xmlhttp2 = getHTTPObject();
		var customerID = searchCustomer;
		if(!searchCustomer){ customerID = formValue('customer'); }
		xmlhttp2.open("GET", "/search/select.p3?type=customer&uniq=" + mydate.valueOf() + "&customer=" + customerID, true);
		xmlhttp2.onreadystatechange = function() {
			if(xmlhttp2.readyState == 4) {
				if (xmlhttp2.status == 200) {
					if(xmlhttp2.responseText != ''){
						//custTD.innerHTML = xmlhttp2.responseText;
						fillSelect('customer',xmlhttp2.responseText);
						try{
							custTR.style.display = 'table-row';
						}catch(exception){ // ибо IE не понимает table-row
							custTR.style.display = 'block';
						}
					}
				};
			}
		}
		xmlhttp2.send(null);
	}
}

function formValue(fieldName) {
	var str = window.location.search.substring(1);
	var parts = str.split("&");
	for (var i=0;i<parts.length;i++) {
		var pparts = parts[i].split("=");
		if (pparts[0] == fieldName) {
			return pparts[1];
		}
	}
}

//----- создание селекта производителей/покупателей
function fillSelect(n,txt){
	var sel = document.getElementById(n+'Sel');
	if(sel){
		sel.options[0].firstChild.nodeValue = '- выберите -';
		var ops = txt.split('|');
		var cur = 0;
		for(var i=0; i<ops.length; i++){
			var oops = ops[i].split('===');
			var optVal = oops[0];
			var nextopt = document.createElement('OPTION');
			var nextoptTxt = document.createTextNode(oops[1]);
			nextopt.appendChild(nextoptTxt);
			if(optVal.indexOf('+++') == 0){
				nextopt.setAttribute('selected','selected');
				optVal = optVal.substr(3);
				cur = i + 1;
			}
			nextopt.setAttribute('value',optVal);
			sel.appendChild(nextopt);
		}
		if(cur){
			sel.selectedIndex = cur;
			showIDs(sel);
		}
	}
}

//----- вывод значений выбранного производителя/покупателя
function showIDs(o){
	var t = o.id.replace(/Sel$/,'');
	var sel = document.getElementById(t+'IDs');
	var inp = document.getElementById(t+'ID');
	if(sel && inp){
		val = o.value;
		if(parseInt(val) > 0){
			// загрузка и показ селекта
			loadSelect(sel,t,val,inp.value);
			sel.style.display = 'block';
			sel.name = t+'id';
			inp.style.display = 'none';
			inp.name = '';
		}else{
			// показ строки для ввода текста
			inp.style.display = 'block';
			inp.name = t+'id';
			inp.value = '';
			sel.style.display = 'none';
			sel.name = '';
		}
	}
}

//----- создание селекта идентификаторов
function loadSelect(sel,t,id,curval){
	// очищаем опции кроме первой
	while(sel.options.length > 1){ sel.remove(sel.options.length - 1); }
	var mydate = new Date();
	var xmlhttp = getHTTPObject();
	var articul = '';
	var addr = "/search/articuls.p3?type="+t+"&uniq=" + mydate.valueOf() + "&id=" + id + "&articul=" + articul;
	//alert(addr);
	xmlhttp.open("GET", addr, true);
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				//alert(xmlhttp.responseText);
				var cur = 0;
				var ops = xmlhttp.responseText.split('|');
				for(var i=0; i<ops.length; i++){
					var nextopt = document.createElement('OPTION');
					var nextoptTxt = document.createTextNode(ops[i]);
					if(ops[i] == curval){
						nextopt.setAttribute('selected','selected');
						cur = i + 1;
					}
					nextopt.appendChild(nextoptTxt);
					sel.appendChild(nextopt);
				}
				if(cur){
					sel.selectedIndex = cur;
				}
			};
		}
	}
	xmlhttp.send(null);
}

//----- получение нотаций
function getNotas(id){
	var td = document.getElementById('notas'+id);
	//alert(td.parentNode.style.display);
	if(td.parentNode.style.display == 'table-row' || td.parentNode.style.display == 'block'){
		//alert(1);
		td.parentNode.style.display = 'none';
	}else{
		//alert(2);
		//alert(td.innerHTML.length);
		if(td.innerHTML.length == 1 || td.innerHTML.length == 6){
			//alert(3);
			var xmlhttp = getHTTPObject();
			var mydate = new Date();
			xmlhttp.open("GET", "/catalog/nota.p3?id=" + id + "&uniq=" + mydate.valueOf(), false); // синхронно, чтобы 100% подгрузилось
			xmlhttp.send(null);
			//alert('!' + xmlhttp.responseText + '!');
			if(xmlhttp.responseText != ''){
				td.innerHTML = xmlhttp.responseText;
				if(document.all && document.all.item && !(window.opera && isDOM)){
					td.parentNode.style.display = 'block';
				}else{
					td.parentNode.style.display = 'table-row';
				}
			}else{
				alert('Нет производителей/покупателей');
			}
		}else{
			//alert(4);
			if(document.all && document.all.item && !(window.opera && isDOM)){
				td.parentNode.style.display = 'block';
			}else{
				td.parentNode.style.display = 'table-row';
			}
		}
	}
}

//----- установка длины страницы в куки
function setPageLen(l){
	var expDate = new Date();
	var toMs = 365*24*60*60*1000;
	expDate.setTime(expDate.getTime() + toMs);
	document.cookie = "pagelen=" + escape(l) + "; expires=" + expDate.toGMTString() + "; path=/";
	document.location.reload();
}

//----- изменение количества заказываемого товара
function quant(o,e){
	if (!e) e = event;
	if (!e) e = window.event;
	var code = e.keyCode;
	if(code == 0){code = e.charCode;}
	//alert(e.ctrlKey + '.' + e.shiftKey + '.' + code);
	//if(document.all && document.all.item && !(window.opera && document.getElementById)){
		// IE (+/-)
		if(code == 43){ inc(o.id,e); }
		if(code == 45){ dec(o.id,e); }
		//e.returnValue=false;
	//}else{
		if(code == 38){ inc(o.id,e); }
		if(code == 40){ dec(o.id,e); }
	//}
	//if(!e.ctrlKey && ((code == 32) || ((code > 32) && (code < 48) && e.shiftKey) || (code > 57))){
	if(!e.ctrlKey && (((code >= 32) && (code < 48)) || (code > 57))){
 		if(document.all && document.all.item && !(window.opera && document.getElementById)){
 			e.returnValue=false;
 		}else{
			e.preventDefault();
 		}
	}
	hl(o);
}

function inc(id,e){
	if (!e) e = event;
	if (!e) e = window.event;
	var inp = document.getElementById(id);
	if(inp){
		if(inp.value != '' && parseInt(inp.value)){
			if(e.ctrlKey || e.shiftKey){
				inp.value = eval(parseInt(inp.value) + 10);
			}else{
				inp.value = eval(parseInt(inp.value) + 1);
			}
		}else{
			inp.value = 1;
			if(e.ctrlKey || e.shiftKey){ inp.value = 10; }
		}
		hl(inp);
	}
}

function dec(id,e){
	if (!e) e = event;
	if (!e) e = window.event;
	var inp = document.getElementById(id);
	if(inp){
		if(inp.value != '' && parseInt(inp.value)){
			if(e.ctrlKey || e.shiftKey){
				inp.value = eval(parseInt(inp.value) - 10);
			}else{
				inp.value = eval(parseInt(inp.value) - 1);
			}
			if(parseInt(inp.value) < 0){
				inp.value = 0;
			}
		}else{
			inp.value = 0;
		}
		hl(inp);
	}
}

function hl(o){
	var c = '';
	if(parseInt(o.value) > 0){
		var c = '#cfe3e3';
	}
	o.parentNode.style.background = c;
}

//----- получение количества товаров в корзине и общей стоимости
function getbasket(){
	var btimer = window.setTimeout(_getbasket,300);
}
function _getbasket(){
	var basketElement = document.getElementById('basket');
	if(basketElement){
		var xmlhttp = getHTTPObject();
		var mydate = new Date();
		xmlhttp.open("GET", "/basket/get.p3?uniq=" + mydate.valueOf(), false); // синхронно, чтобы 100% подгрузилось
		xmlhttp.send(null);
		//alert(xmlhttp.responseText);
		if(xmlhttp.responseText != ''){
			basketElement.innerHTML = xmlhttp.responseText;
		}
	}
}

//----- добавление товара в кп
function addProd(id,nota,quant,rel){
	var basketElement = document.getElementById('basket');
	if(basketElement){
		var xmlhttp = getHTTPObject();
		var mydate = new Date();
		var url = "/basket/add.p3?id=" + id;
		if(nota){ url = url + "&notation=" + nota; }
		//alert(typeof(quant));
		if(typeof(quant) != 'undefined'){
			url = url + "&quantity=" + quant;
		}else{
			if(nota){
				var quantField = document.getElementById('cnt_' +id + '_' + nota);
			}else{
				var quantField = document.getElementById('cnt_' + id);
			}
			if(quantField && quantField.value.match(/^\d+$/) && parseInt(quantField.value) > 0){
				url = url + "&quantity=" + quantField.value;
			}
		}
		//alert(url);
		xmlhttp.open("GET", url + "&uniq=" + mydate.valueOf(), false); // синхронно, чтобы 100% подгрузилось
		xmlhttp.send(null);
		if(xmlhttp.responseText != ''){
			if(xmlhttp.responseText == 'no-id'){
				alert('Неправильный номер товара'); //Неправильно задан номер товара.
			}else{
				if(rel){
					//обновляем страницу
					document.location.href = rel;
				}else{
					alert('Товар добавлен'); //Товар добавлен
					basketElement.innerHTML = xmlhttp.responseText;
				}
			}
		}
	}
}

//----- добавление в КП
function put(id,nota){
	var quantField = document.getElementById('cnt_' +id + '_' + nota);
	if(quantField && quantField.value.match(/^\d+$/)){
		addProd(id,nota,quantField.value,'/basket/');
	}
}

//----- удаление из КП
function sub(id,nota){
	var quantField = document.getElementById('cnt_' +id + '_' + nota);
	if(quantField && quantField.value.match(/^\d+$/)){
		addProd(id,nota,quantField.value * -1,'/basket/');
	}
}

//----- удаление из КП
function del(id,nota){
	addProd(id,nota,0,'/basket/');
}

