

var change_add = false;
/* comments */
function post_new_comment(type)
{
	comment_cont = $("#content").val();
	if (comment_cont.length == 0)
	{
		alert('Введите, пожалуйста, комментарий.');
		return false;
	}
	$("#add_form").hide();
	$("#loading_add_comment").fadeIn("fast");
	$.post("./ajax.php",
	{
		act: 'post_comment',
		type: type,
		block_id: block_id,
		last_comment: last_comment_id,
		comment_cont: comment_cont
	},
	function(data)
	{
		data = eval('(' + data + ')');
		if (data.err)
		{
			alert(data.err);
			$("#loading_add_comment").hide();
			$("#add_form").show();
		}
		else
		{
			$("#total_comments").html(data.total);
			$("#comments_td").append(data.comments);
			$("#loading_add_comment").hide();
			$("#comment_added").fadeIn("fast");
			$("#content").val("");
			new_url = (location.href.indexOf('#') != -1) ? location.href.substring(0,location.href.indexOf('#')) : location.href;
			location.replace(new_url + "#cmt" + (parseInt(last_comment_id) + 1));
		}
	}
	);
	return false;
}
function load_cmnts_by_pg(type, pg_num, link)
{
	if(typeof link == "undefined") link = true;
	$("#comments_td").hide();
	$("#loading_comments").fadeIn("fast");
	$(".pages_td").empty();
	$.post("./ajax.php",
	{
		act: 'show_comments_by_page',
		type: type,
		block_id: block_id,
		com_pg: pg_num
	},
	function(data)
	{
		data = eval('(' + data + ')');
		if(parseInt(data.total) == 0 && change_add ) {
			$("#pages_td_top").html('');
			$("#pages_td_bottom").html('');
		}
		else if (parseInt(data.total) > 25 || change_add)
		{
			$("#pages_td_top").html(data.pages);
			$("#pages_td_bottom").html(data.pages);
		}
		else
			$("#pages_td_bottom").html(data.pages);
		
		$("#total_comments").html(data.total);
		$("#comments_td").html(data.comments);
		last_comment_id = data.last_comment_id;
		$("#loading_comments").hide();
		$("#comments_td").show();
		if ($("#add_form").css("display") == "none")
		{
			$("#add_comm_lnk").show();
			$("#add_comm_img").show();
			$("#comment_added").hide();
		}
		if(link)
		{
			new_url = (location.href.indexOf('#') != -1) ? location.href.substring(0,location.href.indexOf('#')) : location.href;
			location.replace(new_url + "#comments");
		}
		if(change_add)
		{
			if(data.can_add == 0) {
				$("#add_comm_lnk").hide();
				$("#add_comm_img").hide();
				$('#add_form').hide();
			}
			else if( $("#add_form:hidden").length )
				$("#add_comm_lnk").show();
		}
	}
	);
	return false;
}
function anchor_clk(num)
{
	$('#add_form').show();
	$('#add_comm_lnk').hide();
	cont = $('#content').val();
	if (cont != "")
	cont = cont + '\n';
	cont = cont + '#' + num + ', ';
	$('#content').val(cont).focus();
	return false;
}
function add_comment()
{
	$('#add_form').fadeIn('normal');
	$('#add_comm_lnk').hide();
	$('#content').focus();
	return false;
}
function chk_snd(event, chk_frm){
  if ((event.keyCode==13) && (event.ctrlKey))
  { 
    chk_frm_name = chk_frm.form.name;
    if(document.forms[chk_frm_name].onsubmit()) document.forms[chk_frm_name].submit(); 
  }
}
function do_refresh_pg(type)
{
	$("#comments_td").hide();
	$("#loading_comments").fadeIn("fast");

	$.post("./ajax.php",
	{
		act: 'refresh_comments_pg',
		type: type,
		block_id: block_id
	},
	function(data)
	{
		data = eval('(' + data + ')');
		if (parseInt(data.total) > 25)
		{
			$("#pages_td_top").html(data.pages);
		}
		$("#pages_td_bottom").html(data.pages);
		$("#total_comments").html(data.total);
		$("#comments_td").html(data.comments);
		last_comment_id = data.last_comment_id;
		$("#loading_comments").hide();
		$("#comments_td").show();
		last_comment_id = parseInt(data.last_comment_id);
		if ($("#add_form").css("display") == "none")
		{
			$("#add_comm_lnk").show();
			$("#comment_added").hide();
		}
		new_url = (location.href.indexOf('#') != -1) ? location.href.substring(0,location.href.indexOf('#')) : location.href;
		location.replace(new_url + "#cmt" + (last_comment_id));
		setTimeout("$('.refresh_pg').fadeIn('slow');",3000);
		if(change_add)
		{
			if(data.can_add == 0) {
				$("#add_comm_lnk").hide();
				$('#add_form').hide();
			}
			else 
				$("#add_comm_lnk").show();
		}
	}
	);
	return false;
}

/* blocks functions */
function fixDate (date)
{
	var base = new Date(0);
	var skew = base.getTime ();
	if (skew > 0) date.setTime (date.getTime() - skew);
}
/* Функция установки cookie  - на год */
function setCookie (name, value, expires, path, domain, secure)
{
	if (!expires) {
		expires = new Date ();
		fixDate (expires);
		expires.setTime (expires.getTime() + 365 * 24 * 60 * 60 * 1000);
	}

	var curCookie = name + "=" + escape (value) + "; expires=" + expires.toGMTString () +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");

	document.cookie = curCookie;
}
/* Функция для развертывания и свертывания блока */
function block_action (block_name)
{
	var block = document.getElementById (block_name);
	if (block)
	{
		var block_btn = document.getElementById (block_name + "_btn");
		var btn_src = block_btn.src;
		var src_part = btn_src.substr (0, btn_src.length - 5);
		if (block.style.display == "block") {
			$('#'+block_name).slideUp('normal');
			block_btn.src = src_part + "0.gif";
			block_btn.alt = expand;
			setCookie (block_name, "0");
		}
		else {
			$('#'+block_name).slideDown('normal');
			block.style.display = "block";
			block_btn.src = src_part + "1.gif";
			block_btn.alt = collapse;
			setCookie (block_name, "1");
		}
	}
}

