function countDown(i, goBack)
{
	if (i < 0) {
		if (goBack > 0 && history.length > 0) {
			window.history.back();
		} else if (goBack > 0 && history.length == 0) {
			document.location = "/";
		}
		return true;
	}

	document.getElementById('counterSpan').innerHTML = '' + i;

	i--;

	if (goBack > 0) {
		timerId = window.setTimeout('countDown(' + i + ', ' + goBack + ')', 1000);
	} else {
		timerId = window.setTimeout('countDown(' + i + ')', 1000);
	}
}

function submitFrameLoad()
{
	if ($('ajax-loader')) {
		Element.remove('ajax-loader');
		document.onkeypress = function() {return true;}
	}

	var json = submit_frame.document.body.innerHTML;
	json = json.strip();
	if (json == '') return;

	try	{
		var response = eval('(' + json + ')');
	} catch (err) {
		showFatalError(json);
		return;
	}

	var msgStyles = ['msg-error', 'msg-warning', 'msg-message'];

	var hold = false;

	var tmptext = '';
	for (var i=0;i<response.messages.length;i++){
		tmptext += '<p class="' + msgStyles[response.messages[i][1]] + '">' + response.messages[i][0] + '</p>';
		if (response.messages[i][1] == 0 || response.messages[i][1] == 1) hold = true;
	}

	if (response.redirect_path && !hold && !($('mode-add-and-add') && $F('mode-add-and-add') == 1)) {
		document.location.href = response.redirect_path;
		return;
	}

	statusLine = $('status-line');
	statusLine.innerHTML = tmptext;
	statusLine.style.display = 'block';
	Element.scrollTo(statusLine.parentNode);
	statusLine.style.backgroundColor = (hold) ? '#efe5e0' : '#aad1d8';
	setTimeout('smoothShow("status-line")', 2000);

	return true;
}

function smoothShow(divId, maxHeight)
{
	$(divId).style.backgroundColor = '#fff';
}


function setCurrentDate(selectYear, selectMonth, selectDay)
{
	var curDate = new Date();
	var year = curDate.getFullYear();
	var month = curDate.getMonth()+1;
	var day = curDate.getDate();

	if ($(selectYear).options[1].value < $(selectYear).options[$(selectYear).options.length-1].value) {
		$(selectYear).selectedIndex = year - $(selectYear).options[1].value + 1;
	} else {
		$(selectYear).selectedIndex = $(selectYear).options[1].value - year + 1;
	}

	$(selectMonth).selectedIndex = month;
	$(selectDay).selectedIndex = day;
}

function refreshSelect(htmlSelectId, source)
{
	document.onkeypress = function(event) { return disableOnKeyPress(event) };

	var body = $$('body')[0];
	var ajaxLoader = document.createElement('DIV');
	ajaxLoader.style.height = $('body').getHeight() + $('header').getHeight() + 20 + 'px';
	if (isIE6()) ajaxLoader.style.width = body.getWidth() + 'px';
	ajaxLoader.setAttribute('id', 'ajax-loader');

	var ajaxLoaderBody = document.createElement('DIV');
	ajaxLoaderBody.setAttribute('id', 'ajax-loader-body');
	ajaxLoaderBody.innerHTML = '<img src="/img/ajax-loader.gif" width="24" height="24" alt="Wait..."/><br />\nОбновление данных. Подождите...';

	ajaxLoader.appendChild(ajaxLoaderBody);
	body.appendChild(ajaxLoader);


	new Ajax.Request(source, {
	  method: 'get',
	  onSuccess: function(transport, json) {
		var list = $(htmlSelectId);

		oldValue = list.options[list.selectedIndex].value;
		list.selectedIndex = 0;
		list.options.length = (list.options[0].value=='')?1:0;

		var f = false;
		for (var i=0;i<json.length;i++) {
			if (json[i].value==oldValue) f = true;

			list.options.add(new Option(json[i].caption, json[i].value, (json[i].value==oldValue), false));
		}

		if (!f && list.options[0].value != '') {
			list.options.length = 0;
			list.options.add(new Option('--- Error ---', '', true));
			alert("Ошибка! Список не перегружен.\nПредыдущее выбраное значение уже не существует (возможно оно было удалено другим пользователем).\nПопытайтесь обновить всю страницу.");
		}

		if ($('ajax-loader')) Element.remove('ajax-loader');
	  }
	});
}


function disableOnKeyPress(event)
{
	if (event.keyCode == Event.KEY_TAB) {
		return false;
	}

	return true;
}

function isIE6()
{
	var agt = navigator.userAgent.toLowerCase();
	var is_major = parseInt(navigator.appVersion);
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	var is_ie6 = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
	return is_ie6;
}

function confirmDelete(message)
{
	var question = 'Вы намерены удалить запись';
	if (message) {
		question += ':\n[' + message + ']';
	}
	question += '\nВы уверены?';
	return confirm(question);
}


