function CreateXmlHttp()
{
	var xmlHttp = null;

	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try{
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
	}catch (e){
		try{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
		}catch (E){
		}
	}
	@else
	@end @*/
	if (xmlHttp == null) {
		try{
			xmlHttp = new XMLHttpRequest();
		}catch (e){
		}
	}
	return xmlHttp;
}

var xmlHttp = CreateXmlHttp();

if (xmlHttp != null){
	window.xmlHttp = new HttpLoader(xmlHttp);
}

var lps_elm = document.getElementById("list_part_size");
var LIST_PART_SIZE = 20;
if (lps_elm != null)
	LIST_PART_SIZE = parseInt(lps_elm.value);

function HttpLoader(xmlHttp)
{
	this.xmlHttp = xmlHttp;
	this.busy	 = false;
	this.interruptable = false; // 15.03.06 amoro: флаг прерываемости запроса (его может прервать такой же, прерываемый запрос)
	this.load		 = HttpLoader_load;
	this.loadPart	 = HttpLoader_loadPart;
	this.processData = HttpLoader_processData;
}

function HttpLoader_loadPart(el, doc, wnd, mark, afterLoad, marker)
{
	var url = doc.getElementById('part_url').value;
	url += '&id=' + el.className.substring(8);
	if (marker != null)
		url += '&marker=' + marker;
	this.load(el, doc, url, mark, wnd, afterLoad);
}

function HttpLoader_load(el, doc, uri, mark, wnd, afterLoad, data)
{
	if (this.busy)
		return;
	this.busy = true;
	this.el   = el;
	this.doc  = doc;
	this.mark = mark;
	this.wnd  = wnd;
	this.afterLoad = afterLoad;
	if (data == null){
		this.xmlHttp.open("GET", uri, true);
		this.xmlHttp.onreadystatechange = HttpLoader_done;
		this.xmlHttp.send('');
		return;
	}
	this.xmlHttp.open("POST", uri, true);
	this.xmlHttp.onreadystatechange = HttpLoader_done;
	this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	this.xmlHttp.setRequestHeader("Content-Length", data.length);
	this.xmlHttp.send(data);
}
	
// 22.02.06 amoro:
// Отправка массивных данных в серверную часть и установка приемника результатов
// 15.03.06 amoro:
// Добавил возможность создания запросов особого класса - прерываемых.
// Запрос такого класса может прервать другой запрос этого же класса
function HttpLoader_processData(uri, data, callback, cbData, interruptable)
{
	if (interruptable == null)
		interruptable = false;
	if (this.busy && !(this.interruptable && interruptable))
		return;
	this.busy = true;
	this.interruptable = interruptable;
	this.callback = callback;
	this.cbData = cbData;
	// 26.02.06 amoro:
	// Бывает, что URL текущей странички состоит из kwtp://kodeks/ + pPath()
	// Тогда на конце у него оказывается косая (слеш) и присоединение к нему
	// URL-ей, полученных как pPath() + 'something' дает неверный результат.
	// Если убрать косую с конца, эта проблема устраняется
	var durl = document.URL;
	if (durl.charAt(durl.length-1) == "/")
		durl = durl.substr(0, durl.length-1);
	this.xmlHttp.open("POST", uri, true, durl);
	this.xmlHttp.onreadystatechange = HttpLoader_doneProcessData;
	this.xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	this.xmlHttp.setRequestHeader("Content-Length", data.length);
	this.xmlHttp.send(data);
}

function HttpLoader_doneProcessData()
{
	var xmlHttp = window.xmlHttp;
	if (xmlHttp.xmlHttp.readyState != 4)
		return;
	xmlHttp.callback(xmlHttp.xmlHttp.responseText, xmlHttp.cbData);
	xmlHttp.busy = false;
	xmlHttp.interruptable = false;
}

function selY(doc)
{
	var selection = doc.selection;
	if ((selection == null) || (selection.type != 'Text'))
		return null;
	var range = selection.createRange();
	if (range == null)
		return null;
	return range.offsetTop;
}