/* some trsh // need to remake */
function div_visible (flag)
{
  if (flag == 1)
        document.getElementById("add_form").style.display = "block"
  else
   if (flag == 2)
            document.getElementById("add_form").style.display = "none"
   else
     if (document.getElementById("content").value != "")
              document.getElementById("add_form").style.display = "none";
}
function div_visible1 (flag)
{
  if (flag == 1)
        document.getElementById("add_form").style.display = "block"
  else
   if (flag == 2)
            document.getElementById("add_form").style.display = "none"
   else
     if (document.getElementById("id_username").value != "" && document.getElementById("content").value != "")
              document.getElementById("add_form").style.display = "none";
}

function getCityList (flag)
{
  var objSel = document.getElementById("coutryList");
  varSelect = objSel.options[objSel.selectedIndex].value;

 if (flag == "") return;

 if (flag == '0')
  {
      if (varSelect != 68) {
         document.getElementById("divCity1").style.display = "none";
         document.getElementById("divCity2").style.display = "block";
      }
      else {
         document.getElementById("divCity1").style.display = "block";
         document.getElementById("divCity2").style.display = "none";
      }
  }
  else if (flag == '1')
  {
      if (varSelect != 68) {
         document.getElementById("city1").style.display = "none";
      }
      else {
        document.getElementById("city1").style.display = "block";
      }
  }
  else if (flag == '2')
  {
      if (varSelect != 68) {
         document.getElementById("city_name").style.display = "none";
         document.getElementById("city1").style.display = "none";
      }
      else {
        document.getElementById("city1").style.display = "block";
        document.getElementById("city_name").style.display = "block";
      }
  }
}
function disband_visible (flag)
{
  if (flag == 1)
  {
     document.getElementById("disbandID").style.display = "block"
     document.getElementById("transferID").style.display = "none"
     document.getElementById("topaddmemID").style.display = "none";
     document.getElementById("toptransID").style.display = "none";
  }
  else
   if (flag == 2)
        document.getElementById("disbandID").style.display = "none"
   else
     if (document.getElementById("passwdID").value != "" && document.getElementById("security_codeID").value != "")
          document.getElementById("disbandID").style.display = "none";
}

function transfer_visible (flag)
{
  if (flag == 1)
  {
      document.getElementById("transferID").style.display = "block"
      document.getElementById("disbandID").style.display = "none"
  }
  else
   if (flag == 2)
      document.getElementById("transferID").style.display = "none"
}
function toptrans_visible (flag)
{
    if (flag == 1)
    {
        document.getElementById("toptransID").style.display = "block";
        document.getElementById("disbandID").style.display = "none";
        document.getElementById("topaddmemID").style.display = "none";
    }
    else {
        if (flag == 2) document.getElementById("toptransID").style.display = "none";
    }
}
function ban_visible (flag)
{
  if (flag == 1)
  {
     document.getElementById("id2").style.display = "block"
     document.getElementById("id3").style.display = "none"
     document.getElementById("flag").value = "1"
  }
  else
  if (flag == 2)
  {
     document.getElementById("id2").style.display = "none"
     document.getElementById("id3").style.display = "block"
     document.getElementById("flag").value = "2"
  }
  else
  if (flag == 3)
  {
     document.getElementById("id2").style.display = "none"
     document.getElementById("id3").style.display = "none"
     document.getElementById("flag").value = "0"
  }
}
function topaddmem_visible (flag)
{
    if (flag == 1)
    {
        document.getElementById("topaddmemID").style.display = "block";
        document.getElementById("disbandID").style.display = "none";
        document.getElementById("toptransID").style.display = "none";
    }
    else {
        if (flag == 2) document.getElementById("topaddmemID").style.display = "none";
    }
}
function edit_icon (flag, id)
{
     if (flag == 1)
     {
        document.getElementById("iconID"+id).style.display = "none"
        document.getElementById("iconEditID"+id).style.display = "block"
     }
     else
     {
        document.getElementById("iconID"+id).style.display = "block"
        document.getElementById("iconEditID"+id).style.display = "none"
     }
}
function send_title (id, icon_id)
{
     var edit_title = document.getElementById("edit_title"+icon_id).value;
     window.location.href="f_games.php?ocd=edit_icon&id="+id+"&icon_id="+icon_id+"&edit_title="+edit_title;
}

// by no - for latest on forum - AJAX hints

var hintMas = new Array();
var lastKey = '';

function in_array(key, mas)
{
	for(ikey in mas)
		if(ikey == key) return true;
	return false;
}

function HintShow(fname, e, tid, action) //topic_id
{
	var div = document.getElementById(fname);
	
	div.style.visibility = 'visible';
	
	if (document.attachEvent != null) 
	{ // Internet Explorer & Opera 
            x = e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); 
            y = e.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); 
    } else if (!document.attachEvent && document.addEventListener) 
    { // Firefox 
            x = e.clientX + window.scrollX; 
            y = e.clientY + window.scrollY; 
    }
	
	x += 10;
	y += 10;
	x = x + 'px';
	y = y + 'px';

	div.style.left = x;
	div.style.top = y;
	
	//lastKey = String.concat(action, tid);
	lastKey = action + '' + tid;
	
	if(in_array(lastKey, hintMas)) 
	{
		//onAjaxSuccessHints(hintMas[lastKey]);
		document.getElementById('fhint').innerHTML = hintMas[lastKey];
		return;
	}


$.post(
  'ajax.php',
  {
  	act: action,
    id: tid
  },
  onAjaxSuccessHints
);

}

function onAjaxSuccessHints(data)
{
	k = data.indexOf('|');
	key = data.substr(0, k);
	//hintMas[lastKey] = data;
	hintMas[key] = data.substr(k+1);	
	//document.getElementById('fhint').innerHTML = data;
	if(key != lastKey) return;
	document.getElementById('fhint').innerHTML = hintMas[key];
}


function HintHide(fname)
{
	document.getElementById(fname).style.visibility = 'hidden';
	document.getElementById(fname).innerHTML = '...';
}

