function countDown(i)
{
	if (i < 0) {
		return true;
	}

	document.getElementById('counterSpan').innerHTML = '' + i;

	i--;

	timerId = window.setTimeout('countDown(' + i + ')', 1000);
}


function submitFrameLoad()
{
	if ($('ajax-loader')) {
		Element.remove('ajax-loader');
		document.onkeypress = function() {return true;}
	}

	/* As Safari caches request to iframe (it causes application error after F5) we have to change iframe window name on each page load,
	so we should detect current window name first. */
	var submitFrameName = $$('iframe.submit-frame')[0].name;

	var json = frames[submitFrameName].document.body.innerHTML;
	if (frames[submitFrameName].location != 'about:blank') {
		frames[submitFrameName].location.replace('about:blank');
	}

	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 && !($('add-more') && $F('add-more') == 1)) {
		document.location.href = response.redirect_path;
		return;
	}

	statusLine = $('status-line');
	statusLine.innerHTML = tmptext;
	statusLine.style.display = 'block';
	statusLine.addClassName('highlight');
	setTimeout('smoothShow("status-line")', 2000);

	if (!Prototype.Browser.Opera && Element.viewportOffset(statusLine)['top'] < 0) {
		Element.scrollTo(statusLine.parentNode);
	}

	return true;
}

function smoothShow(divId, maxHeight)
{
	$(divId).removeClassName('highlight');
}


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 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 isIE7()
{
	var agt = navigator.userAgent.toLowerCase();
	var is_major = parseInt(navigator.appVersion);
	var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
	var is_ie7 = (is_ie && (is_major == 4) && (agt.indexOf("msie 7.")!=-1) );
	return is_ie7;
}

var ie6 = isIE6();
var ie7 = isIE7();

function showFatalError(text)
{
	document.onkeypress = function(event) { return disableOnKeyPress(event) };

	var body = $$('body')[0];

	var fatalErrorBox = document.createElement('DIV');
	windowHeight = getWindowHeight();

	fatalErrorBox.style.height = windowHeight + 'px';
	if (isIE6()) fatalErrorBox.style.width = getWindowWidth() + '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.innerHTML = text;

	fatalErrorBox.appendChild(fatalErrorBoxMsg);
	body.appendChild(fatalErrorBox);

	fatalErrorHeight = Element.cumulativeOffset(fatalErrorBoxMsg).top * 2 + fatalErrorBoxMsg.clientHeight + 2;
	fatalErrorHeight = fatalErrorHeight > windowHeight ? fatalErrorHeight : windowHeight;
	fatalErrorHeight = fatalErrorHeight > body.clientHeight ? fatalErrorHeight : body.clientHeight;

	fatalErrorBox.style.height = fatalErrorHeight + 'px';
}


function getWindowHeight()
{
	if (window.innerHeight) {
		theHeight = window.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		theHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		theHeight = document.body.clientHeight;
	} else {
		theHeight = false;
	}
	return theHeight;
}

function getWindowWidth()
{
	if (window.innerWidth) {
		theWidth = window.innerWidth;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		theWidth = document.documentElement.clientWidth;
	} else if (document.body) {
		theWidth = document.body.clientWidth;
	} else {
		theWidth = false;
	}
	return theWidth;
}


/**
 * функции для работы с AjaxLoader-ом (отобразить/скрыть)
 *
 */
/*function _showAjaxLoader()
{
	var body = $$('body')[0];
	var ajaxLoader = $('ajax-loader');
	var ajaxLoaderBody = $('ajax-loader-body');

	windowHeight = getWindowHeight();

	ajaxLoader.style.height = windowHeight + 'px';
	if (isIE6()) ajaxLoader.style.width = getWindowWidth() + 'px';

	ajaxLoaderHeight = Element.cumulativeOffset(ajaxLoaderBody).top * 2 + ajaxLoaderBody.clientHeight + 2;
	ajaxLoaderHeight = ajaxLoaderHeight > windowHeight ? ajaxLoaderHeight : windowHeight;
	ajaxLoaderHeight = ajaxLoaderHeight > body.clientHeight ? ajaxLoaderHeight : body.clientHeight;

	ajaxLoader.style.height = ajaxLoaderHeight + 'px';

	ajaxLoader.addClassName('block-visible');
	ajaxLoader.removeClassName('block-hidden');
}
function _hideAjaxLoader()
{
	var ajaxLoader = $('ajax-loader');
	ajaxLoader.addClassName('block-hidden');
	ajaxLoader.removeClassName('block-visible');
}
*/

