$(document).ready(function() {
	$('#add_fav').click(function(){
		if (window.sidebar)
		{
			window.sidebar.addPanel(document.title, window.location.href, "");
		}
		else if( window.opera && window.print )
		{
			var mbm = document.createElement("a");
			mbm.setAttribute("rel","sidebar");
			mbm.setAttribute("href",window.location.href);
			mbm.setAttribute("title",document.title);
			mbm.click();
		}
		else if( document.all )
		{
			window.external.AddFavorite( window.location.href, document.title);
		}
		
		return false;
	});
});

function getCookie(c_name) {
   if (document.cookie.length>0) {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1) {
         c_start=c_start + c_name.length+1;
         c_end=document.cookie.indexOf(";",c_start);
         if (c_end==-1) c_end=document.cookie.length;
         return unescape(document.cookie.substring(c_start,c_end));
      }
   }
   return "";
}

function setCookie(c_name,value,expiredays)
{
   var exdate=new Date();
   exdate.setDate(exdate.getDate()+expiredays);
   document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function toggleIzd() {
	   var izdBlock = document.getElementById('izdBlock');
	   var izdImage = document.getElementById('izdImage');
	   var izdLink  = document.getElementById('izdLink');

	   if (izdBlock.style.display == 'none') {
	      izdBlock.style.display  = 'block';
	      izdImage.src  = url + 'templates/' + template + '/static/images/izd_toggle_off.gif';
	      izdImage.alt  = 'Свернуть';
	      izdLink.title = 'Свернуть издание';
	      izdanie_cookie = getCookie('izdanie_cookie');
	      setCookie('izdanie_cookie', 1, 365);
	   } else {
	      izdBlock.style.display = 'none';
	      izdImage.src = url + 'templates/' + template + '/static/images/izd_toggle_on.gif';
	      izdImage.alt  = 'Развернуть';
	      izdLink.title = 'Развернуть издание';
	      setCookie('izdanie_cookie', 0, 365);
	   }
}

function showLegend() {
   legend = document.getElementById('legend_layer');
   legtxt = document.getElementById('legend_text');
   if (legend.style.display == 'none') {
      legend.style.display  = 'block';
      legend_cookie         = getCookie('legend_cookie');
      setCookie('legend_cookie', 1, 365);
      legend_text.innerHTML = 'Скрыть легенду';
   } else {
      legend.style.display = 'none';
      setCookie('legend_cookie', 0, 365);
      legend_text.innerHTML = 'Показать легенду';
   }
}

function sform(show, id, keyword) {
	el = document.getElementById(id);
	if (show == 1) {
		if (el.value == keyword) {
			el.value = '';
		}
	} else {
		if (el.value == '') {
			el.value = keyword;
		}
	}
}

function changeBack(id,newimg)
{
	document.getElementById(id).style.backgroundImage = 'url("' + newimg + '")';
}

function changeImage(id,newimg)
{
	document.getElementById(id).src = newimg;
}

function strlen(stVar)
{
	return(stVar.length);
}

var load = '<div style="height: 185px;"><p align="center"><img src="' + url + 'templates/' + template + '/static/images/ajax-loader-1.gif" align="absmiddle" alt="Загрузка ..." border="0" /></p></div>';
function loading (name)
{
	div = document.getElementById(name).innerHTML;
	if (div != load) {
		document.getElementById(name).innerHTML = load;
	}
}

function show_quote() {
	wait_message = '<img src="' + url + 'templates/' + template + '/static/images/wheel_small.gif" width="16" height="16" alt="Загрузка ..." />';
	document.getElementById('quote_wheel').innerHTML = wait_message;
	xajax_refresh_quote();
}

function quote_after() {
	// new Effect.Appear('quote_text');
	// new Effect.Appear('quote_stuff');
   new Effect.Opacity('top_qoute', {duration:2.0, from:0, to:1});
}

var born  = new Date();
unixtime *= 1000; // в JS unixtime в ms, а в php в секундах, компенсируем разницу.
born.setTime(unixtime);
var minutes = born.getMinutes();
var hours   = born.getHours();
var seconds = born.getSeconds()


function market_menu() {
	var market_menu_div = document.getElementById('market_submenu').style.display;
	var market_div      = document.getElementById('market').style.display;
	if (market_menu_div == 'none') {
		document.getElementById('market').style.display = 'none';
		document.getElementById('market_submenu').style.display = 'block';
		initFade("market_submenu");
	} else {
		document.getElementById('market_submenu').style.display = 'none';
		document.getElementById('market').style.display = 'block';
	}
}

function initFade(el) {
	testObj = document.getElementById(el);
	for (var i=0;i<11;i++)
		setTimeout('setOpacity('+i+')',100*i);
	return false;
}

function setOpacity(value)
{
	testObj.style.opacity = value/10;
	testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

function check_button(button_id)
{
	el  = document.getElementById(button_id);

	if (el.checked == true) {
		document.getElementById('submit').disabled = false;
	} else {
		document.getElementById('submit').disabled = true;
	}
}

function refresh_captcha()
{
	rand_ints = Math.random() * 10000000000000000000;
	document.getElementById('captcha_img').src = url + 'captcha/' + rand_ints;
}

function process_register()
{
	document.getElementById('spinning_wheel').innerHTML = '<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />';
	document.getElementById('submit').disabled = true;
	document.getElementById('submit').value    = 'Пожалуйста, подождите ...';
	xajax_regme(xajax.getFormValues('regform'));
}

function chat_check_count( obj ) {
	if ( (1400 - jQuery(obj).val().length) > 0 ) {
		jQuery("#mes_count").text(1400 - jQuery(obj).val().length);
	} else {
               jQuery("#mes_count").html("<b><font color='red'>Максимальное количество символов на 1 сообщение не более 1400</font></b>");
               jQuery(obj).val(jQuery(obj).val().substring(0,1400));
	}
}
function chat_check_enter(event)
{
	//Ctrl + Enter
	if (event.ctrlKey && (event.keyCode == 0xA  || event.keyCode == 0xD))
	{
		chat_mes_send();
	}
	
}

function chat_login()
{
	$('login_spinning_wheel').html('<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />');
	$('login_submit').attr('disabled', 'disabled').val('Пожалуйста, подождите ...');
	xajax_chat_login(xajax.getFormValues('login_form'));
}

function chat_register()
{
	$('spinning_wheel').html('<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />');
	$('submit').attr('disabled', 'disabled').val('Пожалуйста, подождите ...');
	xajax_chat_reg(xajax.getFormValues('regform'));
}

function chat_set_tab(id)
{
	chat_select_tab(id);
	xajax_chat_load(id);
}

var reload_history = true;
var reload_history_timer = null;
function chat_select_tab(id)
{
	if (reload_history) // Первый раз вызываем и ставим таймер, второй раз снимаем.
	{
		reload_history = false;
		reload_history_timer = setInterval('xajax_chat_load(' + id + ')', 1000);
	}
	else
	{
		clearInterval(reload_history_timer);
	}
	
	chat_blink_tab_stop(id);
	$('.chat_tabs').css('font-weight', '');
	$('#chat_tabs_' + id).css('font-weight', 'bold');
}

var blinking = {};
function chat_blink_tab_start(id)
{
	if (blinking[id] || $('#chat_tabs_' + id).length == 0)
	{
		return;
	}
	
	blinking[id] = setInterval('chat_blink_tab(' + id + ')', 500);
}

function chat_blink_tab(id)
{
	var blinkOn = !($('#chat_tabs_' + id)[0].blink);

	$('#chat_tabs_' + id).toggleClass('chat_tabs_blink', blinkOn);
	$('#chat_tabs_' + id)[0].blink = blinkOn;
}

function chat_blink_tab_stop(id)
{
	$('#chat_tabs_' + id).removeClass('chat_tabs_blink');
	clearInterval(blinking[id]);
	delete blinking[id];
}

function chat_personal(id, login)
{
	chat_personal_tab(id, login);
	chat_set_tab(id);
	$('#mes_text').focus();
}

function chat_personal_tab(id, login)
{
	if ( $('#chat_tabs_' + id).length )
	{
		return;
	}
	
	var elm = $('#chat_tabs_new')[0].innerHTML;
	elm = elm.replace(/-0/g, id);
	elm = $(elm);
	elm.val(login);
	elm.hide();
	$('#chat_tabs_new').parent().append(elm);
	elm.wrap('<div style="float: left" class="chat_tab_del"></div>');
	elm.show();
	chat_blink_tab_start(id);
}

function chat_tab_clear()
{
	$('.chat_tab_del').remove();
}

function chat_quote(login)
{
	if ($('#mes_text').length = 0)
	{
		return;
	}
	
	var tmp = $('#mes_text').val() + '[' + login + '], ';
	$('#mes_text').val(tmp);
	$('#mes_text').focus();
}

function chat_abuse(id)
{
	xajax_chat_abuse(id);
}

function chat_pre_ban(elm, id)
{
	var pos = $(elm).position();
	
	pos.left += $(elm).width() - $('#ban_block').width();
	pos.top += $(elm).height() - $('#ban_block').height();
	$('#ban_id').val(id);
	$('#ban_time').val('');
	$('#ban_block').css('left', pos.left);
	$('#ban_block').css('top', pos.top);
	$('#ban_block').show();
}

function chat_close_ban()
{
	$('#ban_block').hide();
}

function chat_ban()
{
	var ban_type, ban_time, ban_id;
	
	ban_type = $('#ban_form :radio:checked').val();
	ban_time = $('#ban_time').val();
	ban_id   = $('#ban_id').val();
	$('#ban_block').hide();
	
	xajax_chat_ban(ban_id, ban_type, ban_time);
}

function chat_del(id)
{
	if (!confirm('Серьёзно?'))
	{
		return;
	}

	xajax_chat_del(id);
}

var chat_timer_ban, chat_timer_last;
function chat_count_ban(setNum)
{
	var timerDiff = 1;
	if (new Date().getTime() - chat_timer_last < timerDiff * 1000)
	{
		return;
	}
	
	var num = parseInt( $('#ban_time').text() );
	
	if (!chat_timer_ban)
	{
		num = setNum;
	}
	
	clearInterval(chat_timer_ban);
	if (num > 0)
	{
		num -= timerDiff;
		if (num < 0)
		{
			num = 0;
		}
		
		$('#ban_time').text(num);
		chat_timer_ban = setInterval(chat_count_ban, timerDiff * 1000);
		chat_timer_last = new Date().getTime();
	}
}

var chat_timer;
function chat_mes_send()
{
	var data = {};

	data.text = $('#mes_text').val();
	if (data.text == '')
	{
		alert('Укажите текст!');
		$('#mes_text').focus();

		return;
	}

	if (data.text.length > max_symbol)
	{
		alert('Максимальная длина сообщения ' + max_symbol + '!' + "\n" + 'Введено: ' + data.text.length);
		$('#mes_text').focus();

		return;
	}

	var ban_time = parseInt( $('#ban_time').text() );
	if ($('#ban_time_container').css('visibility') == 'visible' && ban_time > 0)
	{
		alert('Погодите ещё ' + ban_time + 'сек.!');

		return;
	}

	data.captcha = '';
	if ($('#captcha_container').css('display') != 'none')
	{
		data.captcha = $('#mes_captcha').val();
		if (data.captcha == '')
		{
			alert('Укажите код!');
			$('#mes_captcha').focus();

			return;
		}
	}

	clearTimeout(chat_timer);
	$('#mes_submit').attr('disabled', 'disabled').val('Отправляю ...');
	xajax_chat_mes_send(data);
}

function chat_subscribe(user_id, author_id) {
	xajax_chat_subscribe(user_id, author_id);
}

var chat_do_scroll = true;
function chat_scroll_check()
{
	var pos = $("#history_layer")[0].scrollHeight 
			- $("#history_layer").height()
			- $("#history_layer").scrollTop();
	if (pos < 30)
	{
		chat_do_scroll = true;
	}
}


function chat_scroll()
{
	if (chat_do_scroll)
	{
		$("#history_layer").scrollTop( $("#history_layer")[0].scrollHeight - $("#history_layer").height() );
		chat_do_scroll = false;
	}
}

function process_pass()
{
	document.getElementById('rec_spinning_wheel').innerHTML = '<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />';
	document.getElementById('rec_submit').disabled = true;
	document.getElementById('rec_submit').value    = 'Пожалуйста, подождите ...';
	xajax_forget_pass(xajax.getFormValues('recoverform'));
}

function process_resend()
{
	document.getElementById('res_spinning_wheel').innerHTML = '<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />';
	document.getElementById('res_submit').disabled = true;
	document.getElementById('res_submit').value    = 'Пожалуйста, подождите ...';
	xajax_resend_letter(xajax.getFormValues('resendform'));
}

function process_login()
{
	document.getElementById('login_spinning_wheel').innerHTML = '<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />';
	document.getElementById('login_submit').disabled = true;
	document.getElementById('login_submit').value    = 'Пожалуйста, подождите ...';
	xajax_login(xajax.getFormValues('loginform'));
}

function process_small_login()
{
	document.getElementById('login_spinning_wheel').innerHTML = '<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />';
	document.getElementById('login_submit').disabled = true;
	//document.getElementById('login_submit').value    = 'Пожалуйста, подождите ...';
	xajax_login(xajax.getFormValues('loginform_'), 'small');
}

function process_myprofile()
{
	document.getElementById('spinning_wheel').innerHTML = '<img src="' + url + 'templates/' + template + '/static/images/spinning_wheel_throbber.gif" border="0" width="32" height="32" alt="Идёт загрузка" />';
	document.getElementById('submit').disabled = true;
	document.getElementById('submit').value    = 'Пожалуйста, подождите ...';
	xajax_myprofile(xajax.getFormValues('myprofileform'));
}

function resend_activation()
{
	react = document.getElementById('resend_activation_layer');
	if (react.style.display == 'none') {
		react.style.display = 'block';
	} else {
		react.style.display = 'none';
	}
}


var intervalcheg;
function refresh_analititcs_block(mseconds)
{
	if (intervalcheg != mseconds) {
		clearInterval(intervalcheg);
		intervalcheg = setInterval("makeLoad()", mseconds);
	} else {
		intervalcheg = setInterval("makeLoad()", mseconds);
	}
}

function makeLoad()
{
	//loading('our_analitics');

   // var el = $("our_analitics");
   // el.setOpacity(0.0);
   xajax_updatean('');
   // new Effect.Opacity(el, {duration:3.0, from:0.0, to:1.0});
}

function get_ed_text(editor_name)
{
    var oEditor = FCKeditorAPI.GetInstance(editor_name) ;
    if (oEditor.EditorDocument.body.innerHTML) {
        // Uncomment the following line for a proper XHTML return
        // return oEditor.GetXHTML();
        return oEditor.EditorDocument.body.innerHTML;
    }
    else return '';
}

function check_add_art_form()
{

	text   = get_ed_text("text");
	title  = document.getElementById('art_title').value;
	errors = 0;
	if (strlen(title) == 0) {
		alert("Вы забыли ввести заголовок для Вашей статьи!\nСделайте это, пожалуйста, после чего добавьте свою статью.");
		errors++;
	}

	if (strlen(title) > 0 && strlen(title) < 5) {
		alert("Вы ввели слишком короткий заголовок статьи!\nОн не может быть короче пяти символов.\nИсправьте его, после чего добавьте свою статью.");
		errors++;
	}

	if (strlen(text) == 0) {
		alert("Вы забыли ввести содержимое для Вашей статьи!\nСделайте это, пожалуйста, после чего добавьте свою статью.");
	}

	if (strlen(text) > 0 && strlen(text) < 50) {
		alert("Вы пытаетесь опубликовать не особо информативную заметку.\nКоличество символов в ней не может быть менее 50(вместе с оформлением)!\nИсправьте текст, после чего добавьте свою статью.");
		errors++;
	}

	if (errors == 0) {
		document.getElementById('art_form').submit();
	}
}

function layerShow(id)
{
	el = document.getElementById(id);
	if (el.style.display == 'none') {
		el.style.display = 'block';
	} else {
		el.style.display = 'none';
	}
}

function redirect_with_timeout(seconds, to)
{
	seconds = seconds * 1000;
	setTimeout('redirect("' + to + '")',seconds);
}

function redirect(to)
{
	window.location.href = to;
}

function editor_loaded()
{
	document.getElementById('editor_loaded').innerHTML = '';
}

function rollOver(div_id, way)
{

	var divObj= document.getElementById( div_id ); if ( !divObj );
	divObj.style.backgroundPosition= ( way ) ? "0% 100%" : "0% 0%";

}



function check_updatean()
{
   var divObj = document.getElementById( 'our_analitics' );
   var divObjTemp = document.getElementById( 'our_analitics_temp' );

   if (divObj.innerHTML == divObjTemp.innerHTML) return;

   new Effect.Opacity(divObj, {duration:0.0, to:0.0});
   window.setTimeout("copyDivAn()", 500);
}

function copyDivAn()
{
   var divObj = document.getElementById( 'our_analitics' );
   var divObjTemp = document.getElementById( 'our_analitics_temp' );

   divObj.innerHTML = divObjTemp.innerHTML;
   new Effect.Opacity(divObj, {duration:3.0, from:0.0, to:1.0});
}



function nav_block(p)
{
	new Ajax.Request('http://' + (uri.indexOf('//www.') != -1 ? 'www.' : '' ) + 'forexaw.com/components/partner_ban/index.php?p='+p+'&'+Math.random(),
  {
    method:'get',
    onSuccess: function(transport){
      var response = transport.responseText || "";
      if (response == "") {
         return;
      }

      var el = $("partner_ban");
      el.setOpacity(0.0);
      el.update(response);
      new Effect.Opacity(el, {duration:3.0, from:0.0, to:1.0});
    },
    onFailure: function(){ }
  });
}


function doTermSearch()
{
	var text = $('#termSearchText').val();

	if (text == '')
	{
		alert('Введите текст');
		return;
	}

	$('#loading_find').css('visibility', 'visible');
	xajax_termSearch(text);
}


function doNewsSearch()
{
	var text = $('#newsSearchText').val();

	if (text == '')
	{
		alert('Введите текст');
		return;
	}

	$('#loading_find').css('visibility', 'visible');
	xajax_newsSearch(text);
}


function adjustImgWidth()
{
	var curW = $('#col_wrapper').width();
	var difW = $('#content_wrap').get(0).scrollWidth - $('#content_wrap').width();

	$('#col_wrapper').css('minWidth', curW + difW);
}