function srch_head()
{
  if (document.search_frm_head.s.value != 'Поиск →')
  {
    document.search_frm_head.submit();
  }
  else
  {
    document.search_frm_head.s.focus();
  }
}

/* who online ajax change */
function rotate_last(i) 
{

	if (onl_count_i != 23)
	{
		$('#onl_total').html('<b>'+onl_count_arr[onl_count_i]+'</b> ' + plural(onl_count_arr[onl_count_i], ["человек", "человека", "человек"]));
		onl_count_i++;
	}
	else 
	{
		/*$.post(
				'ajax.php',
				{
					act: 'get_online_cnt'
				},
				function(data)
									{
										eval(data);
										onl_count_arr = data.onl;
									}
				); 
		*/
		onl_count_i = 0;
	}

	var y = i-1;
	if (y<0)
		y = 14;
	var offdiv = 'last_act_' + y;
	$('#'+offdiv).hide();
	var ondiv = 'last_act_' + i;
  $('#'+ondiv).fadeIn("fast");
	i++;
	if (i>14)
	{
    setTimeout("rotate_last(0)", 5000);
	}
	else
	{
    setTimeout("rotate_last(" + i + ")", 5000);
	}
}

// Show/Hide spoiler 
function fShowHideSpoiler(tr)
{
	tr2 = tr.parentNode.lastChild;
	if(tr2.style.display == 'none') tr2.style.display = 'block'; else tr2.style.display = 'none';
}

function onAjaxSuccessXLBet(data)
{
	dv = document.getElementById('div_xlbet');
	dv.innerHTML = data;
	//todo
}

function fGetXLBetLg()
{
	//var lid = 80;	
	sel = document.getElementById('xlbet_lg_id');
	lid = sel.options[sel.selectedIndex].value;
	if(lid != 0) $.post('ajax.php', {act: "get_xlbet", lg: lid}, onAjaxSuccessXLBet);	
}

/* key page nav */
function chk_page_nav(ev)
{
  var targ;
	if(!ev)	ev = window.event;

	if (ev.target) targ = ev.target;
	else if (ev.srcElement) targ = ev.srcElement;
	if (targ.nodeType == 3) targ = targ.parentNode;
		
	if(targ.tagName != 'TEXTAREA' && targ.tagName != 'INPUT') 
	{
    if (max_pg > 1)
    {
      next_pg = $("#cur_pg").html(); next_pg--;
      
      if (next_pg > max_pg) next_pg = max_pg;
      else if (next_pg < 0) next_pg = max_pg;
      cur_type = $(".nav_cmts").attr("type");
      
      switch (ev.keyCode ? ev.keyCode : ev.which ? ev.which : null)
      {
        case 0x25:
          load_cmnts_by_pg(cur_type,next_pg-1);
          break;
        case 0x27:
          load_cmnts_by_pg(cur_type,next_pg+1);
          break;
      }
    }
	}
}

// add rewards (in user_details.php) // by no

function onAjaxGetRewards(data)
{
	/*k = data.indexOf('|');
	mid = data.substr(0, k);
	data = data.substr(k+1);*/

	t = document.getElementById("reward_tbl");
	if(!t) return;

	tr = document.createElement("TR");
	tr.innerHTML = data;
	t.tBodies[0].appendChild(tr);	
}

function fGetRewards(mid)
{
$.post(
  'ajax.php',
  {
  	act: "get_rewards",
    id: mid
  },
  onAjaxGetRewards
);
}

var selected_reward = null;
var last_rew_border = null;

function fImgRewardMOver(img)
{
	last_rew_border = img.style.border;
	img.style.border = 'solid 3px black';
}

function fImgRewardMOut(img)
{
	img.style.border = last_rew_border;
}


function fImgRewardSel(img)
{
	if(selected_reward != null) selected_reward.style.border = 'solid 3px transparent';
	selected_reward = img;
	last_rew_border = img.style.border = 'solid 3px red';
}

function onAjaxDelReward(data)
{
	eval(data);
	if(data.rez == 'ok') 
	{
		alert('Награда была удалена');
		img = document.getElementById(data.id);
		img.src = null;
		img.alt = '';
		img.title = '';
	}
}

function fDelReward()
{
	if(selected_reward == null) return;
	$.post('ajax.php', { act: "del_reward", id: selected_reward.id}, onAjaxDelReward );
}

function onAjaxAddReward(data)
{
	if(data=='ok')
	{
		t = document.getElementById("reward_tbl");
		if(!t) return;
		
		tr = t.tBodies[0].lastChild;
		tr.parentNode.removeChild(tr);
		
		alert('Награда была добавлена успешно!');
	}
	else
	{
		alert(data);
	}
}

function fAddReward(mid)
{
	sel = document.getElementById('sel_reward');
	rid = sel.options[sel.selectedIndex].value;
	if(rid != 0) 
	{
		$.post(
		  'ajax.php',
		  {
		  	act: "add_reward",
		    id: mid,
		    rew: rid
		  },
		  onAjaxAddReward
		);
	}
}

function fAddCancel()
{
	t = document.getElementById("reward_tbl");
	if(!t) return;
	
	tr = t.tBodies[0].lastChild;
	tr.parentNode.removeChild(tr);
}

/* matches toggle */
function matchesToggle(id)
{
  if (id == 0)
  {
    $("#PastMatches").show();
    $("#CurrentMatches").hide();
    $("#FutureMatches").hide();
  }
  else if (id == 1)
  {
    $("#PastMatches").hide();
    $("#CurrentMatches").show();
    $("#FutureMatches").hide();
  }
  else if (id == 2)
  {
    $("#PastMatches").hide();
    $("#CurrentMatches").hide();
    $("#FutureMatches").show();
  }

  setCookie("bMatches", id);

  return false;
}

