// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
name_block = 1;
name_unik = '';
old_elem = 0;
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // if running Internet Explorer
  if(window.ActiveXObject)
  {
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    {
      xmlHttp = false;
    }
  }
  // if running Mozilla or other browsers
  else
  {
    try
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {
      xmlHttp = false;
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)

    alert("Error creating the XMLHttpRequest object.");
  else
    return xmlHttp;
}

// make asynchronous HTTP request using the XMLHttpRequest object
function process(q, n, ccount)
{
	name_block = n;
	ccount = ccount || 1;//количество заказаных товаров
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {
    // retrieve the name typed by the user on the form
    //name = encodeURIComponent(document.getElementById("myName").value);
    // execute the ajax.php page from the server

	switch(name_block)
	  {
		case 1:xmlHttp.open("GET", "/ajax/filtr.php?q=" + q + "&razdel=" + ccount + "&r="+Math.random(), true);
		break;
		case 2:name_unik = q;
		document.getElementById(name_unik+'_compare').innerHTML = '<img src="/ajax/pw.gif">';//картинка имитации загрузки результатов
		xmlHttp.open("GET", "/ajax/filtr.php?compare=" + q + "&r="+Math.random(), true);
		break;
		case 3:
		document.getElementById('cart').innerHTML = '<img src="/ajax/pw.gif">';//картинка имитации загрузки результатов
		xmlHttp.open("GET", "/ajax/filtr.php?cart=" + q + "&count="+ccount+"&r="+Math.random(), true);
		break;
	  }
    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse;
    // make the server request
    xmlHttp.send(null);
  }
}

// executed automatically when a message is received from the server
function handleServerResponse()
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4)
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200)
    {
	  // extract the XML retrieved from the server
      /*xmlResponse = xmlHttp.responseXML;
      // obtain the document element (the root element) of the XML structure
      xmlDocumentElement = xmlResponse.documentElement;
      // get the text message, which is in the first child of
      // the the document element
      helloMessage = xmlDocumentElement.firstChild.data;
	*/
	  Message = xmlHttp.responseText;
      // update the client display using the data received from the server
    //alert(Message);
	switch(name_block)
	{
		case 1:	
		var reg=/(.*)###(.*)/;
		if((arr=reg.exec(Message)) != null)
		{
			document.getElementById("result").innerHTML = arr[1];
			document.getElementById('ttip').innerHTML = arr[2];
		}
		break;
		case 2: document.getElementById(name_unik+"_compare").innerHTML = Message;
		break;
		case 3: 
		var mass3 = Message.split(':');
		document.getElementById("cart").innerHTML = mass3[0];
		document.getElementById("basket").innerHTML = mass3[1];
		break;
	}
	  // restart sequence
    }
    // a HTTP status different than 200 signals an error
    else
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

function display(id, edizm) 
{
	var c = document.getElementById('cart_'+id);
	if(old_elem)
	{
		var old = document.getElementById('cart_'+old_elem);
		old.innerHTML = '';
	}
	old_elem = id;
	if (c.style.display != "block")
	{
		html = "<form onSubmit=\"process("+id+",3,document.forms['count_cart'].elements[0].value);return false;\" name='count_cart'><input type='text' style='width:27px;' name='ccount' value='1'> "+edizm+"</form> <span id='cart' onClick=\"process("+id+",3,document.forms['count_cart'].elements[0].value)\"><u>добавить</u></span>";

		c.innerHTML = html;
		c.style.display = "block";
	}
	else
	{
		c.style.display = "none";
	}
    return false;
}




timeout_id = '';
id_f = new Array();//массив с отмечеными чекбоксами
function filtr_res(id)//ф-я обработки события клика по чекбоксу
{
	//document.getElementById('ttip').innerHTML = 'Идет запрос, подождите пожалуйста <br> <img src="/ajax/pw.gif">';//загрузка в подсказку
	if(id.checked)
		id_f[id.name] = id.name;
	else
		id_f[id.name] = 0;
	
	clearTimeout(timeout_id);
	timeout_id = setTimeout('filtr_get(1)',500);//ждем пол сек после каждого действия пользователя
	document.getElementById('result').innerHTML = '<img src="/ajax/pw.gif">';//картинка имитации загрузки результатов
}

function filtr_res2(id)//ф-я обработки события клика по сгенирированному чекбоксу
{
	//alert(id.name);
	//alert(id.value);

	if(id.checked)
		id_f[id.name] +=  id.value + '!';
	else
		id_f[id.name] = id_f[id.name].replace(id.value + '!','');
	
	clearTimeout(timeout_id);
	timeout_id = setTimeout('filtr_get(2)',500);//ждем пол сек после каждого действия пользователя
	document.getElementById('result').innerHTML = '<img src="/ajax/pw.gif">';//картинка имитации загрузки результатов
}

function filtr_get(v)//ф-я подсчета и отправки запроса отмеченых чекбоксов
{
	var q = '';
	if(v == 1)
	{
		for(var key in id_f) 
		{
			if(id_f[key])
				q = q + id_f[key] + ':';
		}
	}
	if(v == 2)
	{
		for (var sKey in id_f)
		{
			q = q + sKey + '!' + encodeURIComponent(id_f[sKey]) + ';';
			/*for(i=0;i<arr[sKey].length;i++)
			{
				q = q + sKey + '=' + id_f[sKey][i] + '&';
			}*/
		}
		q = q.replace(/undefined/g,'');//удалим все несуществующие переменные
		//alert(q);
	}
	process(q,1,document.getElementById('razdel').value);//ajax
}
