function getE(id)
{
	return document.getElementById(id);
}

function change_status(id,reg_id,fld_name){
	dt = new Date();
	dt_day = dt.getDate()<9?'0'+dt.getDate():dt.getDate();
	dt_month = dt.getMonth()<9?'0'+(1+dt.getMonth()):(1+dt.getMonth());

	if( id==reg_id )
	  getE(fld_name).value = dt_day + '.' + dt_month + '.' + dt.getFullYear();
}

function addEvent(element_ptr, event_type, event_func)
{
	if (element_ptr.addEventListener)
	{
		element_ptr.addEventListener(event_type, event_func, false);
	}
	else if (element_ptr.attachEvent)
	{
		element_ptr.attachEvent('on' + event_type, event_func);
	}
}

function getDocumentRoot()
{
	return window.addEventListener || window.attachEvent ? window : document.addEventListener ? document : null;
}


function loadCities(callbackFunction)
{
	if ($('region_id')) {
		$('region').value = $('region_id').value ? $('region_id').options[$('region_id').selectedIndex].innerHTML : '';
	}

	if ($('district_id')) {
		$('district').value = $('district_id').value ? $('district_id').options[$('district_id').selectedIndex].innerHTML : '';
	}

	$('cities').update('<img src="/design/images/ajax-loader.gif" alt="" />обновляется список городов');

	new Ajax.Updater('cities', '/index.htm/kladr/cities', {
		parameters: {
			region_id :		$('region_id') 		? 	$('region_id').value	: 0,
			district_id :	$('district_id') 	? 	$('district_id').value	: 0
		},
		onComplete: callbackFunction
	});
}


function loadStreets(callbackFunction)
{
	if ($('city_id')) {
		$('city').value = $('city_id').value ? $('city_id').options[$('city_id').selectedIndex].innerHTML : '';
	}

	$('streets').update('<img src="/design/images/ajax-loader.gif" alt="" />обновляется список улиц');

	new Ajax.Updater('streets', '/index.htm/kladr/streets', {
		parameters: {
			city_id: $('city_id') ? $('city_id').value : 0
		},
		onComplete: callbackFunction
	});
}

function loadDistricts(callbackFunction)
{
	if ($('region_id')) {
		$('region').value = $('region_id').value ? $('region_id').options[$('region_id').selectedIndex].innerHTML : '';
	}

	$('districts').update('<img src="/design/images/ajax-loader.gif" alt="" />обновляется список районов');

	new Ajax.Updater('districts', '/index.htm/kladr/districts', {
		parameters: {
			region_id: $('region_id') ? $('region_id').value : 0
		},
		onComplete: callbackFunction
	});
}

/**
* Перед отправкой формы открывает окно с показом процесса загрузки.
* Необходимо для форм, у которых долго происходит процесс получения 
* результата от сервера.
*/
function ShowProgressWindowBeforeFormSubmit()
{
	var popupWindow = new PopupWindow();
	popupWindow.setWidth(300);
	
	popupWindow.setData('<center><h1>Пожалуйста, подождите...</h1><img src="/design/g2p/images/loaders/gibdd-next-step.gif" width="220" height="19" alt="Отправка формы" /></center>');
	
	popupWindow.show();
}