function get_matches(teamId, type, lnk)
{
	if (typeof teamId == 'undefined') teamId = 0;
	if (typeof lnk != 'undefined') $(lnk).blur();
	if (typeof $("#m_choose").data("cur_load") == 'undefined')
	{
		if (typeof type == 'undefined') type = cur_tab_m;
		$("#matches_blk_"+Math.abs(type-1)).hide();
		$("#matches_blk_"+Math.abs(type-2)).hide();
		$("#matches_blk_"+Math.abs(type-3)).hide();
		if (typeof lnk != 'undefined') 
		{
			$("#m_choose .active").attr("class", "");
			$(lnk).attr("class", "active");
		}
		
		if (matches_loaded[type] == 0)
		{
			if (teamId > 0)
				url = 'ajax.php?teamid=' + teamId;
			else
				url = 'ajax.php';
		
			if ($("#matches_blk_"+type).length > 0) $("#matches_blk_"+type).remove();
			if ($("#refresh_m_btn").css("display") != 'none')
			{
				$("#refresh_m_btn a").blur();
				$("#refresh_m_btn").hide();
			}
			$("#m_choose").data("cur_load", type);
			$("#m_choose").append('<tr id="matches_loading"><td class="cell_bright_blue" align="center" colspan="2"><img src="images/ajax-loader_blue.gif" align="absmiddle" alt="loading" /></td></tr>');
			$.post(
				url,
				{
					act: 'get_matches',
					type: type
				},
				function(data)
									{
										eval(data);
										if (data.err)
										{
											alert(data.err);
										}
										else
										{
											m_last_upd = Math.round(new Date().getTime() / 1000);
											$("#m_choose").removeData("cur_load");
											$("#m_choose").after(data.content);
											highlightTableRows ("matches_blk_"+type, "cell_dark_blue");
											matches_loaded[type] = 1;
											$("#matches_loading").remove();
										}
									}
				); 
		}
		$("#matches_blk_"+type).show();
		setCookie("bMatches", type);
		cur_tab_m = type;
	}
	return false;
}

function refresh_btns()
{
	if (e_last_upd == 0 && m_last_upd == 0 && d_last_upd == 0 && diaries_last_upd == 0 && files_last_upd == 0)
	{
		files_last_upd = 0;
		diaries_last_upd = 0;
		e_last_upd = 0;
		m_last_upd = 0;
		d_last_upd = 0;
	}
	now = Math.round(new Date().getTime() / 1000);
	if (files_last_upd + 12 <= now)
	{
		diaries_loaded = [0,0,0];
	}
	if (diaries_last_upd + 12 <= now)
	{
		diaries_loaded = [0,0];
	}
	if (e_last_upd + 12 <= now)
	{
		events_loaded = [[0,0,0],[0,0,0]];
	}
	if (m_last_upd + 12 <= now && $("#refresh_m_btn").css("display") == 'none')
	{
		matches_loaded = [0,0,0];
		$("#refresh_m_btn").show();
	}
	if (d_last_upd + 12 <= now && $("#refresh_d_btn").css("display") == 'none')
	{
		demos_loaded = [0,0,0];
		$("#refresh_d_btn").show();
	}
	setTimeout("refresh_btns()", 15000);
}

/* demos toggle */
function demosToggle(id)
{
  if (id == 0)
  {
    $("#StandardDemos").show();
    $("#SilverDemos").hide();
    $("#GoldDemos").hide();
  }
  else if (id == 1)
  {
    $("#StandardDemos").hide();
    $("#SilverDemos").show();
    $("#GoldDemos").hide();
  }
  else if (id == 2)
  {
    $("#StandardDemos").hide();
    $("#SilverDemos").hide();
    $("#GoldDemos").show();
  }

  setCookie("bDemos", id);

  return false;
}

function get_demos(teamId, type, lnk)
{
	if (typeof teamId == 'undefined') teamId = 0;
	if (typeof lnk != 'undefined') $(lnk).blur();
	if (typeof $("#d_choose").data("cur_load") == 'undefined')
	{
		if (typeof type == 'undefined') type = cur_tab_d;
		$("#demos_blk_"+Math.abs(type-1)).hide();
		$("#demos_blk_"+Math.abs(type-2)).hide();
		$("#demos_blk_"+Math.abs(type-3)).hide();
		if (typeof lnk != 'undefined') 
		{
			$("#d_choose .active").attr("class", "");
			$(lnk).attr("class", "active");
		}
		
		if (demos_loaded[type] == 0)
		{
			if (teamId > 0)
				url = 'ajax.php?teamid=' + teamId;
			else
				url = 'ajax.php';
				
			if ($("#demos_blk_"+type).length > 0) $("#demos_blk_"+type).remove();
			if ($("#refresh_d_btn").css("display") != 'none')
			{
				$("#refresh_d_btn a").blur();
				$("#refresh_d_btn").hide();
			}
			$("#d_choose").data("cur_load", type);
			$("#d_choose").append('<tr id="demos_loading"><td class="cell_bright_blue" align="center" colspan="2"><img src="images/ajax-loader_blue.gif" align="absmiddle" alt="loading" /></td></tr>');
			$.post(
				url,
				{
					act: 'get_demos',
					type: type
				},
				function(data)
									{
										eval(data);
										if (data.err)
										{
											alert(data.err);
										}
										else
										{
											d_last_upd = Math.round(new Date().getTime() / 1000);
											$("#d_choose").removeData("cur_load");
											$("#d_choose").after(data.content);
											highlightTableRows ("demos_blk_"+type, "cell_dark_blue");
											demos_loaded[type] = 1;
											$("#demos_loading").remove();
										}
									}
				); 
		}
		$("#demos_blk_"+type).show();
		setCookie("bDemos", type);
		cur_tab_d = type;
	}
	return false;
}

function change_events(mode, lnk)
{
	$("#events_blk_"+cur_mode_e+"_"+cur_tab_e).hide();
	cur_mode_e = mode;
		
	if (typeof lnk != 'undefined')
	{
		$(lnk).blur();
		$("#e_head .active").attr("class", "");
		$(lnk).attr("class", "active");
	}
	
	get_events(0, cur_tab_e)
	return false;
}