function toggleLogin() {

	divLogin = $('header-login');
	if (divLogin.style.display == 'block') {
		divLogin.style.display = 'none';
		$('header-recovery').style.display = 'none';
		$('header-recovery-bg').style.display = 'none';
		$('header-menu2').style.display = 'block';
		$('header-menu2-bg').style.display = 'block';
	} else {
		$('header-menu2').style.display = 'none';
		$('header-menu2-bg').style.display = 'none';
		divLogin.style.display = 'block';
	}
	return false;
}
function toggleRecovery() {

	divRecovery = $('header-recovery');
	if (divRecovery.style.display == 'block') {
		divRecovery.style.display = 'none';
		$('header-recovery-bg').style.display = 'none';
	} else {
		$('header-recovery-bg').style.display = 'block';
		divRecovery.style.display = 'block';
	}
	return false;
}


function countDown(i, goBack)
{
	if (i < 0) {
		if (goBack > 0 && history.length > 0) {
			window.history.back();
		} else if (goBack > 0 && history.length == 0) {
			document.location = "/";
		}
		return true;
	}

	document.getElementById('counterSpan').innerHTML = '' + i;

	i--;

	if (goBack > 0) {
		timerId = window.setTimeout('countDown(' + i + ', ' + goBack + ')', 1000);
	} else {
		timerId = window.setTimeout('countDown(' + i + ')', 1000);
	}
}

function submitFrameLoad()
{
	if ($('ajax-loader')) {
		Element.remove('ajax-loader');
		document.onkeypress = function() {return true;}
	}

	var json = submit_frame.document.body.innerHTML;
	json = json.strip();
	if (json == '') return;

	try	{
		var response = eval('(' + json + ')');
	} catch (err) {
		showFatalError(json);
		return;
	}

	var msgStyles = ['msg-error', 'msg-warning', 'msg-message'];

	var hold = false;

	var tmptext = '';
	for (var i=0;i<response.messages.length;i++){
		tmptext += '<p class="' + msgStyles[response.messages[i][1]] + '">' + response.messages[i][0] + '</p>';
		if (response.messages[i][1] == 0 || response.messages[i][1] == 1) hold = true;
	}

	if (response.redirect_path && !hold && !($('mode-add-and-add') && $F('mode-add-and-add') == 1)) {
		document.location.href = response.redirect_path;
		return;
	}

	statusLine = $('status-line');
	statusLine.innerHTML = tmptext;
	statusLine.style.display = 'block';
	Element.scrollTo(statusLine.parentNode);
	statusLine.style.backgroundColor = (hold) ? '#efe5e0' : '#aad1d8';
	setTimeout('smoothShow("status-line")', 2000);

	return true;
}

function smoothShow(divId, maxHeight)
{
	$(divId).style.backgroundColor = '#fff';
}

function showFatalError(text)
{
	document.onkeypress = function(event) { return disableOnKeyPress(event) };

	var body = $$('body')[0];

	var fatalErrorBox = document.createElement('DIV');
	fatalErrorBox.style.height = $('body').getHeight() + $('header').getHeight() + 20 + 'px';
	if (isIE6()) fatalErrorBox.style.width = body.getWidth() + 'px';
	fatalErrorBox.setAttribute('id', 'fatal-error-box');
	fatalErrorBox.setAttribute('onclick', "Element.remove('fatal-error-box');");

	var fatalErrorBoxMsg = document.createElement('DIV');
	fatalErrorBoxMsg.setAttribute('id', 'fatal-error-box-msg');
	//fatalErrorBoxMsg.style.width = body.getWidth() - 100 + 'px';

	fatalErrorBoxMsg.innerHTML = text;

	fatalErrorBox.appendChild(fatalErrorBoxMsg);
	$('header').appendChild(fatalErrorBox);



}

function setCurrentDate(selectYear, selectMonth, selectDay)
{
	var curDate = new Date();
	var year = curDate.getFullYear();
	var month = curDate.getMonth()+1;
	var day = curDate.getDate();

	if ($(selectYear).options[1].value < $(selectYear).options[$(selectYear).options.length-1].value) {
		$(selectYear).selectedIndex = year - $(selectYear).options[1].value + 1;
	} else {
		$(selectYear).selectedIndex = $(selectYear).options[1].value - year + 1;
	}

	$(selectMonth).selectedIndex = month;
	$(selectDay).selectedIndex = day;
}