function HttpLoader_done() 
{
	if (window.xmlHttp.xmlHttp.readyState != 4)
		return;
	// 26.02.06 amoro:
	// Когда осуществляется возврат по истории на список с сортировкой,
	// отличной от умолчальной, то происходит следующее:
	// фрейм списка грузится с умолчальной сортировкой, но до того, как данный обработчик
	// успевает выполнится, сменяется сортировка и фрейм перезагружается, а сюда
	// мы попадаем со ссылками на объекты, которые уже не существуют.
	// Посему сделал, чтобы исключения ловились и игнорировались
	try
	{
		var el  = window.xmlHttp.el;
		var doc = window.xmlHttp.doc;
		var el_top    = 0;
		var p = el;
		while (p != null){
			el_top += p.offsetTop;
			p = p.offsetParent;
		}

		var el_bottom     = el_top + el.offsetHeight;
		var scroll_top    = doc.body.scrollTop;
		var scroll_height = doc.body.scrollHeight;
		var screen_height = doc.body.offsetHeight;
			
		var sel_y = selY(doc);
		if (sel_y != null){
			if ((sel_y < 0) || (sel_y > doc.body.offsetHeight))
				sel_y = null;
		}
			
		el.innerHTML = window.xmlHttp.xmlHttp.responseText;
					
		var style_name = el.className;
		var style_id   = style_name.replace('unload', 'style');
		el.className = 'load';
		
		if (style_name.substring(0, 7) == 'unload'){
			var css = window.xmlHttp.doc.styleSheets;
			for (var i = 0; i < css.length; i++){
				if (css[i].id == style_id){
					var rules = css[i].rules;
					for (var i = 0; i < rules.length; i++){
						var rule = rules[i];
						if (rule.selectorText == '.' + style_name){
							if (rule.style.height == (LIST_PART_SIZE + 'em'))
								rule.style.height = window.xmlHttp.el.offsetHeight + 'px';
							break;
						}
					}
					break;
				}
			}
		}else{
			el.style.height = '';
		}

		var wnd = window.xmlHttp.wnd;
		var doc_wnd = doc.parentWindow;
		if (typeof doc_wnd == 'undefined')
			doc_wnd = doc.defaultView;
		if (window.xmlHttp.mark != null){
			var mark = doc.getElementById(window.xmlHttp.mark);
			if (mark != null)
				mark.scrollIntoView();
			window.xmlHttp.mark = null;
		}else{
			var new_sel_y = null;
			if (sel_y != null)
				new_sel_y = selY(doc);
			if (new_sel_y != null){
				doc.body.scrollTop += new_sel_y - sel_y;				
				new_sel_y = selY(doc);
				wnd.scroll_y = doc.body.scrollTop;
			}else if (doc_wnd.go_up){
				var new_bottom = el.offsetHeight;
				var p = el;
				while (p != null){
					new_bottom += p.offsetTop;
					p = p.offsetParent;
				}
				doc.body.scrollTop += new_bottom - el_bottom;
				wnd.scroll_y = doc.body.scrollTop;
			}else if (style_name.substring(0, 8) != "punload_"){
				var new_top = 0;
				var p = el;
				while (p != null){
					new_top += p.offsetTop;
					p = p.offsetParent;
				}
				doc.body.scrollTop += new_top - el_top;
				wnd.scroll_y = doc.body.scrollTop;
			}
		}
	}
	catch (e)
	{
		window.xmlHttp.busy = false;
		return;
	}

	if ((window.search_res != null) && (window.parent.selectContextInPart != null))
		window.parent.selectContextInPart(window.xmlHttp.el, window);
		
	if (window.xmlHttp.afterLoad != null){
		window.xmlHttp.afterLoad(window.xmlHttp.el, window.xmlHttp.doc, wnd);
		window.xmlHttp.afterLoad = null;
	}
		
	window.xmlHttp.el = null;
	window.xmlHttp.busy = false;

	if (wnd.firstLoad == true)
	{
		if (wnd.updatePage != null)
			wnd.updatePage();
	}
	else
	{
		if (wnd.testVisibility != null)
			wnd.testVisibility(true);
	}
}

function setFocusTo(el)
{
	el.focus();
}

function window_close()
{
	window.close();
}