function get_events(teamId, type, lnk)
{
	if (typeof teamId == 'undefined') teamId = 0;
	if (typeof lnk != 'undefined') $(lnk).blur();
	if (typeof $("#e_head").data("cur_load") == 'undefined')
	{
		if (typeof type == 'undefined') type = cur_tab_e;
		$("#events_blk_0_"+Math.abs(type-1)).hide();
		$("#events_blk_0_"+Math.abs(type-2)).hide();
		$("#events_blk_0_"+Math.abs(type-3)).hide();
		$("#events_blk_1_"+Math.abs(type-1)).hide();
		$("#events_blk_1_"+Math.abs(type-2)).hide();
		$("#events_blk_1_"+Math.abs(type-3)).hide();
		if (typeof lnk != 'undefined') 
		{
			$("#e_choose .active").attr("class", "");
			$(lnk).attr("class", "active");
		}
		
		if (events_loaded[cur_mode_e][type] == 0)
		{
			if (teamId > 0)
				url = 'ajax.php?teamid=' + teamId;
			else
				url = 'ajax.php';
				
			if ($("#events_blk_"+cur_mode_e+"_"+type).length > 0) $("#events_blk_"+cur_mode_e+"_"+type).remove();
			$("#e_choose").remove();
			$("#e_head").data("cur_load", type);
			$("#e_head").append('<tr id="events_loading"><td class="cell_bright_orange" align="center" colspan="2"><img src="images/ajax-loader.gif" align="absmiddle" alt="loading" /></td></tr>');
			$.post(
				url,
				{
					act: 'get_events_lnks',
					mode: cur_mode_e,
					type: type
				},
				function(data)
									{
										eval(data);
										if (data.err)
										{
											alert(data.err);
										}
										else
										{
											$("#e_head").after(data.content);
											$("#events_loading").remove();
											$("#e_choose").append('<tr id="events_loading"><td class="cell_bright_orange" align="center" colspan="2"><img src="images/ajax-loader.gif" align="absmiddle" alt="loading" /></td></tr>');
											
											$.post(
												url,
												{
													act: 'get_events',
													mode: cur_mode_e,
													type: type
												},
												function(data)
																	{
																		eval(data);
																		if (data.err)
																		{
																			alert(data.err);
																		}
																		else
																		{
																			e_last_upd = Math.round(new Date().getTime() / 1000);
																			$("#e_head").removeData("cur_load");
																			$("#e_choose").after(data.content);
																			highlightTableRows ("events_blk_"+cur_mode_e+"_"+type, "cell_dark_orange");
																			events_loaded[cur_mode_e][type] = 1;
																			$("#events_loading").remove();
																		}
																	}
												); 
										}
									}
				); 
		}
		$("#events_blk_"+cur_mode_e+"_"+type).show();
		setCookie("bEvents", cur_mode_e+","+type);
		cur_tab_e = type;
	}
	return false;
}
/* matches toggle */
function get_diaries(type, lnk)
{
	if (typeof lnk != 'undefined') $(lnk).blur();
	if (typeof $("#diaries_choose").data("cur_load") == 'undefined')
	{
		if (typeof type == 'undefined') type = cur_tab_diaries;
		$("#diaries_blk_"+Math.abs(type-1)).hide();
		$("#diaries_blk_"+Math.abs(type-2)).hide();
		if (typeof lnk != 'undefined') 
		{
			$("#diaries_choose .active").attr("class", "");
			$(lnk).attr("class", "active");
		}
		
		if (diaries_loaded[type] == 0)
		{
			url = 'ajax.php';
		
			if ($("#diaries_blk_"+type).length > 0) $("#diaries_blk_"+type).remove();
			if ($("#refresh_m_btn").css("display") != 'none')
			{
				$("#refresh_m_btn a").blur();
				$("#refresh_m_btn").hide();
			}
			$("#diaries_choose").data("cur_load", type);
			$("#diaries_choose").append('<tr id="diaries_loading"><td class="cell_bright_grey" align="center" colspan="2"><img src="images/ajax-loader.gif" align="absmiddle" alt="loading" /></td></tr>');
			$.post(
				url,
				{
					act: 'get_index_diaries',
					type: type
				},
				function(data)
									{
										eval(data);
										if (data.err)
										{
											alert(data.err);
										}
										else
										{
											diaries_last_upd = Math.round(new Date().getTime() / 1000);
											$("#diaries_choose").removeData("cur_load");
											$("#diaries_choose").after(data.content);
											diaries_loaded[type] = 1;
											$("#diaries_loading").remove();
										}
									}
				); 
		}
		$("#diaries_blk_"+type).show();
		setCookie("bDiaries", type);
		cur_tab_diaries = type;
	}
	return false;
}
/* files toggle */
function get_files(type, lnk)
{
	if (typeof lnk != 'undefined') $(lnk).blur();
	if (typeof $("#files_choose").data("cur_load") == 'undefined')
	{
		if (typeof type == 'undefined') type = cur_tab_files;
		$("#files_blk_"+Math.abs(type-1)).hide();
		$("#files_blk_"+Math.abs(type-2)).hide();
		if (typeof lnk != 'undefined') 
		{
			$("#files_choose .active").attr("class", "");
			$(lnk).attr("class", "active");
		}
		if (files_loaded[type] == 0)
		{
			url = 'ajax.php';
		
			if ($("#files_blk_"+type).length > 0) $("#files_blk_"+type).remove();
			$("#files_choose").data("cur_load", type);
			$("#files_choose").append('<tr id="files_loading"><td class="cell_bright_blue" align="center" colspan="2"><img src="images/ajax-loader.gif" align="absmiddle" alt="loading" /></td></tr>');
			$.post(
				url,
				{
					act: 'get_index_files',
					type: type
				},
				function(data)
					{
						eval(data);
						if (data.err)
						{
							alert(data.err);
						}
						else
						{
							files_last_upd = Math.round(new Date().getTime() / 1000);
							$("#files_choose").removeData("cur_load");
							$("#files_choose").after(data.content);
							files[type][0] = data.url;
							files[type][1] = data.title_all;
							$("#files_url_all").attr("href", data.url);
							$("#files_url_all").html(data.title_all);
							files_loaded[type] = 1;
							$("#files_loading").remove();
						}
					}
				); 
		}
		$("#files_blk_"+type).show();
		$("#files_url_all").attr("href", files[type][0]);
		$("#files_url_all").html(files[type][1]);
		setCookie("bFiles", type);
		cur_tab_files = type;
	}
	return false;
}

