function makeHttpRequest(url, callback_function, return_xml)
{
    var http_request = false;

    //Пытаемся создать объект всеми доступными способами
    if (window.XMLHttpRequest)
      { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();

        //Для правильного отображения на русском языке
        if (http_request.overrideMimeType)
          {
              //http_request.overrideMimeType('text/xml');
              http_request.overrideMimeType('text/plain;charset=windows-1251');
          }
       }
    else if (window.ActiveXObject)
       { // IE
          try
          {
              http_request = new ActiveXObject("Msxml2.XMLHTTP");
          }
          catch (e)
          {
              try
               {
                  http_request = new ActiveXObject("Microsoft.XMLHTTP");
               }
              catch (e) {}
          }
       }

    //Если все-таки не удалось-не судьба...
    if (!http_request)
    {
        alert('Unfortunatelly you browser does not support this feature: XMLHttpRequest');
        return false;
    }

    //Ждем изменения состояния на 200 ОК и передаем все вызывающей функции
    http_request.onreadystatechange = function()
     {
        if (http_request.readyState == 4)
        {
            //После || - условие для локальных адресов, там XMLHttpRequest возвращает status=0
            if (http_request.status == 200 || location.href.indexOf('http:')<0&&http_request.status==0)
             {
                if (return_xml)
                {
                    eval(callback_function + 'http_request.responseXML)');
                }
                else
                {
                    //alert(http_request.responseText);
                    eval(callback_function + 'http_request.responseText);');
                    //eval("setInnerHtml('03101','123');");

                }
             }
            else
             {
                alert('There was a problem with the request.(Status: ' + http_request.status + ')');
             }
        }
     }

    //Открытие запроса
    http_request.open('GET', url, true);
    http_request.send(null);
}

//--------------------------------------------------------------------------------------------------------
//-----------Вызов индексатора (/risearch/spider.php проверяет дату /risearch/last_index.cfg)-------------
//--------------------------------------------------------------------------------------------------------
   //Для вызова нужно в _head.tpl прописать <script language="JavaScript" src="/image/common.js"></script>
   //var out_xml='';
   //makeHttpRequest("/risearch/spider.php", "alert(", out_xml);
   //makeHttpRequest("/risearch/spider.php", "void(", out_xml);
//--------------------------------------------------------------------------------------------------------
//----------/Вызов индексатора (/risearch/spider.php проверяет дату /risearch/last_index.cfg)-------------
//--------------------------------------------------------------------------------------------------------

function show_form()
{
	var popup = document.getElementById("all_sites_div");
	popup.style.display = 'block';
}
	