/* Класс для создания popup-окна с затенением страницы */
function PopupWindow()
{
	// Список кнопок popup окна, выводящихся внизу
	var windowButtons	= [];
	
	// Размеры
	var popupWidth	= 0;
	var popupHeight	= 0;
	
	// Тень
	var shadowDiv	= null;
	// Контейнер для текста
	var textDiv		= null;
	// Блок сообщения
	var messageDiv	= null;
	// Блок с кнопками
	var buttonsDiv	= null;
	
	// HTML-текст сообщения
	var innerHtmlObject	= null;
	
	function getWindowHeight()
	{
		var documentElement = document.documentElement;
		return (self.innerHeight || (documentElement && documentElement.clientHeight) || document.body.clientHeight);
	}
	
	function createHtmlWindow()
	{
		// Основная тень
        shadowDiv = document.createElement('div');
        shadowDiv.className = 'shadow_block';
        shadowDiv.style.width = (document.body.clientWidth - 40) + 'px';
        
        var windowHeight = getWindowHeight();
        var documentHeight = document.body.clientHeight;
        
        shadowDiv.style.height = ((windowHeight > documentHeight) ? windowHeight : documentHeight)  + 'px';
        
        // Блок с сообщением
        messageDiv = document.createElement('div');
        messageDiv.className = 'message_container';
        shadowDiv.appendChild(messageDiv);
        
        textDiv = document.createElement('div');
        textDiv.className = 'text';
        messageDiv.appendChild(textDiv);
        
        // Блок с кнопками
        buttonsDiv = document.createElement('div');
        buttonsDiv.className = 'buttons';
        messageDiv.appendChild(buttonsDiv);
        
        document.getElementsByTagName('body')[0].appendChild(shadowDiv);
	}
	
	function closeWindow()
	{
		shadowDiv.style.display = 'none';
	}
	
	function showWindow()
	{
		// Зададим размеры
        if (popupWidth > 0)
		{
		    messageDiv.style.width = popupWidth + 'px';
        }
        
        if (popupHeight > 0)
		{
			textDiv.style.height = popupHeight + 'px';
		}
		
		// Зададим контент
		var childrens = textDiv.childNodes;
		for (i = childrens.length - 1; i >= 0; i--)
		{
			textDiv.removeChild(childrens[i]);
		}
		
		textDiv.appendChild(innerHtmlObject);
		
		// Впишем кнопки
		// Сначала удалим старые
		var buttons = buttonsDiv.childNodes;
		for (i = buttons.length - 1; i >= 0; i--)
		{
			buttonsDiv.removeChild(buttons[i]);
		}
		
		for (i = 0; i < windowButtons.length; i++)
		{
			buttonsDiv.appendChild(windowButtons[i]);
		}
		
		// Покажем блок
		shadowDiv.style.display = '';
		
		// Если не задана высота и контент больше окна, то надо уменьшить высоту
		if (popupHeight <= 0)
		{
			var maxHeight = getWindowHeight() - 100;
			if (textDiv.clientHeight > maxHeight)
			{
				textDiv.style.height = maxHeight + 'px';
			}
			else
			{
				textDiv.style.height = '';
			}
		}
		
		// Определим смещение страницы по высоте
        var windowScrollY = (navigator.userAgent.indexOf('Firefox') != -1 ? scrollY : document.body.scrollTop);
        // Определим размер видимой области
		var visibleHeight = getWindowHeight();
		// Разместим блок по центру видимой области
		messageDiv.style.marginTop = (visibleHeight / 2) - (messageDiv.clientHeight / 2) + windowScrollY + 'px';
	}
	
	function WindowObject()
	{
		createHtmlWindow();
		
		this.setWidth = function(newWidth)
		{
			popupWidth = parseInt(newWidth);
		}
		
		this.setHeight = function(newHeight)
		{
			popupHeight = parseInt(newHeight);
		}
		
		this.setData = function(newObject)
		{
			if (typeof(newObject) == 'object')
			{
				innerHtmlObject = newObject;
			}
			else
			{
				var newDiv = document.createElement('div');
				newDiv.innerHTML = newObject;
				innerHtmlObject = newDiv;
			}
		}
		
		this.show = function()
		{
			showWindow();
		}
		
		this.close = function()
		{
			closeWindow();
		}
		
		/**
		* @access public
		* @param int buttonText Текст для кнопки
		* @param function functionClickHandler Обработчик нажатия кнопки
		*/
		this.addButton = function(buttonText, functionClickHandler)
		{
			var newButton = document.createElement('button');
	        newButton.appendChild(document.createTextNode(buttonText));
	        $(newButton).observe('click', functionClickHandler);
	        
	        windowButtons.push(newButton);
		}
		
		this.removeButtons = function()
		{
			windowButtons = [];
		}
	}
	
	return new WindowObject();
}