function streamToggle(id)
{
  swfobject.removeSWF("vstream");
  swfobject.removeSWF("vstreamhq");
  swfobject.removeSWF("vstream_SC2TV");
  $("#Stream").hide();
  $("#StreamHQ").hide();
  $("#Stream_SC2TV").hide();
  
  if (id == 0)
  {
	//var flashvars = {"comment":"gg","st":"http://www.goodgame.ru/js/plr/styles/video96.txt","file":"rtmp://87.118.126.65/live/livestream"};
	//var params = { flashvars: "comment=gg&st=http://www.goodgame.ru/js/plr/styles/video96.txt&file=rtmp://87.118.126.65/live/livestream", bgcolor: "#ffffff", allowFullScreen: "true", allowScriptAccess: "always", wmode: "opaque"};
	//new swfobject.embedSWF("http://www.goodgame.ru/js/plr/uppod.swf", "stream", "400", "320", "9.0.0", false, flashvars, params);
    $("#Stream").show();
	
	addStreamFlash("Stream", "vstream", "video96", "livestream1", 400, 320);
	$("textarea[name='stream_code']").text($('<div>').append($('#vstream').clone()).remove().html().toLowerCase());
  }
  else if (id == 1)
  {
	//var flashvars = {"comment":"gg","st":"http://www.goodgame.ru/js/plr/styles/video96hq.txt","file":"rtmp://87.118.126.65/live/stream_hq"};
	//var params = {bgcolor:"#ffffff", allowFullScreen:"true", allowScriptAccess:"always", wmode:"opaque"};
	//new swfobject.embedSWF("http://www.goodgame.ru/js/plr/uppod.swf", "streamhq", "640", "480", "9.0.0", false, flashvars, params);
    $("#StreamHQ").show();
		
	addStreamFlash("StreamHQ", "vstreamhq", "video96hq", "livestream2", 512, 404);
	$("textarea[name='stream_code']").text($('<div>').append($('#vstreamhq').clone()).remove().html().toLowerCase());
  }
  else if (id == 2)
  {
	//var flashvars = {"comment":"gg","st":"http://www.goodgame.ru/js/plr/styles/video96hq.txt","file":"rtmp://87.118.126.65/live/stream_hq"};
	//var params = {bgcolor:"#ffffff", allowFullScreen:"true", allowScriptAccess:"always", wmode:"opaque"};
	//new swfobject.embedSWF("http://www.goodgame.ru/js/plr/uppod.swf", "streamhq", "640", "480", "9.0.0", false, flashvars, params);
    $("#Stream_SC2TV").show();
		
	addStreamFlash("Stream_SC2TV", "vstream_SC2TV", "video96hq", "sc2tv", 512, 404);
	$("textarea[name='stream_code']").text($('<div>').append($('#vstream_SC2TV').clone()).remove().html().toLowerCase());
  }

  setCookie("bStream", id);

  return false;
}

function addStreamFlash(elem, id, style, host, channel, width, height)
{	
	var div = document.getElementById(id);
	if (!div) {					
		div = document.createElement("div");
		div.setAttribute("id", id);
		document.getElementById(elem).appendChild(div);
	}
	
	if (swfobject.hasFlashPlayerVersion("9.0.0"))
	{
		//var attr = { data: "", width: width, height: height };
		//var params = { flashvars: "comment=gg&st=" + style + ".txt&file=, bgcolor: "#ffffff", allowFullScreen: "true", allowScriptAccess: "always", wmode: "opaque"};
		//swfobject.createSWF(attr, params, id);
		
		var flashvars = {comment:"gg", st:"http://www.goodgame.ru/js/plr/styles/" + style + ".txt", file:"rtmp://" + host + "/live/" + channel};
		var params = {bgcolor:"#ffffff", allowFullScreen:"true", allowScriptAccess:"always"};
		var attributes = {id:id,name:"player"};
		new swfobject.embedSWF('http://www.goodgame.ru/js/plr/uppod.swf', id, width, height, "9.0.0", false, flashvars, params, attributes); 
	}
	else
		document.getElementById(id).innerHTML = "Возникла ошибка при загрузке проигрывателя. Для корректной работы обновите вашу версию flash плеера.<br><br>";
}

function playAudio(id, file) {
	if ($('#' + id).html() == '') {
		var flashvars = {uid: id, st:"http://www.goodgame.ru/js/plr/styles/audio_right.txt", file: file};
		var params = {bgcolor:"#ffffff", allowFullScreen:"true", allowScriptAccess:"always"};
		new swfobject.embedSWF('http://www.goodgame.ru/js/plr/uppod.swf', id, 340, 31, "9.0.0", false, flashvars, params);
	}
	else
		uppodSend(id, "file:" + file);
		
	return false;
}

/* diary rating*/
var _diaryRating = false;

function diaryRating(id, type) {
	_diaryRating = true;
			
	$.ajax({
		async: true,
		cache: false,
		type: "GET",
		url: "ajax.php",
		data: "act=diary_rating&id=" +id + "&type=" + type,
		dataType: "json",
		beforeSend: function() {
		},
		error: function() {
			_diaryRating = false;
			$("#diaryRateInfo").css("color", "red");
			$("#diaryRateInfo").html("При оценке дневника произошла ошибка. Попробуйте ещё раз.");
		},
		success: function(data) {
			eval(data);
			if (data.err) {
				$("#diaryRateInfo").css("color", "red");
				$("#diaryRateInfo").html(data.err);
			} else {
				if (data.rating >= 0) {
					$("#diaryRating").html("+" + data.rating);
					$("#diaryRating").attr("class", "diary_rating_1");
				} else {
					$("#diaryRating").html(data.rating);
					$("#diaryRating").attr("class", "diary_rating_0");
				}
				$("#diaryRatingContainer a").remove();
				$("#diaryRateInfo").css("color", "green");
				$("#diaryRateInfo").html("Вы успешно оценили дневник.");
			}
		},
		complete: function() {
			_diaryRating = false;
		}
	});
	
	return false;
}