function get_page_size()
{
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

function addGoodToCP(){
	var cell;
	var tbl = document.getElementById('cart-list');
	var id = 1;
	
	//ищем новый идентификатор для товара
	var inputs = tbl.getElementsByTagName('input');
	for(var i=0; i<inputs.length; i++){
		if(inputs[i].name.substr(0, 8)=='id_added'){
			id = Math.max(id, parseInt(inputs[i].name.substr(9)));
		}
	}
	
	var index = tbl.rows.length - 1;
	var counter = parseInt(tbl.rows[index-1].cells[0].innerHTML) + 1;
	id = Math.max(counter, id + 1);
	//добавляем строку
	var row = tbl.insertRow(index);
	row.className = (tbl.rows[index-1].className=='dark' ? 'light' : 'dark');
	//ячейка 1
	cell = row.insertCell(0);
	cell.innerHTML = counter+'<input type="hidden" name="new_id[]" value="'+id+'"><input name="id_added_'+id+'" value="added_'+id+'" type="hidden">';
	//ячейка 2
	cell = row.insertCell(1);
	cell.innerHTML = '<input type="text" class="text" name="title_added_'+id+'">';
	//ячейка 3
	cell = row.insertCell(2);
	cell.innerHTML = '<input type="text" class="text" name="vendorcode_added_'+id+'">';
	//ячейка 4
	cell = row.insertCell(3);
	cell.innerHTML = '<input type="text" class="text" name="category_added_'+id+'">';
	//ячейка 5
	cell = row.insertCell(4);
	cell.innerHTML = '<input type="text" class="text" name="stuff_added_'+id+'">';
	//ячейка 6
	cell = row.insertCell(5);
	cell.innerHTML = '<input type="text" class="text" name="price_added_'+id+'" onkeypress="return checkdigitalfield(event)">';
	//ячейка 7
	cell = row.insertCell(6);
	cell.innerHTML = '<input type="text" class="count-item" name="discount_added_'+id+'__" size="3" onkeypress="return checkdigitalfield(event)" maxlength="2" style="width:30px;">';
	//ячейка 8
	cell = row.insertCell(7);
	cell.innerHTML = '<input type="text" class="count-item" name="count_added_'+id+'__" value="1" size="2" onkeypress="return checkdigitalfield(event)" maxlength="2"><input type="hidden" name="hidden_count_added_'+id+'__" value="1">';
	//ячейка 9
	cell = row.insertCell(8);
	cell.innerHTML = '';
	//ячейка 10
	cell = row.insertCell(9);
	cell.innerHTML = '<input class="del_button" alt="Удалить" title="Удалить" value="" type="submit" onClick="deleteGoodFromCP('+counter+'); return false;">';
	
	for(var i=0; i<row.cells.length; i++){
		row.cells[i].align = "center";
		row.cells[i].valign = "middle";
	}
	row.cells[1].align = "left";
}

function deleteGoodFromCP(id){
	var inputs;
	var classname="dark"
	var tbl = document.getElementById('cart-list');
	tbl.deleteRow(id);
	for(var i=1; i<tbl.rows.length-1; i++){		
		inputs = tbl.rows[i].cells[0].getElementsByTagName('input');
		if(inputs.length > 0 && inputs[0].name=="new_id[]"){
			for(var j=0; j<tbl.rows[i].cells.length; j++){
				inputs = tbl.rows[i].cells[j].getElementsByTagName('input');
				for(var k=0; k<inputs.length; k++){
					inputs[k].name = inputs[k].name.replace(/added_\d+$/, 'added_'+i);
				}
			}
			
			tbl.rows[i].cells[0].innerHTML = i+'<input type="hidden" name="new_id[]" value="'+i+'">';
			tbl.rows[i].cells[9].innerHTML = '<input class="del_button" alt="Удалить" title="Удалить" value="" type="submit" onClick="deleteGoodFromCP('+i+'); return false;">';
		}
		
		tbl.rows[i].className = classname;
		classname = (classname=='dark' ? 'ligth' : 'dark');
	}
}

function putInBasket(form)
{
	form.action = "/usr/extensions/ajax/expressoffice_put_in_basket.php";
	form.target = 'hidden_frame';
	return true;
}

function fixed(e, pos)
{	
	//pos = parseInt((screen.height - e.offsetHeight) / 2);
    if (/MSIE ([\d\.]+).+Win/.test(navigator.userAgent))
    {
        e.style.position = 'absolute';
        var top = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
        return (top + pos) + 'px';
    }
    else e.style.top = pos + 'px';
}

/*Мгновенный поиск (используется JQuery)*/
var qSearch = {
	init: function(id1, id2){
		$('body').attr('search_input', id1);
		$('body').attr('search_popup', id2);
		$('#'+id2).removeAttr('wait');
	},
	
	find: function(input, e){
		var code = (e.keyCode || e.which);
		  
		/*Движение в выпадающем окне*/
		var id = $('body').attr('search_popup');
		if($('#'+id))
		{
			var links = $('#'+id+' a');
			links.removeClass('active');
			var cnt = links.length;
			var current = $('#'+id).attr('current');
			var move = false;
			if(code==38)
			{
				if(!isNaN(current))
				{
					current = (parseInt(current)+cnt-1)%cnt;
				}
				else
				{
					current = cnt-1;
				}
				move = true;
			}
			if(code==40)
			{
				if(!isNaN(current))
				{
					current = (parseInt(current)+1)%cnt;
				}
				else
				{
					current = 0;
				}
				move = true;
			}
			if(move && links[current])
			{
				links[current].className = 'active';
				$('#'+id).attr('current', current);
				qSearch.pretoinput(links[current]);
				return true;
			}
		}
		/*/Движение в выпадающем окне*/
		
		/*Если значение не изменилось, но не делаем запрос к серверу*/
		if(input.getAttribute('value_old')==input.value || (input.getAttribute('value_old')!=input.value && code==13))
		{
			return true;
		}
		input.setAttribute('value_old', input.value);
		/*/Если значение не изменилось, но не делаем запрос к серверу*/
		
		var w = input.parentNode.getElementsByTagName('div')[0];
		//php-скрипт для ajax-запроса
		var phpScript = "/usr/extensions/ajax/search.php";
		$.get(phpScript, {title: input.value},
		  function(data){
			//alert(data);
			if(data)
			{
			  w.innerHTML = data;
			  w.style.display = 'block';
			}
			else
			{
				qSearch.hide(input);
			}
		  });
	},
	
	check: function(input, e){
		var code = (e.keyCode || e.which);
		var id = $('body').attr('search_popup');
		var current = $('#'+id).attr('current');
		var links = $('#'+id+' a');
		if(code==13 && !isNaN(current))
		{
			qSearch.toinput(links[current]);
			/*return false;*/
		}
		return true;
	},
	
	hide: function(input){
		var w = input.parentNode.getElementsByTagName('div')[0];
		w.style.display = 'none';
		
		var id = $('body').attr('search_popup');
		$('#'+id).removeAttr('current');
		$('#'+id).removeAttr('wait');
	},
	
	waithide: function(){
		var id = $('body').attr('search_popup');
		$('#'+id).attr('wait', 1);
		qSearch.toinput(this);
	},
	
	toinput: function(link){
		var input = link.parentNode.parentNode.getElementsByTagName('input')[0];
		input.value = link.innerHTML;
		qSearch.hide(input);
		input.focus();
	},
	
	pretoinput: function(link){
		var input = link.parentNode.parentNode.getElementsByTagName('input')[0];
		input.value = link.innerHTML;
	},
	
	destroy: function(input){
		setTimeout(function(){
								var id = $('body').attr('search_popup');
								if($('#'+id).attr('wait')!=1)
								{
									qSearch.hide(input);
								}
							}, 100);
	}
}
/*/Мгновенный поиск (используется JQuery)*/

/*Где купить - расрывающийся список*/
function getRegion(link)
{
	var div = link;
	while(div.tagName!='DIV')
	{
		div = div.parentNode;
	}
	
	var tbls = div.getElementsByTagName('table');
	if(tbls.length > 0)
	{
		var tbl = tbls[0];
		if(tbl.style.display=='none')
		{
			$('.sub_cities').hide();
			$('.region_name').css('color','');
			$('.region_name').css('borderBottom','1px dashed #0089e1');
			tbl.style.display = '';
			link.style.color = 'black';
			link.style.borderBottom = '1px dashed black';
		}
		else
		{
			tbl.style.display = 'none';
			link.style.color = '';
			link.style.borderBottom = '1px dashed #0089e1';
		}
		return false;
	}
	return true;
}
/*/Где купить - расрывающийся список*/