function refreshSelect(htmlSelectId, source)
{
	document.onkeypress = function(event) { return disableOnKeyPress(event) };

	var body = $$('body')[0];
	var ajaxLoader = document.createElement('DIV');
	ajaxLoader.style.height = $('body').getHeight() + $('header').getHeight() + 20 + 'px';
	if (isIE6()) ajaxLoader.style.width = body.getWidth() + 'px';
	ajaxLoader.setAttribute('id', 'ajax-loader');

	var ajaxLoaderBody = document.createElement('DIV');
	ajaxLoaderBody.setAttribute('id', 'ajax-loader-body');
	ajaxLoaderBody.innerHTML = '<img src="/img/ajax-loader.gif" width="24" height="24" alt="Wait..."/><br />\nОбновление данных. Подождите...';

	ajaxLoader.appendChild(ajaxLoaderBody);
	body.appendChild(ajaxLoader);


	new Ajax.Request(source, {
	  method: 'get',
	  onSuccess: function(transport, json) {
		var list = $(htmlSelectId);

		oldValue = list.options[list.selectedIndex].value;
		list.selectedIndex = 0;
		list.options.length = (list.options[0].value=='')?1:0;

		var f = false;
		for (var i=0;i<json.length;i++) {
			if (json[i].value==oldValue) f = true;

			list.options.add(new Option(json[i].caption, json[i].value, (json[i].value==oldValue), false));
		}

		if (!f && list.options[0].value != '') {
			list.options.length = 0;
			list.options.add(new Option('--- Error ---', '', true));
			alert("Ошибка! Список не перегружен.\nПредыдущее выбраное значение уже не существует (возможно оно было удалено другим пользователем).\nПопытайтесь обновить всю страницу.");
		}

		if ($('ajax-loader')) Element.remove('ajax-loader');
	  }
	});
}


function disableOnKeyPress(event)
{
	if (event.keyCode == Event.KEY_TAB) {
		return false;
	}

	return true;
}

function isIE6()
{
	var agt = navigator.userAgent.toLowerCase();
	var is_major = parseInt(navigator.appVersion);
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	var is_ie6 = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );
	return is_ie6;
}

function confirmDelete(message)
{
	var question = 'Вы намерены удалить запись';
	if (message) {
		question += ':\n[' + message + ']';
	}
	question += '\nВы уверены?';
	return confirm(question);
}


function toggleLogin() {

	divLogin = $('header-login');
	if (divLogin.style.display == 'block') {
		divLogin.style.display = 'none';
		$('header-recovery').style.display = 'none';
		$('header-recovery-bg').style.display = 'none';
		$('header-menu2').style.display = 'block';
		$('header-menu2-bg').style.display = 'block';
	} else {
		$('header-menu2').style.display = 'none';
		$('header-menu2-bg').style.display = 'none';
		divLogin.style.display = 'block';
	}
	return false;
}
function toggleRecovery() {

	divRecovery = $('header-recovery');
	if (divRecovery.style.display == 'block') {
		divRecovery.style.display = 'none';
		$('header-recovery-bg').style.display = 'none';
	} else {
		$('header-recovery-bg').style.display = 'block';
		divRecovery.style.display = 'block';
	}
	return false;
}


function trMouseOver(trElement)
{
	$(trElement).addClassName('hovered');
}
var clicked = new Array();
function trClick(trElement)
{

	if (!clicked[$(trElement).rowIndex]) {
		$(trElement).addClassName('hovered');
		clicked[$(trElement).rowIndex] = true;
	} else {
		$(trElement).removeClassName('hovered');
		clicked[$(trElement).rowIndex] = false;
	}
}
function trMouseOut(trElement)
{
	if (!clicked[$(trElement).rowIndex]) {
		$(trElement).removeClassName('hovered');
	}
}




var printableVersion = false;
function printableVersionShow()
{
	itemsToHide = $$('.print-version-hidden');
	for (i = 0; i < itemsToHide.length; i++) {
		itemsToHide[i].addClassName('print-version-hide');
	}

	itemsToShow = $$('.print-version-visible');
	for (i = 0; i < itemsToShow.length; i++) {
		itemsToShow[i].addClassName('print-version-unhide');
	}

	$$('body')[0].style.backgroundColor = '#fff';
}
function printableVersionHide()
{
	itemsToHide = $$('.print-version-visible');
	for (i = 0; i < itemsToHide.length; i++) {
		itemsToHide[i].removeClassName('print-version-unhide');
	}

	itemsToShow = $$('.print-version-hidden');
	for (i = 0; i < itemsToShow.length; i++) {
		itemsToShow[i].removeClassName('print-version-hide');
	}

	$$('body')[0].style.backgroundColor = '#111a21';
}
function togglePrint()
{
	if (printableVersion == false) {
		printableVersion = true;
		printableVersionShow();
	} else {
		printableVersion = false;
		printableVersionHide();
	}

}


function popupWindow(wndURL,wndWidth,wndHeight)
{
    if (document.all) var xMax = screen.width, yMax = screen.height;
    else
        if (document.layers) var xMax = window.outerWidth, yMax = window.outerHeight;
        else var xMax = 640, yMax=480;

    var xOffset = (xMax - wndWidth)/2, yOffset = (yMax - wndHeight)/2;

    window.open(wndURL,'','width='+wndWidth+',height='+wndHeight+',screenX='+xOffset+',screenY='+yOffset+',top='+yOffset+',left='+xOffset+',copyhistory=no,directories=no, menubar=no,location=no,scrollbars=yes,resizable=yes');
}