/* team games member toggle */
function teamMembersToggle(id)
{
	if ($("#game_" + id + "_members"))
	{
		$("#game_" + id + "_members").toggle();
		
	    var image = document.getElementById("game_" + id + "_header_image");
		
		if ($("#game_" + id + "_members").css("display") == "none")
			image.src = "./images/game_headers/" + id + "_close.gif";
		else
			image.src = "./images/game_headers/" + id + "_open.gif";
	}

	return false;
}

var xmlHttp_Targets;
/* targets */
function targetsAdd(name, isTeam, page, teamId)
{
	if (page == null)
	{
		page = "news";
	}
	if (teamId == null)
	{
		teamId = 0;
	}
	
	xmlHttp_Targets = GetXmlHttpObject()
	
	if (xmlHttp_Targets == null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}
	
	var target;
	if (isTeam == 1)
	{
		target = document.getElementById(name + "Input").value;
		
		if (name == "teamTarget")
			document.getElementById("teamTargetInput").value = "";
	}
	else
	{
		target = document.getElementById(name + "Input").value;
		
		if (name == "playerTarget")
			document.getElementById("playerTargetInput").value = "";
	}
    	
    var url;
    url = page + ".php?ocd=TargetGetId&target=" + target + "&type=" + isTeam;
		
    xmlHttp_Targets.onreadystatechange=function()
	{
		if (xmlHttp_Targets.readyState==4 || xmlHttp_Targets.readyState=="complete")
		{
			var xmldoc = xmlHttp_Targets.responseXML;
			
			if (xmldoc.getElementsByTagName('content').item(0).firstChild.data.length != 0)
			{
				var memberid;
				memberid = xmldoc.getElementsByTagName('content').item(0).firstChild.data;
														
				var targets;
				if (isTeam == 1)
					targets = document.getElementById("teamTargets").value;
				else
					targets = document.getElementById("playerTargets").value;
					
				var tmp = targets.split(",");
				var find = false;
				
				for(elem in tmp)
					if ((tmp[elem] > 0) && (tmp[elem] == memberid))
						find = true;
											
				if (!find)
				{
					if (isTeam == 1)
					{
						if (targets)
							document.getElementById("teamTargets").value += ",";
						
						document.getElementById("teamTargets").value += memberid;
					}
					else
					{
						if (targets)
							document.getElementById("playerTargets").value += ",";
							
						document.getElementById("playerTargets").value += memberid;
					}
																		
					targetsUpdate(isTeam, page, teamId);
				}
			}
		}
	}
    xmlHttp_Targets.open("GET",url,true);
    xmlHttp_Targets.send(null);
}

function targetsDelete(id, isTeam, page, teamId)
{
	if (page == null)
	{
		page = "news";
	}
	if (teamId == null)
	{
		teamId = 0;
	}
	
	var targets;
	if (isTeam == 1)
		targets = document.getElementById("teamTargets").value;
	else
		targets = document.getElementById("playerTargets").value; 
								
	var tmp = targets.split(",");
	targets = "";
				
	for(elem in tmp)
	{		
		if ((tmp[elem] > 0) && (tmp[elem] != id))
			targets += tmp[elem] + ",";
	}
	targets.substring(0, targets.length - 1);
	
	if (isTeam == 1)
		document.getElementById("teamTargets").value = targets;
	else
		document.getElementById("playerTargets").value = targets; 
						
	targetsUpdate(isTeam, page, teamId);
	
	return false;
}

function targetsUpdate(isTeam, page, teamId)
{
	if (page == null)
	{
		page = "news";
	}
	if (teamId == null)
	{
		teamId = 0;
	}
	
	xmlHttp_Targets = GetXmlHttpObject()
	
	if (xmlHttp_Targets == null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}
	
	var targets;
	if (isTeam == 1)
		targets = document.getElementById("teamTargets").value;
	else
		targets = document.getElementById("playerTargets").value;
    
	if (!targets)
		targets = 0;
	
    var url = page + ".php?ocd=TargetGetSigns&targets=" + targets + "&type=" + isTeam + "&teamid=" + teamId;		
			
    xmlHttp_Targets.onreadystatechange=function()
	{
		if (xmlHttp_Targets.readyState==4 || xmlHttp_Targets.readyState=="complete")
		{
			var xmldoc = xmlHttp_Targets.responseXML;		

			if (xmldoc.getElementsByTagName('content').item(0).firstChild.data.length != 0)
			{
				var signs;
				signs = xmldoc.getElementsByTagName('content').item(0).firstChild.data;
					
				if (isTeam == 1)
					document.getElementById("teamTargetData").innerHTML = signs;
				else
					document.getElementById("playerTargetData").innerHTML = signs;
			}
		}
	}
    xmlHttp_Targets.open("GET",url,true);
    xmlHttp_Targets.send(null);
}

function postModeChange(value)
{
	if (value == 0)
	{
		$('#selectTeam').hide();
		$('#onlyTeam').hide();
		document.getElementById("onlyTeamCheckBox").checked = false;
		document.getElementById("postTeam").value = "";
		document.getElementById("selectTeamData").innerHTML = "";
		$("#selectTeamInput").show();
		$("#selectTeamButton").show();
	}
	else if (value == 1)
	{
		$('#selectTeam').show();
		$('#onlyTeam').show();
		if (document.getElementById("selectTeamData").innerHTML.length > 0)
		{
			$("#selectTeamInput").hide();
			$("#selectTeamButton").hide();
		}
	}
}

function postSelectTeam(page, teamId)
{
	xmlHttp_SelectTeam = GetXmlHttpObject()
	
	if (xmlHttp_SelectTeam == null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}
	var team = document.getElementById("selectTeamInput").value;
	document.getElementById("selectTeamInput").value = "";
	
    var url = page + ".php?ocd=TargetGetId&target=" + team + "&type=1";
		
    xmlHttp_SelectTeam.onreadystatechange=function()
	{
		if (xmlHttp_SelectTeam.readyState==4 || xmlHttp_SelectTeam.readyState=="complete")
		{
			var xmldoc = xmlHttp_SelectTeam.responseXML;
			
			if (xmldoc.getElementsByTagName('content').item(0).firstChild.data.length != 0)
			{
				var team = xmldoc.getElementsByTagName('content').item(0).firstChild.data;
																		
				document.getElementById("postTeam").value = team;
				
				$("#selectTeamInput").hide();
				$("#selectTeamButton").hide();
				postUpdateTeam(page, teamId);
			}
		}
	}
    xmlHttp_SelectTeam.open("GET",url,true);
    xmlHttp_SelectTeam.send(null);
}