function selectTag(linkElement)
{
	var tagName = linkElement.getAttribute('rel');
	var tagContainer = $('tag-container');
	var tagContainerValue = tagContainer.value;
	if (tagContainerValue.match(tagName) == null) {
		tagContainerValue += ', ' + tagName + ', ';
	}
	tagContainerValue = tagContainerValue.replace(/\,+ *\,+/, ', ').replace(/^ *\,* */, '').replace(/ +/, ' ');
	tagContainer.value = tagContainerValue;

	highlightTag(tagContainer);
}

function searchTags(searchLink)
{
	var inputText = tinyMCE.get('news-text').getContent();
	$(searchLink).addClassName('hidden-inline');
	$('ajax-loader-tags').addClassName('visible-inline');


	new Ajax.Request('/admin/anews/searchtags.html', {
		parameters: $H({'text': inputText}).toQueryString(),
		onSuccess: function(transport, json) {
			$('tag-list').innerHTML = transport.responseText;
			$('ajax-loader-tags').removeClassName('visible-inline');
			$(searchLink).removeClassName('hidden-inline');
			highlightTag($('tag-container'));
		},
  		onFailure: function() {
  			alert('Ошибка! Невозможно отправить комментарий. Проверьте ваше Internet соединение');
			$('ajax-loader-tags').removeClassName('visible-inline');
			$(searchLink).removeClassName('hidden-inline');
  		}
	});

	return false;

}

function highlightTag(textareaElement)
{
	var tags = textareaElement.value.split(",");
	var tagLinks = $$('a.select-tag');


	for	(i = 0; i < tagLinks.length; i++) {
		tagCurrent = tagLinks[i].getAttribute('rel');
		tagLinks[i].removeClassName('highlight');
		for	(j = 0; j < tags.length; j++) {
			if (tagCurrent == tags[j].strip()) {
				tagLinks[i].addClassName('highlight');
			}
		}
	}

}


var windowDimensions = function() {
	var viewportDimensions = document.viewport.getDimensions();
	var bodyDimensions = $$('body')[0].getDimensions();
	var result = {};

	result[0] = result.width = viewportDimensions.width > bodyDimensions.width ? viewportDimensions.width : bodyDimensions.width;
	result[1] = result.height = viewportDimensions.height > bodyDimensions.height ? viewportDimensions.height : bodyDimensions.height;

	return result;
}

var registerShow = function() {
	registerRefresh();

	new Effect.Parallel([
		new Effect.Appear($('blocker'), {from: 0, to: 0.7, sync: true}),
		new Effect.BlindDown($('register'), {sync: true})
	], {
		duration: 0.4,
		queue: {scope: 'registerForm', position: 'end'}
	});
}

var registerRefresh = function() {
	var d = windowDimensions();
	$('blocker').setStyle({width: d[0] + 'px', height: d[1] + 'px'});
	$('register').setStyle({left: $('main').cumulativeOffset().left - 30 + 'px'});
}

var registerHide = function() {
	new Effect.Parallel([
		new Effect.Fade($('blocker'), {sync: true}),
		new Effect.BlindUp($('register'), {sync: true})
	], {
		duration: 0.4,
		queue: {scope: 'registerForm', position: 'end'}
	});
}

var changeCaptcha = function(element) {
	var el = $(element);
	var image = (el.hasClassName('captcha') && el.src) ? el : el.down('img.captcha');
	image.src = '/register/getcaptcha.html?' + Math.random();
}


/*
var e = Prototype.emptyFunction;
var divConsole;

if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) {
	e = console.log;
} else {
	divConsole = new Element('div', {className: 'console', style: 'position: fixed; top: 300px; left: 300px; width: 400px; height: 400px; background-color: #000; color: #fff; max-height: 200px; overflow-y: auto;'}).update(new Element('p'));
//	divConsole.setOpacity(0.7);


	e = function() {
		if (!divConsole.up(0)) {
//			$$('body')[0].appendChild(divConsole);
		}

//		divConsole.update(null);
		for (var i = 0; i < arguments.length; i++) {
//			var p = new Element('p');
//			if (arguments[i].inspect) {
//				p.update(arguments[i].inspect());
//			} else if (arguments[i].toString) {
//				p.update(arguments[i].toString());
//			} else {
//				p.update(arguments[i]);
//			}
			alert(arguments[i]);
//			divConsole.insert({top: p});
		}
	}

}
*/
