// Интервал для всех времязависимых функций.
var delay = 30;
var flag = false;
scroll_h = 0;

function ajaxFunction(element, url, flag)
{	var xmlHttp;
	try {// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();		
	} catch (e) {// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	
	xmlHttp.onreadystatechange = function()
	{
		if (xmlHttp.readyState == 4)
		{	AJAXmsg = xmlHttp.responseText.valueOf();
				elem.innerHTML += /*'<!-- INSERT-START -->' +*/ AJAXmsg.substring(AJAXmsg.indexOf('/>',AJAXmsg.indexOf('/>')+3)+2, AJAXmsg.lastIndexOf('</div>')) /*+ '<!-- INSERT-FINISH -->'*/;
			
			page_id="/default.asp?trID=" + element.id.substring(3);
			pageTracker._trackPageview (page_id);
			
			elem.style.height = 'auto';
			elem.style.background = 'none'; // абсолютно не обязательно
			if (scroll_h != -1)
				setTimeout("window.scrollTo(0, '" + scroll_h + "')", 100);
			
		}
	}

//	var elem = document.getElementById(id);
	var elem = element;
	if (!elem) {
		alert('The passed element doesn\'t exists in your page');
		return false;
	}
	
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

// Функция отключает крестик если после загрузки страницы элемент всего один, вешается на онлоад
function check_one()
{	// Считаем ветви и отрабатываем включение "крестика"
	y = document.getElementById('content_container');
	c = 0;
	len = y.childNodes.length;
	for (i=0;i<len;i++)
		if (y.childNodes[i].nodeName == 'DIV')
		{	c++;
//			alert(y.childNodes[i].id);
		}
//	alert(c);
	if (c == 1)
	{	mas = y.childNodes;
		for (i=0;i<mas.length;i++)
		{	if (mas[i].nodeName == 'DIV')
			{	mas[i].firstChild.setAttribute('src', '/images/2sun/close_dis.gif');
				mas[i].firstChild.style.cursor = 'pointer';
				mas[i].firstChild.setAttribute('onclick', '');
				mas[i].firstChild.setAttribute('alt', 'Невозможно закрыть');
				mas[i].firstChild.setAttribute('title', 'Невозможно закрыть');
			}
		}
	}
}


// Добавление нового блока. При наличии элемента - сворачиваем его.
function new_block (id, element)
{	// Выбираем нужный уровень дерева
	if (element)
	{	y = document.getElementById('content_container');
		x = element;
		while(x != y)
		{	element = x;
			x = x.parentNode;
		}
	}
	
	// Очередной костыль, бля!
	if (flag)
		element = false;
	
	// Удаляем все кроме родительского элемента
	remove_all(element);
	
	// Блокировка попытки вызова самого себя
	if (element == document.getElementById('id_'+id))
		return false;

	// Сворачиваем блок если указан
	if (element)
		if (element.firstChild.nextSibling.getAttribute('src').match("mini")) // проверяем развернут ли
			minimize(element);
	
	// Проверяем создаваемое на существование, удаляем если существует
	if (old_id = document.getElementById('id_' + id))
		old_id.parentNode.removeChild(old_id);

	// Создаем новый блок
	newDiv = document.createElement('div');
	newDiv.id = 'id_' + id;
	newDiv.className = 'window';
	
	// Считаем ветви и отрабатываем включение "крестика"
	y = document.getElementById('content_container');
	c = 0;
	for (i=0;i<y.childNodes.length;i++)
		if (y.childNodes[i].nodeName == 'DIV')
			c++;
	if (c == 1)
	{	mas = y.childNodes;
		for (i=0;i<mas.length;i++)
		{	if (mas[i].nodeName == 'DIV')
			{	mas[i].firstChild.setAttribute('src', '/images/2sun/close.gif');
				mas[i].firstChild.style.cursor = 'pointer';
				if (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.substr(navigator.appVersion.indexOf('MSIE')+5, 1) < 8)
					mas[i].firstChild.setAttribute('onclick', function(){closex(this);return false;});
				else
					mas[i].firstChild.setAttribute('onclick', 'closex(this); return false;');
			}
		}
	}
	
	// Если указан элемент, то надо всунуть блок за ним, если нет, то в конец
	if (element)
		x = element.parentNode.insertBefore(newDiv, element.nextSibling);
	else
		x = document.getElementById('content_container').appendChild(newDiv);

	x.style.height = '16px';
	x.style.background = 'url(/images/2sun/loading.gif)';

	// Вырубаем крестик если пересоздалась одна ветвь
	if (c === 0)
		x.innerHTML = "<img class=\"button\" style=\"cursor: default;\" src=\"/images/2sun/close_dis.gif\" /><img class=\"button\" onclick=\"minimize(this); return false;\" src=\"/images/2sun/minimize.gif\" />";
	else
		x.innerHTML = "<img class=\"button\" onclick=\"closex(this); return false;\" alt=\"Закрыть\" title=\"Закрыть\" src=\"/images/2sun/close.gif\" /><img class=\"button\" onclick=\"minimize(this); return false;\" alt=\"Свернуть\" title=\"Свернуть\" src=\"/images/2sun/minimize.gif\" />";

	// Поехали за контентом
	//alert(location.hostname);  //определяем доменное имя	
	//site_url=window.location.hostname; //задаем на сервере, так в ие глючит
	
	ajaxFunction(document.getElementById('id_' + id), 'http://'+site_url+'/default.asp?trID=' + id + '&mode=ajax');
	
	// Двигаем скроллер на свежеоткрытый блок если идет догрузка вниз
	if (!element)
		myScrollTo(document.getElementById('id_' + id));
	else
		scroll_h = -1;
}

////////////////////////////////////////////////////////////////////////////////////////////////////

// рекурсивная функция СЖимающая элемент
function in_it (element)
{	h = element.clientHeight;
	if (h > 16)
	{	element.style.height = Math.round(0.7*(h)) + 'px';
		setTimeout("in_it (element)", delay);
	}
	else
	{	element.style.height = 16 + 'px';
		element.style.position = 'relative'; // !!!

		switch_button(element);
	}
}

// рекурсивная функция РАЗЖимающая элемент
function out_it (element, n) // итоговая ожидаемая высота
{	h = element.clientHeight;
	if (h/0.7 < n)
	{	element.style.height = Math.round(h/0.7) + 'px';
		setTimeout("out_it (element, '" + height + "')", delay);
	}
	else
	{	element.style.height = '';
		
		switch_button(element);
	}
}

// рекурсивная функция удаляющая элемент
function del_it (element)
{	h = element.clientHeight;
	if (h > 2)
	{	element.style.height = Math.round(0.5*(h)) + 'px';
		setTimeout("del_it (element)", delay);
	}
	else
		element.parentNode.removeChild(element);
		
}

// Функция переключения кнопки
function switch_button (element) // element - ДИВ для сворачивания/разворачивания
{	// вытаскиваем нужную кнопку
	element = element.firstChild.nextSibling;
	if (navigator.appName == 'Microsoft Internet Explorer' && navigator.appVersion.substr(navigator.appVersion.indexOf('MSIE')+5, 1) < 8)
	{	if (element.getAttribute('src').match("maxi")) // если нажали РАЗВЕРНУТЬ
		{	element.setAttribute('onclick', function(){minimize(this);return false;});
			element.setAttribute('src', '/images/2sun/minimize.gif');
			element.setAttribute('alt', 'Свернуть');
			element.setAttribute('title', 'Свернуть');
		}
		else // если нажали СВЕРНУТЬ
		{	element.setAttribute('onclick', function(){maximize(this);return false;});
			element.setAttribute('src', '/images/2sun/maximize.gif'); // При изменении см. условие IF
			element.setAttribute('alt', 'Развернуть');
			element.setAttribute('title', 'Развернуть');
		}
	}
	else
	{	//element = element.firstChild.nextSibling;
		if (element.getAttribute('src').match("maxi")) // если нажали РАЗВЕРНУТЬ
		{	element.setAttribute('onclick', 'minimize(this); return false;');
			element.setAttribute('src', '/images/2sun/minimize.gif');
			element.setAttribute('alt', 'Свернуть');
			element.setAttribute('title', 'Свернуть');
		}
		else // если нажали СВЕРНУТЬ
		{	element.setAttribute('onclick', 'maximize(this); return false;');
			element.setAttribute('src', '/images/2sun/maximize.gif'); // При изменении см. условие IF
			element.setAttribute('alt', 'Развернуть');
			element.setAttribute('title', 'Развернуть');
		}
	}

	return false;
}

////////////////////////////////////////////////////////////////////////////////////////////////////

/* MINImization */
function minimize (x)
{	y = document.getElementById('content_container');

	while(x != y)
	{	element = x;
		x = x.parentNode;
	}

	element.firstChild.nextSibling.setAttribute('onclick', '');
	element.style.overflow = 'hidden';
	height = element.clientHeight;

//	alert(element.lastChild.nodeName + '->' + element.lastChild.id);
	if (element.lastChild.nodeName == 'DIV')
		element.lastChild.style.display = 'block'; // показываем заголовок
	else
		element.lastChild.previousSibling.style.display = 'block'; // показываем заголовок


	in_it(element);

	// Сохраняем исходную высоту блока
	hint = document.createElement('hint');
	element.appendChild(hint);
	element.lastChild.data = height;

	return false;
}


/* MAXImization */
function maximize (x)
{	y = document.getElementById('content_container');
	
	while(x != y)
	{	element = x;
		x = x.parentNode;
	}

	element.firstChild.nextSibling.setAttribute('onclick', '');
	height = element.lastChild.data;
	element.lastChild.parentNode.removeChild(element.lastChild);
//	element.lastChild.parentNode.removeChild(element.lastChild.previousSibling);

	if (element.lastChild.nodeName == 'DIV')
		element.lastChild.style.display = 'none'; // показываем заголовок
	else
		element.lastChild.previousSibling.style.display = 'none'; // убираем заголовок
//	alert(element.lastChild.previousSibling.nodeName + '->' + element.lastChild.previousSibling.id)
	element.style.position = 'static'; // !!!

	out_it(element, height);

	return false;
}


/* CLOSE */
function closex (x)
{	y = document.getElementById('content_container');

	while(x != y)
	{	element = x;
		x = x.parentNode;
	}

	// Считаем ветви и выключаем "крестик" если закрывают предпоследнюю
	c = 0;
	for (i=0;i<y.childNodes.length;i++)
		if (y.childNodes[i].nodeName == 'DIV')
			c++;
	if (c == 2)
	{	mas = y.childNodes;
		for (i=0;i<mas.length;i++)
		{	if (mas[i] != element && mas[i].nodeName == 'DIV')
			{	mas[i].firstChild.setAttribute('src', '/images/2sun/close_dis.gif');
				mas[i].firstChild.setAttribute('onclick', '');
				mas[i].firstChild.style.cursor = 'default';
			}
		}
	}

	// Схлопываем ветвь
	element.style.overflow = 'hidden';
	del_it(element);
	
	return false;
}

function remove_all (element)
{	if (flag)
	{	y = document.getElementById('content_container');

		for (i=y.childNodes.length-1;i>-1;i--)
			if (y.childNodes[i].nodeName == 'DIV')
				if (!element || y.childNodes[i] != element)
					y.removeChild(y.childNodes[i]);

	}
	flag = false;
}

function myScrollTo(element)
{	y = document.getElementById('content_container');
	total_height = -10; // можно сразу добавку вписать
	fl = true;
	for (i=0;i<y.childNodes.length-1;i++)
	{	if (y.childNodes[i] == element)
			fl = false;
		if (fl && (y.childNodes[i].nodeName == 'DIV'))
			total_height += y.childNodes[i].offsetHeight;
	}				
	
	// Записываем результат в глобальную переменную
	scroll_h = total_height;
}