function postDeleteTeam()
{
	document.getElementById("postTeam").value = "";
	document.getElementById("selectTeamData").innerHTML = "";
	$("#selectTeamInput").show();
	$("#selectTeamButton").show();
	
	return false;
}

function postUpdateTeam(page, teamId)
{
	xmlHttp_SelectTeam = GetXmlHttpObject()
	
	if (xmlHttp_SelectTeam == null)
	{
		alert ("Browser does not support HTTP Request")
		return
	}
	
	var team = document.getElementById("postTeam").value;
	if (!team)
		team = 0;
	
    var url = page + ".php?ocd=GetTeamSign&team=" + team + "&teamid=" + teamId;		
			
    xmlHttp_SelectTeam.onreadystatechange=function()
	{
		if (xmlHttp_SelectTeam.readyState==4 || xmlHttp_SelectTeam.readyState=="complete")
		{
			var xmldoc = xmlHttp_SelectTeam.responseXML;		

			if (xmldoc.getElementsByTagName('content').item(0).firstChild.data.length != 0)
			{
				var sign = xmldoc.getElementsByTagName('content').item(0).firstChild.data;
					
				document.getElementById("selectTeamData").innerHTML = sign;
			}
		}
	}
    xmlHttp_SelectTeam.open("GET",url,true);
    xmlHttp_SelectTeam.send(null);
}

/* ajax voting */
function ajax_vote(q_id)
{
	answ_id = $('input[name=opros]:checked').val();
	if (!answ_id) alert('Выберите вариант ответа!');

	vote_blk = $("form[name='vote_form']").parent();
	vote_btn = $("input[class='block_green_voteButton']").parent();
	$(vote_blk).attr("align", "center");
	$(vote_blk).html('<img src="images/ajax-loader-green.gif" title="Пожалуйста, подождите..." align="absmiddle" alt="loading"/>');
  $.post("./ajax.php",
	{
		act: 'do_vote',
		q_id: q_id,
		answ_id: answ_id 	        
	},
	function(data)
	{
		eval(data);
		if (data.err)
		{
			alert(data.err);
		}
		else
		{
			$(vote_blk).html(data.content);
			$(vote_btn).html(data.button);
		}
	}); 
	return false;
}

/* toggle post */
function toggle_post(post_id)
{
	exp = ($("#forum_post_"+post_id).attr("class") == 'forum_post');
	if (exp)
	{
		$("#forum_post_"+post_id).attr("class", "forum_post_del");
		$("#forum_post_"+post_id+" .exp img").attr("src", "images/ico/exp.png");
		$("#forum_post_"+post_id+" .exp img").attr("title", "Развернуть");
	}
	else
	{
		$("#forum_post_"+post_id).attr("class", "forum_post");
		$("#forum_post_"+post_id+" .exp img").attr("src", "images/ico/col.png");
		$("#forum_post_"+post_id+" .exp img").attr("title", "Свернуть");
	}
	$("#forum_post_"+post_id+" .exp a").blur();
	return false;
}

/* claim */
function init_dialog()
{
	$("#dialog").dialog({ autoOpen: false, position: 'center', width: 400, height: 300, maxWidth: 450,
	buttons: { 
						 'Отправить жалобу': function() 
						 {
							$("#claim_loading").show();
							$.post("./ajax.php",
							{
								act: 'do_claim',
								type: $("form[name='claim_form'] input[name='type']").val(),	        
								obj_id: $("form[name='claim_form'] input[name='obj_id']").val(),	        
								desc: $("form[name='claim_form'] textarea[name='desc']").val()	        
							},
							function(data)
							{
								eval(data);
								if (data.err)
								{
									alert(data.err);
								}
								else
								{
									$("#claim_loading").hide();
									$("#claim_res").html(data.content);
									$("#claim_res").show();
									$("div[role='dialog'] button").hide();
								}
							}); 
						 }
					 }
	});
}
function claim(obj, type, obj_id)
{
	$("#claim_username").html($("#author_"+obj_id).html());
	$("form[name='claim_form'] input[name='type']").val(type);
	$("form[name='claim_form'] input[name='obj_id']").val(obj_id);
	$("#claim_loading").hide();
	$("#claim_res").hide();
	$("div[role='dialog'] button").show();
	
	$("#dialog").dialog("open");
	$("form[name='claim_form'] textarea[name='desc']").focus();
	return false;
}
function plural(n, ends) 
{
    var n = n % 100;
    var n2 = n % 10;

    if (n >= 5 && n <= 20) return ends[2];
    else if (n2 > 1 && n2 < 5) return ends[1];
    else if (n2 == 1) return ends[0];

    return ends[2];
}

function gameEditSave(game, btn) {
	if (btn.disabled)
		return false;
			
	var dat = tinyMCE.getContent();
			
	$.ajax({
		async: true,
		cache: false,
		type: "POST",
		contentType: "application/x-www-form-urlencoded",
		url: "game.php",
		data: {
			ocd: "save",
			id: game,
			data: dat
		},
		beforeSend: function() {
			$("#gameDataLoading").show();
			btn.disabled = true;
		},
		error: function() {
			btn.disabled = false;
		},
		success: function() {
		},
		complete: function() {
			btn.disabled = false;
			$("#gameDataLoading").hide();
			$("#gameDataEdit").hide();
			$("#gameData").show();
			$("#gameData").html(dat);
		}
	});
}


function donate(type) {
	if(type == 1) var purse = 'Z279657895526';
	else var purse = 'R349427971724';

	var link = "wmk:payto?Purse="+purse+"&Desc=Пожертвование";
	location.href = link;
	
	return false;
}

$(function() {
	if($('#donateform').length)
	$('#donateform').replaceWith('<input type="button" onclick="return donate(0);" value="Пожертвовать (WMR)" />&nbsp;<input type="button" value="Пожертвовать (WMZ)" onclick="return donate(1);" />');
});


