var IE = false;
var IE6 = false;
var IE7 = false;
var Opera = window.opera ? true : false
var Safari = navigator.userAgent.indexOf('Safari') > -1;
var Gecko = navigator.userAgent.indexOf('Gecko') > -1 && !Safari;

//////////////////////////////////////////////

function ErrHandler(msg, url, lno)
{
//	if (top.debug) {
		if (top.sys_msg)
		{
			top.sys_msg('error - ' + msg + '<br>url - ' + url + '<br>line - ' + lno); 
		}
		else
		{
			alert('error - ' + msg + '<br>url - ' + url + '<br>line - ' + lno); 
		}	
//	}
	return true;
}

//window.onerror = ErrHandler;

//////////////////////////////////////////////
/*
clear = window.location.href.split('?');
if (clear[1]) 
{
	clear = clear[1].split('&');
	if (clear[0] == 'clear')
	{
		top.chat_mode_refresh[0] = 0;
		top.chat_refresh(1);
	}
}
*/
//////////////////////////////////////////////

function fnShowProps(obj, objName)
{
  result = '';
  for (var i in obj)
 		if (i != 'outerHTML' && i != 'innerHTML') 
		alert(objName + '.' + i + ' = ' + obj[i]);
		//result += objName + '.' + i + ' = ' + obj[i] + '<br /> ';
//  top.sys_msg(result);
	//alert(result);
//	$('idPage2').innerHTML+=result;
}

//////////////////////////////////////////////

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

function $f(id)
{
	if (navigator.appName.indexOf('Microsoft') != -1) 
	{
		return window[id];
	} 
	else 
	{
	  return document[id];
	}
}

function getBodyScrollTop()
{
	return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function getBodyScrollLeft()
{
	return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}

function getDocumentHeight()
{
	return document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight;
}

function getDocumentWidth()
{
	return document.body.scrollWidth > document.body.offsetWidth ? document.body.scrollWidth : document.body.offsetWidth;
}
//////////////////////////////////////////////

function fixPNG()
{
	if (IE6)
	{
		var div = document.body.getElementsByTagName('DIV');
		for(i=0; i<div.length; i++)
		{
			src = div[i].currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
			if (src) 
			{
				src = src[1];
				div[i].runtimeStyle.backgroundImage='none'; 
			}
			if (src) 
			{
				div[i].runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '",sizingMethod="crop")';
			}
		}
	}
}

////////////////////////////////////////////////

function WaitResponse(reqData)
{
	if (reqData.loader.readyState == 4) 
	{
		clearTimeout(reqData.loader.reqDataTimeout);
		if (reqData.loader.status == 200)
		{ 
			if (reqData.loader.responseText != null) 
			{
				processdata(reqData.loader.responseText);
			}
			reqData.loader = false;
		}
	}			
}

function RequestTimeout(reqData)
{
	clearTimeout(reqData.reqDataTimeout);

	try 
	{
		reqData.loader.abort();
		reqData.loader = false;
	}
	catch(e)
	{
	}
}

function _reqData() 
{
	this.loader = false;
	this.reqDataTimeout = -1;
}

function doLoad(query, url)
{
	if (!url)
	{
		url = window.location.href;
	}

	var reqData = new _reqData();
	
	if (window.XMLHttpRequest && !(window.ActiveXObject)) 
	{
		try 
		{
			reqData.loader = new XMLHttpRequest();
		}
		catch (e)
		{
			reqData.loader = false;
		}
	} 
	else if (window.ActiveXObject) 
	{
		try 
		{
			reqData.loader = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (e) 
		{
			try 
			{
				reqData.loader = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e)
			{
				reqData.loader = false;
			}
		}
	}
	
	if (reqData.loader) 
	{
		url = url.split('#');
		url = url[0].split('?');
		
		reqData.reqDataTimeout = -1;
		reqData.loader.onreadystatechange = function ()
			{
				WaitResponse(reqData);
			}; 
		reqData.loader.open('POST', url[0], true);
		reqData.loader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		reqData.loader.setRequestHeader('Content-length', query.length);
		//reqData.setRequestHeader('Accept-Language', 'ru, en');
		//reqData.setRequestHeader('Accept-Charset', 'utf-8');
		reqData.loader.send(query);
		reqData.reqDataTimeout = setTimeout(
			function ()
			{
				RequestTimeout(reqData);
			}, 
			5000);
	}
}

/////////////////////////////////////////////////

function show_status(status)
{
	$('id_status_text').innerHTML = msg(status);
	$('id_status').style.display = status == '' ? 'none' : 'block';
}

/////////////////////////////////////////////////

function format_timestamp(timestamp)
{
	format_time = '';
	timestamp = parseInt(timestamp);

	if (timestamp == 0) 
	{
		return '00:00:00';
	}
	else
	{
		format_time = ':' + (timestamp % 60 < 10 ? '0' : '') + timestamp % 60;
		timestamp = Math.floor(timestamp / 60);

		format_time = ':' + (timestamp % 60 < 10 ? '0' : '') + timestamp % 60 + format_time;
		timestamp = Math.floor(timestamp / 60) + 3 + top.dst;

		format_time = (timestamp % 24 < 10 ? '0' : '') + timestamp % 24 + format_time;
		return format_time;
	}
}

function format_time_left(time_left, seconds, left_text)
{
	s = '';
	arr = [' сек ', 60, ' мин ', 60, ' ч ', 60, ' д ', 24]; 
	
	if (seconds && seconds == 1) 
	{ 
		start = 0; 
		time_left = time_left * 60; 
	}	
	else 
	{
		if (time_left < 60)
		{
			s = 'меньше минуты';
		}
		start = 1;
	}
	if (time_left < 1)
	{
		s = 'время истекло';
	}
	else 
	{
		for (i = start; i < 4; i++) 
		{
			t = i < 3 ? Math.floor(time_left / arr[i * 2 + 1]) % arr[(i + 1) * 2 + 1] : Math.floor(time_left / arr[i * 2 + 1]);
			if (t >= 0 && i == 0 || t > 0)
			{
				if (t > 0)
				{
					s = t + arr[i * 2] + s;
				}
			}
			time_left = Math.floor(time_left / arr[i * 2 + 1]);
		}
		
		if (!left_text) 
		{
			s = 'осталось ' + s;
		}
	}
	return s;
}

var Month = new Array('янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек');

function format_date_time(date, time, w)
{
	arr = date.split(' ');
	d = arr[0].split('-');
	if (time)
	{
		t = arr[1].split(':');
	}
	fstr = d[2] + ' ' + Month[(d[1]) * 1 - 1] + ' ' + d[0].substr(2, 2) + ' г ' + (time ? t[0] + ':' + t[1] : '');
	if (w)
	{
		document.write(fstr);
	}
	else
	{
		return fstr;
	}
}


var smiles_size = [25,25, 27,23, 20,24, 20,24, 20,24, 21,21, 20,20, 25,25, 20,20, 34,23, 31,22, 22,26, 36,27, 29,23, 28,28, 20,24, 39,34, 28,25, 23,26, 21,21, 26,22, 36,23, 47,24, 30,26, 26,23, 51,28, 20,26, 28,24, 30,33, 35,26, 21,25, 40,26, 28,25, 24,22, 40,27, 29,25, 36,26, 36,26, 20,27, 32,20, 39,26, 42,27, 43,27, 29,24, 20,24, 27,24, 51,26, 36,26, 27,24];

function msg(message, chat)
{
	max_smiles = chat ? 3 : 30;

	num_smiles = 0;
	smile_index = 1;
	index = 0;

	message = ' ' + message + ' ';

	smiles = [[],
		[":1:","8P","8p"],
		[":2:","O:-)","O:)","O+)","O=)","0:-)","0:)","0+)","0=)"],
		[":3:",":-(",":(","+(","=("],
		[":4:",";-)",";)","^_~"],
		[":5:",":-P",":P",":-p",":p","+P","=P","+p","=p",":-b",":b","+b","=b"],
		[":6:","8-)","8)","B)"],
		[":7:",":-D",":D","+D","=D"],
		[":8:",":-[",":[",";'&gt;",";-."],
		[":9:","=-O","=O","=-o","=0","O_O","O_o","o_O","O_0","o_0","0_O","0_o"],
		[":10:",":-*",":*",":-{}",":{}","+{}","={}","^.^"],
		[":11:",":'(",":-'("],
		[":12:",":-X",":-x","X:","x:",":-#",":#"],
		[":13:","&gt;:o","&gt;:O","&gt;+O","&gt;:o","&gt;+o","&gt;=o",":-@"],
		[":14:",":-|",":|","=|"],
		[":15:",":-\\",":-/",":\\"],
		[":16:",":-)",":)","=)","+)"],
		[":17:","]:-&gt;","}:-&gt;","]:&gt;","}:&gt;","&gt;:-]","&gt;:]"],
		[":18:","[:-}","[:}"],
		[":19:"],
		[":20:",":-!",";-!",":!",";!",":-~",";-~"],
		[":21:","|-0"],
		[":22:"],
		[":23:"],
		[":24:","@}-&gt;--","@}-:--","@&gt;}--`---"],
		[":25:"],
		[":26:"],
		[":27:"],
		[":28:","@="],
		[":29:"],
		[":30:","\\m/"],
		[":31:","%)","%-)",":$"],
		[":32:"],
		[":33:"],
		[":34:"],
		[":35:"],
		[":36:"],
		[":37:"],
		[":38:"],
		[":39:"],
		[":40:"],
		[":41:"],
		[":42:"],
		[":43:"],
		[":44:"],
		[":45:"],
		[":46:"],
		[":47:"],
		[":48:"],
		[":49:"]
	];

	var coint =  [['euro'], 
		[' евро ']
	];

	while (smile_index < smiles.length)
	{
		index = 0;
		while (index < smiles[smile_index].length)
		{
			while ((message.indexOf(' ' + smiles[smile_index][index] + ' ') != -1) && (num_smiles < max_smiles))
			{
				message = message.replace(' ' + smiles[smile_index][index] + ' ', ' <img src="/images/smiles/' + smile_index + '.gif" style="width: ' + smiles_size[smile_index * 2 - 2] + 'px; height: ' + smiles_size[smile_index * 2 - 1] + 'px; cursor: pointer; " onclick="add_smile(\'' + smile_index + '\')" alt="' + smiles[smile_index][index] + '" title="' + smiles[smile_index][index] + '"> ');
				num_smiles++;
			}
			if (num_smiles >= max_smiles) break;
			index++;
		}
		if (num_smiles >= max_smiles) break;
		smile_index++;
	}

	if (chat)
	{
		smile_index = 1;
		while (smile_index <= 155)
		{
			while ((message.indexOf(':ms' + smile_index + ':') != -1) && (num_smiles < max_smiles))
			{
				message = message.replace(':ms' + smile_index + ':', ' <img src="/images/smiles/ms/' + smile_index + '.gif"> ');
				num_smiles++;
			}
			if (num_smiles >= max_smiles) break;
			smile_index++;
		}
	}

	smile_index = 1;
	num_smiles = 0;
	while (smile_index <= 255)
	{
		while ((message.indexOf(':cl' + smile_index + ':') != -1) && (num_smiles < max_smiles))
		{
			message = message.replace(':cl' + smile_index + ':', (IE6 ? '<img src="/images/clan/' + smile_index + '.gif" style="width:16px; height:16px;" class="image_link" />' : ' <span style="margin-left:18px;"><span class="relative"><span style="background: url(/images/clan/' + smile_index + '.gif); position:absolute; bottom:0px; margin:0 0 0 -18px; width:16px; height:16px;" class="image_link"></span></span></span> '));
			num_smiles++;
		}
		if (num_smiles >= max_smiles) break;
		smile_index++;
	}

	smile_index = 0;
	num_smiles = 0;
	while (smile_index < 2)
	{
		while ((message.indexOf(':' + coint[0][smile_index] + ':') != -1) && (num_smiles < max_smiles))
		{
			message = message.replace(':' + coint[0][smile_index] + ':', (IE6 ? coint[1][smile_index] : '<span class="res"><span class="rel"><span class="' + coint[0][smile_index] + '"></span></span></span>'));
			num_smiles++;
		}
		if (num_smiles >= max_smiles) break;
		smile_index++;
	}

	return message;
}

function info(uname) 
{
	var w = window.open('/~' + uname, '_blank');
	w.focus();
}

//	name, level, align, clan, sex
function login(login_text, w, color)
{
	a = login_text.split(',');
	var s = '';
	if (a.length == 5)
	{
		s = '&nbsp;' + (a[3] > 0 ? (IE6 ? '<img src="/images/clan/' + a[3] + '.gif" style="width:16px; height:16px; cursor:pointer;" onclick="window.open(\'/clan.php?id=' + a[3] + '\')" class="image_link" />' : '<span style="margin-left:18px;"><span class="rel"><span style="background: url(/images/clan/' + a[3] + '.gif); position:absolute; margin:0 0 0 -15px; bottom:0px; width:16px; height:16px; cursor:pointer;" onclick="window.open(\'/clan.php?id=' + a[3] + '\', \'_blank\', \'width=905,height=700\')" class="image_link"></span></span></span>') : '') +
		(a[2] > 0 ? (IE6 ? '<img src="/images/clan/al_' + a[2] + '.gif" style="width:16px; height:16px; cursor:pointer;" onclick="window.open(\'/clan.php?id=' + a[2] + '\')" class="image_link" />' : '<span style="margin-left:18px;"><span class="rel"><span style="background: url(/images/clan/al_' + a[2] + '.gif" position:absolute; margin:0 0 0 -15px; bottom:0px; width:16px; height:16px;"></span></span></span>') : '') +
		'<span class="textB '+(color ? 'team_' + color : 'link')+'" onclick="' + (top ? 'top.' : '') + 'click_to(\'' + a[0] + '\');" style="margin-left:1px; cursor:pointer;">' + a[0] + '</span><span style="margin-left:3px;">[' + a[1] + ']</span>' +
		(IE6 ? '<img src="/images/design/' + a[4] + '.gif" style="width:12px; height:14px; cursor:pointer; vertical-align:middle;" title="Информация" onclick="info(\'' + a[0] + '\')" />' : '<span style="margin-left:18px;"><span class="rel"><span class=' + (a[4] == 'f' ? 'female' : 'male') + ' title="Информация" onclick="info(\'' + a[0] + '\')" style="margin:0 0 0 -15px; bottom:0px; cursor:pointer; position:absolute;"></span></span></span>');
	}

	if (w)
	{
		document.write(s);
	}
	else
	{
		return s;
	}
}

function team(team_text, team, w){
	s = '';
	team_arr = team_text.split(';');
	for (i=0; i<team_arr.length; i++)
	{
		if (team_arr[i] != '')
		{
			s += login(team_arr[i], 0, team);
		}
	}
	
	if (w) 
	{
		document.write(s);
	}
	else 
	{
		return s;
	}
}

//name, level, align, clan, sex, st_time, tr
function chat_login(a, w, half)
{
	if (half)
	{
		a = a.split('\t');
	}
	
	s = (half ? '<span style="float:left; clear:left;">' : '<span class="private" style="float:left; clear:left; margin-top:3px; margin-right:3px; height:15px;" alt="Приват" onclick="click_to(\'' + a[0] + '\',1)"></span>') +
		(a[3] > 0 ? '<span style="float:left; margin-top:-2px; background:url(/images/clan/' + a[3] + '.gif); width:16px; height:16px; cursor:pointer;" onclick="window.open(\'clan.php?id=' + a[3] + '\', \'_blank\', \'width=905,height=700\')"></span>' : '') +
		'<span class="link" style="float:left;" onclick="click_to(\'' + a[0] + '\',0)" oncontextmenu="open_menu(\'' + a[0] + '\',this); return false;">' + a[0] + '</span><span style="float:left;">[' + a[1] + ']</span>' +
		'<span class=' + (a[4] == 'f' ? 'female' : 'male') + ' title="Информация" onclick="info(\'' + a[0] + '\')" style="float:left; cursor:pointer;"></span>' +
		(a[5] > 0 ? '<span style="float:left; background:url(/images/design/st.gif); width:24px; height:13px;" title="Наложено заклятие молчания: ' + formatTimeLeft(a[5]) + '"></span>' : '') +
		(a[6] > 0 ? '<span style="float:left; margin-top:-2px; background:url(/images/design/tr.gif); width:16px; height:16px;" title="Травма - ' + formatTimeLeft(a[6]) + '"></span>' : '') + 
		(half ? '</span>' : '') +	'<br />';


	if (w) 
	{
		document.write(s);
	}
	else 
	{
		return s;
	}
}

function click_to(uname, chat_mode)
{
	if (top.frames.length > 0)
	{
		var text = top.frames['chatline'].$('text');
	
		if (text)
		{
			s = text.value;
			exists = false;
			first_pos = s.indexOf('[');
			end_pos = s.indexOf(']', first_pos);
			
			if (first_pos != -1 && end_pos != -1) 
			{
				names = s.substr(first_pos + 1, end_pos - first_pos - 1);
				names_arr = names.split(',');
				i = 0;
				while (!exists && i < names_arr.length)
				{
					exists = (names_arr[i] == uname);
					i++;
				}
				if (!exists)
				{
		 			text.focus();
					text.value = s.substr(0, end_pos) + ',' + uname + s.substr(end_pos);
				}
			} 
			else
			{
		 		text.focus();
				text.value = ' [' + uname + '] ' + top.frames['chatline'].$('text').value;
			} 
			
			if (chat_mode != undefined)
			{
				top.frames['chatline'].select_mode(chat_mode);
			}
		}
		else
		{
			var text = top.frames['chatline'].$('name');
			if (text)
			{
				text.value = uname;
			}
		}
	}
}

////////////////////////////////////////////////////////////////////////////////

function by_name_asc(a, b)
{
	if (a[0].toLowerCase() < b[0].toLowerCase())
	{
		return -1;
	}
	else if (a[0].toLowerCase() > b[0].toLowerCase())	
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

function by_name_desc(a, b)
{
	if (b[0].toLowerCase() < a[0].toLowerCase())
	{
		return -1;
	}
	else if (b[0].toLowerCase() > a[0].toLowerCase())
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

function by_number_asc(a, b)
{
	return a[1]-b[1];
}

function by_number_desc(a, b)
{
	return b[1]-a[1];
}

////////////////////////////////////////////////////////////////////////////////

var submenu_items = [,
	['Инвентарь', 'inv.php', 'Магазин', 'shop.php', 'Замок (смена фракции)', 'castle.php', 'Набор армии', 'recruitment.php', 'Личная почта', 'mail.php'],
	['Заявки', 'demand.php'],
	['Карта мира', 'map.php', 'Биржа', 'exchange.php'],
	['Рулетка', 'roulette.php'],
	[]];

var submenu_timer = -1;

function show_submenu(submenu_index)
{
	if (submenu_index > 0 && submenu_index < 6)
	{
		clearTimeout(submenu_timer);
		var s = '&nbsp; |';
		for (i=0; i<submenu_items[submenu_index].length/2; i++)
		{
			s += ' <span class="link" style="color:white;" onclick="location.href=\''+submenu_items[submenu_index][i*2+1]+'\'">' + submenu_items[submenu_index][i*2] + '</span> |';
		}	
		$('id_submenu').innerHTML = s;
	}
}

function hide_submenu()
{
	submenu_timer = setTimeout(function() {$('id_submenu').innerHTML = '&nbsp;'}, 500);
}

function submit_search_name()
{
	if (top == window)
	{
		location.href='/~'+$('id_search_name').value;
	}
	else
	{
		info($('id_search_name').value);
	}
	
	return false;
}

function flogin_submit()
{
	if (window.location.search.indexOf('url') == -1)
	{
		$('flogin').action = '/?url=' + encodeURIComponent(window.location.pathname + window.location.search);
	}
	else
	{
		$('flogin').action = '/' + window.location.search;
	
	}
	return true;
}

function top_header()
{
	var s = '<div class="head_bg"></div>'+
	'<a href="/" class="logo">' +
/*	
			AC_FL_RunContent2(
			'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0',
			'width', '41',
			'height', '45',
			'src', 'swf/logo',
			'quality', 'high',
			'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
			'play', 'true',
			'loop', 'true',
	//		'scale', 'showall',
			'wmode', 'transparent',
			'devicefont', 'false',
			'id', 'logo',
			'bgcolor', '#F7F7F7',
			'name', 'logo',
			'menu', 'false',
			'allowFullScreen', 'false',
			'allowScriptAccess','always',
			'movie', 'swf/logo',
			'salign', ''		
		)+
*/
	'</a>'+
	'<div class="energy"></div>'+
	'<div id="id_online" style="position:absolute; top:10px; right:15px; color:white; font-size:1.1em;">online 50000 server time 15:00</div>'+
	'<div id="id_user_resource" style="position:absolute; width:350px; height:20px; top:8px; left:50%; margin-left:-274px; color:white; font-weight:bold;" title=""></div>';
	document.write(s);
}

function header(login, online, resource)
{
	$('head_bg').innerHTML = '<a href="/" class="logo"></a>' +
		
		//'<div id="id_online" style="position:absolute; top:10px; right:15px; color:white; font-size:1.1em;">online 50000 server time 15:00</div>'+

	(login == '1' ? 
		'<div id="id_user_resource">' + USER.get_resource(resource.split("\t")) + '</div>'
		:
		'<div class="form_login">' +
			'<form id="flogin" name="flogin" action="" method="post">' +
				'<div>' +
					'<span>Логин</span>' +
					'<input name="login" />' +
					'<span>Пароль</span>' +
					'<input name="password" type="password" />' +
					'<div class="button" style="float:left;"><div onclick="if (flogin_submit()) document.flogin.submit()">Войти</div></div>' + 
				'</div>' +
			'</form>' +
		'</div>'
	) + 
	'<div id="top_menu">' +
	
		/*(login == '1' ? '<div style="width:966px; margin-top:-5px; text-align:center; padding: 3px 0px 4px 0px; font-weight:bold;" onmouseover="clearTimeout(submenu_timer)" onmouseout="hide_submenu()">'+
			' | <span class="link" style="color:white;" onclick="show_submenu(1)">Персонаж</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(2)">Поединки</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(3)">Карта мира</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(4)">Казино</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(5)">Рейтинги</span>'+
			' | <a href="/forum.php">Форум</a>' +
		'</div>'+
		'<div id="id_submenu" style="width:966px; margin-top:-5px; text-align:center; padding: 3px 0px 4px 0px; font-weight:bold;" onmouseover="clearTimeout(submenu_timer)" onmouseout="hide_submenu()">'+
			'&nbsp;'+
		'</div>' : '<a href="/forum.php">Форум</a>') +*/
		
		(login == '1' ? /*'<div style="float:left; width:766px; margin-top:-5px; text-align:center; padding: 3px 0px 4px 0px; font-weight:bold;" onmouseover="clearTimeout(submenu_timer)" onmouseout="hide_submenu()">'+
			' | <span class="link" style="color:white;" onclick="show_submenu(1)">Персонаж</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(2)">Поединки</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(3)">Карта мира</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(4)">Казино</span>'+
			' | <span class="link" style="color:white;" onclick="show_submenu(5)">Рейтинги</span>'+
		'</div>'*/ '' : '') +
		'<div class="button" style="float:right;"><div onclick="location.href=\'/forum.php\'">Форум</div></div>' +
		(login == '1' ? 
		'<div id="id_submenu" style="width:766px; text-align:center; padding: 3px 0px 4px 0px; font-weight:bold;" onmouseover="clearTimeout(submenu_timer)" onmouseout="hide_submenu()">'+
			'&nbsp;'+
		'</div>' : /*'<div class="button" style="float:right; margin-right:10px;"><div onclick="location.href=\'/preview.php\'">Попробовать бой</div></div>'*/'<div class="button" style="float:right; margin-right:10px;"><div onclick="location.href=\'/reg.php\'">Регистрация</div></div>') +
	'</div>';
}

function top_menu()
{
	$('id_user_resource').innerHTML = USER.get_resource();
	var s = '<div style="width:966px; background:#EEDBA2; text-align:center; padding: 3px 0px 4px 0px; font-weight:bold;" onmouseover="clearTimeout(submenu_timer)" onmouseout="hide_submenu()">'+
		' | <span class="link" onclick="show_submenu(1)">Персонаж</span>'+
		' | <span class="link" onclick="show_submenu(2)">Поединки</span>'+
		' | <span class="link" onclick="show_submenu(3)">Карта мира</span>'+
		' | <span class="link" onclick="show_submenu(4)">Казино</span>'+
		' | <span class="link" onclick="show_submenu(5)">Рейтинги</span> |'+
	'</div>'+
	'<div id="id_submenu" style="width:966px; background:#F7F7F7; text-align:center; padding: 3px 0px 4px 0px; font-weight:bold;" onmouseover="clearTimeout(submenu_timer)" onmouseout="hide_submenu()">'+
		'&nbsp;'+
	'</div>';
	document.write(s);
}

////////////////////////////////////////////////////////////////////////////////

function update_online(online)
{
	var s = '';
	online = online.toString();
	while (online != '')
	{
		value = online.substr(0,1);
		online = online.substr(1);
		s += '<div class="digit'+value+'" style="float:left; margin-left:1px;"></div>';
	}
	
	if (top != window)
	{
		if (top.frames['main'].$('id_online'))
		{
			top.frames['main'].$('id_online').innerHTML = s;
		}
	}
	else
	{
		if ($('id_online'))
		{
			$('id_online').innerHTML = s;
		}
	}
}

////////////////////////////////////////////////////////////////////////////////

var selected_tab = -1; 
var selected_tab_content = -1; 

function select_tab(tab, content)
{
	if (tab > 0 && tab < 10)
	{
		if (selected_tab != -1)
		{
			//$('id_tab_'+selected_tab).className = 'tab';
			
			var tab_content = $('id_tab_content_'+selected_tab_content);
			if (tab_content)
			{
				tab_content.className = 'hide';
			}
		}
		//$('id_tab_'+tab).className = 'tab_active';

		var tab_content = $('id_tab_content_'+(content ? content : tab));
		if (tab_content)
		{
			tab_content.className = '';
			selected_tab_content = (content ? content : tab);
		}
		selected_tab = tab;
		//show_status('');
	}
}

////////////////////////////////////////////////////////////////////////////////

function png(element, image, rand)
{
	if (element == '')
	{
		return (IE6 ? 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' : 'background-image: url(') + '/images/' + image + '.png' + (IE6 ? ', sizingMethod=crop);' : '); background-repeat: no-repeat;');
	}
	else if (IE6)
	{
		$(element).style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/images/' + image + '.png' + (rand ? '?' + Math.random() : '') + ', sizingMethod=crop);';
	}
	else
	{
		$(element).style.backgroundImage = 'url(/images/' + image + '.png' + (rand ? '?' + Math.random() : '') + ')';
	}
}

function round_ex(value, decimals){
	n_power = Math.pow(10, decimals);
	value = isNaN(value) ? 0 : Math.round(value * n_power) / n_power;
	return value;
}

function format_digit(digit)
{
	if (digit == 0)
	{
		return '0';
	}
	else
	{
		return (digit > 0 ? '+' : '&minus;') + Math.abs(digit);
	}
}

function euro(value, bold)
{
	return '<span class="res"><span class="rel"><span class="euro"></span></span></span>' + (bold ? '<b>' : '') + round_ex(value, 2) + (bold ? '</b>' : '');
}
////////////////////////////////////////////////////////////////////////////////

var id = 0;
var amount = 1;
var thing_id = 2;
var image = 3;
var thing_name = 4;
var slot = 5;
var cost = 6;
var level_need = 7;
var now_wear = 8;
var max_wear = 9;
var attack = 10;
var defence = 11;
var power = 12;
var knowledge = 13;
var luck = 14;
var morale = 15;
var initiative = 16;
var visible = 17;
var description = 18;

var template_size = [, ['m', 100, 100, 504, 508, 384, 510], ['b', 200, 200, 938, 942, 716, 944]];

var bNone = 0;
var bBuy = 1;
var bSale = 2;
var bWear = 3;
var bInfo = 0;
var bEdit = 4;
var bDelete = 5;

var button_caption = [[],
											['Купить','buy'],
											['Продать','sale'],
											['Надеть','wear'],
											['Редактировать','edit'],
											['Удалить','delete']
											];
/*
function template_thing(a, size, button1, button2)
{
	var s = '<div style="padding:3px; background:#DAE2E8; border-'+(size == 2 ? 'bottom' : 'top')+':#45688E 1px solid;text-align:center;font-weight:bold; width:' + template_size[size][3] + 'px;">'+
			(button1 > 0 ? '<div style="float:right; color:#A9B8CB;" class="link" onclick="button_action_'+button_caption[button1][1]+'(\''+a[thing_id]+'\', \''+a[image]+'\', \''+a[thing_name]+'\', \'\', \''+a[id]+'\')">'+button_caption[button1][0]+'</div>' : '')+
			(button2 > 0 ? '<div style="float:right; margin-right:10px; color:#A9B8CB;" class="link" onclick="button_action_'+button_caption[button2][1]+'(\''+a[thing_id]+'\', \''+a[image]+'\', \''+a[thing_name]+'\', \'\', \''+a[id]+'\')">'+button_caption[button2][0]+'</div>' : '')+
			(a[visible] > 0 ? '<div style="float:right; margin-right:10px; color:red;">скрыто</div>' : '') +
			'<span style="color:black;" class="link" onclick="show_thing(' + (a[id] != '' ? a[id] + ', 1' : a[thing_id] + ', 0') + ')">'+a[thing_name]+'</span>'+
		'</div>'+

		'<div style="overflow:hidden; width:' + template_size[size][4] + 'px; background:white; border-left:#DAE2E8 1px solid; border-right:#DAE2E8 1px solid; ">'+
			'<div class="slot' + template_size[size][0] + '" style="float:left; margin-left:'+(IE6 ? '2' : '5')+'px; margin-top:12px; cursor:pointer; '+png('', a[image]+template_size[size][0])+'" onclick="show_thing(' + (a[id] != '' ? a[id] + ', 1' : a[thing_id] + ', 0') + ')"></div>'+
			'<div style="float:left; margin-top:12px; width:5px; height:'+template_size[size][2] + 'px; background:white;"></div>'+
			
			'<div style="float:right; padding:4px 7px 4px 7px; overflow:hidden; width:' + template_size[size][5] + 'px; height:16px;">'+
				'<div class="textG" style="float:left;">Требует:</div>'+
				'<div class="textB" style="float:right;font-weight:bold;">Уровень '+a[level_need]+'</div>'+
			'</div>'+
			'<div class="hr" style="clear:right;"></div>'+
			'<div class="textB" style="float:right; padding:4px 7px 4px 7px; overflow:hidden; width:' + template_size[size][5] + 'px; height:16px;">'+
				'<div class="textG" style="float:left;">Свойства:</div>'+
				(a[attack] != 0 ? '<div style="float:right;font-weight:bold; margin-right:10px;">'+(a[attack] > 0 ? '+' : '&minus;')+Math.abs(a[attack])+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>' : '')+
				(a[defence] != 0 ? '<div style="float:right;font-weight:bold; margin-right:10px;">'+(a[defence] > 0 ? '+' : '&minus;')+Math.abs(a[defence])+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>' : '')+
				(a[power] != 0 ? '<div style="float:right;font-weight:bold; margin-right:10px;">'+(a[power] > 0 ? '+' : '&minus;')+Math.abs(a[power])+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>' : '')+
				(a[knowledge] != 0 ? '<div style="float:right;font-weight:bold; margin-right:10px;">'+(a[knowledge] > 0 ? '+' : '&minus;')+Math.abs(a[knowledge])+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>' : '')+
				(a[luck] != 0 ? '<div style="float:right;font-weight:bold; margin-right:10px;">'+(a[luck] > 0 ? '+' : '&minus;')+Math.abs(a[luck])+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>' : '')+
				(a[morale] != 0 ? '<div style="float:right;font-weight:bold; margin-right:10px;">'+(a[morale] > 0 ? '+' : '&minus;')+Math.abs(a[morale])+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>' : '')+
				(a[initiative] != 0 ? '<div style="float:right;font-weight:bold; margin-right:10px;">'+(a[initiative] > 0 ? '+' : '&minus;')+Math.abs(a[initiative])+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>' : '')+
			'</div>'+
			'<div class="hr" style="clear:right;"></div>'+
			'<div style="float:right; padding:4px 7px 4px 7px; overflow:hidden; width:' + template_size[size][5] + 'px; height:16px;">'+
				'<div class="textG" style="float:left;">Стоимость:</div>'+
				'<div class="textB" style="float:right;font-weight:bold;">'+round_ex(a[cost], 2)+'</div><div style="float:right; margin-top:-3px;" class="euro"></div>'+
			'</div>'+
			'<div class="hr" style="clear:right;"></div>'+
			'<div style="float:right; padding:4px 7px 4px 7px; overflow:hidden; width:' + template_size[size][5] + 'px; height:16px;">'+
				'<div class="textG" style="float:left;">Наличие:</div>'+
				'<div class="textB" style="float:right;font-weight:bold;">'+a[amount]+' шт</div>'+
			'</div>'+
			'<div class="hr" style="clear:right;"></div>'+
			'<div style="float:right; padding:4px 7px 4px 7px; overflow:hidden; width:' + template_size[size][5] + 'px; height:16px;">'+
				'<div class="textG" style="float:left;">Прочность:</div>'+
				'<div class="textB" style="float:right;font-weight:bold;">'+a[now_wear]+'/'+a[max_wear]+'</div>'+
			'</div>'+

			(size == 2 ? '<div class="hr" style="clear:right;"></div>'+
				'<div class="textB" style="float:left; padding:4px 7px 4px 7px; overflow:hidden; width:' + template_size[size][5] + 'px;">'+
					'<span class="textG">Описание:</span> ' + a[description] +
				'</div>' : '')+

		'</div>'+
		'<div style="float:left;border-top:#45688E 1px solid; width:' + template_size[size][6] + 'px;"></div>';

	return s;
}
*/

function template_thing(a, size, button1, button2)
{
	var s = '<div onclick="button_action_'+button_caption[button1][1]+'(\''+a[thing_id]+'\', \''+a[image]+'\', \''+a[thing_name]+'\', \'\', \''+a[id]+'\')" style="float:left; margin:2px 2px 0 0; cursor:pointer; ' + png('', a[image]) + '" class="slot"></div>';

	return s;
}

function show_thing(id, shop)
{
	if (id > 0)
	{
		window.open('/thing.php?' + (shop > 0 ? 'shop_' : '') + 'id=' + id);
	}
}

////////////////////////////////////////////////////////////////////////////////

function button_action_buy(thing_id, image, thing_name, magic, id)
{
	if (confirm('Вы действительно хотите приобрести "' + thing_name + '"?'))
	{
		if (thing_id > 0)
		{
			doLoad('action=buy&thing_id=' + thing_id + '&category=' + category);
		}
		else
		{
			doLoad('action=buy&id=' + id + '&category=' + category);
		}
	}
}

function button_action_sale(thing_id, image, thing_name, magic, id)
{
	if (confirm('Вы действительно хотите продать "' + thing_name + '"?'))
	{
		doLoad('action=sale&thing_id=' + thing_id + '&category=' + category);
	}
}

function button_action_wear(thing_id, image, thing_name, magic, id)
{
	if (thing_id > 0)
	{
		doLoad('action=wear&thing_id=' + thing_id);
	}
}

function button_action_edit(thing_id, image, thing_name, magic, id)
{
	if (id > 0)
	{
		doLoad('action=edit&id=' + id + '&category=' + category);
	}
}

function button_action_delete(thing_id, image, thing_name, magic, id)
{
	if (id > 0 && confirm('Удалить ' + thing_name + '?'))
	{
		doLoad('action=delete&id=' + id + '&category=' + category);
	}
}

////////////////////////////////////////////////////////////////////////////////

function wear_slot(index,image,cursor, alpha)
{
	var idSlot = $('slot' + index);
	if (IE6)
	{
		idSlot.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/images/' + image + '.png, sizingMethod=crop);';
	}
	else
	{
		idSlot.style.backgroundImage = 'url(/images/' + image + '.png)';
		if (IE7)
		{
			idSlot.style.filter = alpha ? 'progid:DXImageTransform.Microsoft.Alpha(opacity=10)' : '';
		}
		else
		{
			idSlot.style.opacity = alpha ? '0.50' : '1';
		}
	}
	idSlot.style.cursor = cursor ? 'pointer' : 'default';
}

function thing_wear_down(slot)
{
	if (USER.wear_on[slot-1]>0)
	{
		//if (slot == 6)
		//{
		//	slot = 4;
		//} 
		doLoad('action=wear_down&slot_id='+slot);
	}
}

////////////////////////////////////////////////////////////////////////////////

function left_menu_header(title)
{
	var s = '<div style="float:left; clear:left; background:#F7EFBF; text-align:center; border:#D7CF9E 1px solid; margin-top:1px; padding:0 0 1px 0; width:210px;font-weight:bold; color:black;">'+
		'<div style="border-top:#EBE2B6 1px solid;"></div>'+
		(title ? title : 'Навигация')	+
	'</div>';
	document.write(s);
}

function left_menu()
{
	var menu_item = [['Инвентарь', 'inv.php'], ['Магазин', 'shop.php'], ['Карта мира', 'map.php'], ['Биржа', 'exchange.php'], ['Рулетка', 'roulette.php'], ['Замок (смена фракции)', 'castle.php'], ['Набор армии', 'recruitment.php'], ['Личная почта', 'mail.php']];
	var s = '<div style="float:left; clear:left; width:200px; margin-top:2px; margin-left:1px;">';

	for (i=0; i<menu_item.length; i++)
	{
		s += '<div class="link3" onclick="location.href=\''+menu_item[i][1]+'\'" style="padding:3px;">' + menu_item[i][0] + '</div>';
	}	

	s += '</div>';
	document.write(s);
}

var owner = 1;
var owner_name = 2;
var sector_x = 3;
var sector_y = 4;
var area = 5;
var balance = 6;
var salary = 7;
var building_name = 8;
var building_cost = 9;
var building_type = 10;
var building_category = 11;
var product_id = 12;
var product_count = 13;
var product_add = 14;
var product_time = 15;
var product_price = 16;
var building_resource = 17;
var building_resource_id = 0;
var building_resource_need = 1;
var building_resource_count = 2;
var building_resource_max = 3;
var building_resource_price = 4;

var building_type_name = [,'Шахта кристаллов','Каменоломня','Лесопилка','Шахта железной руды','Рудник','Угольная шахта']

var sector_name = [, 'Первый'];

function template_building(a, worker_list, w)
{
	if (a.length == 1)
	{
		var s = '<div style="text-align:center;margin-bottom:35px;">Здание не существует</div>';
	}
	else
	{
		var worker_count = worker_list.split(';').length - 1;
		var can_buy = Math.min(Math.floor(USER.resource[top.USER.euro] / a[product_price]), a[product_count]);
		
		sector[0] = a[sector_x];
		sector[1] = a[sector_y];
		
		var s = '<div id="id_status" style="background:#F7EFBF; border:#D7CF9E 1px solid; display:none;margin-bottom:5px;">' +
		'<div id="id_status_text" style="font-weight:bold; text-align:center; color:black; border-top:#EBE2B6 1px solid; padding:3px;"></div>' +
		'</div>' +
//		'<div style="text-align:center;margin-bottom:15px;">' + a[building_name] + '</div>' +
		'<span class="textG">Тип:</span> <span class="textB">' + building_type_name[a[building_type]] + '</span><br />' +
		'<span class="textG">Район:</span> <span class="link" style="font-weight:bold;" onclick="location.href=\'map.php?x=' + a[sector_x] + '&y=' + a[sector_y] + '\'">' + a[sector_x] + '_' + a[sector_y] + '</span><br />' +
		'<span class="textG">Владелец:</span> <span class="link" style="font-weight:bold;" onclick="info(\'' + a[owner_name] + '\')">' + a[owner_name] + '</span><br />' +
		'<br />' +
		'<span class="textG">Баланс:</span> <span class="res"><span class="rel"><span class="euro"></span></span></span> <span class="textB" style="font-weight:bold;">' + round_ex(a[balance], 2) + '</span><br />' +
		'<span class="textG">Площадь:</span> <span class="textB">' + a[area] + '</span><br />' +
		'<span class="textG">Зарплата:</span> <span class="res"><span class="rel"><span class="euro"></span></span></span> <span class="textB" style="font-weight:bold;">' + a[salary] + '</span><br />' +
		'<br />' +
		'<span class="textG">Список рабочих:</span> <span class="textB">(' + worker_count + ') ' + team(worker_list) + '</span><br />' +
		'<span class="textG">Свободных мест:</span> <span style="font-weight:bold;" class="textB">' + (a[area] * (a[building_category] == 'mining' ? 5 : 3) - worker_count) + '</span><br />' +
		'<br />' +
		'<span class="textG">Продукция:</span>' +
		'<table style="width:100%;margin-bottom:15px;" cellspacing="0">' +
		'<tr>' +
		'<th>Тип</th><th>Выход</th><th>Количество</th><th>Цена</th><th>Можете купить: ' + (can_buy < 1 ? '-' : can_buy) + '</th>' +
		'</tr>' +
		'<tr>' +
		'<td>' + USER.resource_name[a[product_id]] + '</td><td>' + a[product_add] + '</td><td>' + round_ex(a[product_count], 2) + '</td><td>&nbsp;<span class="res"><span class="rel"><span class="euro"></span></span></span>' + round_ex(a[product_price], 2) + '</td><td>' + (can_buy < 1 ? '-' : '<input id="id_product" style="width:50px;" value="' + can_buy + '"/> <input type="button" class="button" onclick="buy_product(' + a[id] + ')" value="Купить" />') + '</td>' +
		'</tr>' +
		'</table>' +
		'<span class="textG">Для производства требуется:</span>' +
		'<table style="width:100%;margin-bottom:15px;" cellspacing="0">' +
		'<tr>' +
		'<th>Тип</th><th>Ед/час</th><th>Закупочная цена</th><th>Количество</th><th>Продажа</th><th>У вас</th>' +
		'</tr>' +
		'<tr>' +
		'<td>Требуется часов</td><td>' + a[product_time] + '</td><td colspan="4"> - </td>' +
		'</tr>';
	
		for (i=0; i<5; i++)
		{
			if (a[building_resource + building_resource_id + i * 5] > 0)
			{
				resource_id = a[building_resource + building_resource_id + i * 5];
				resource_count = round_ex(a[building_resource + building_resource_count + i * 5], 2);
				resource_max = a[building_resource + building_resource_max + i * 5] == 0 ? '-' : a[building_resource + building_resource_max + i * 5];
		
				user_resource_count = USER.resource[resource_id];
				
				s += '<tr><td>' + USER.resource_name[a[product_id]] + '</td><td>' + a[building_resource + building_resource_need + i * 5] + '</td><td>&nbsp;<span class="res"><span class="rel"><span class="euro"></span></span></span>' + round_ex(a[building_resource + building_resource_price + i * 5], 2) + '</td><td>' + resource_count + '/' + resource_max + '</td><td>' + (user_resource_count > 0 && (resource_max == '-' || resource_max - resource_count >= 1) ? '<input id="id_resource_' + i + '" style="width:50px;" value="0"/> <input type="button" class="button" onclick="sale_resource(' + a[id] + ', ' + i + ')" value="Впарить" />' : '-') + '</td><td>' + (user_resource_count > 0 ? user_resource_count : '-') + '</td></tr>';
			}
		}
	
		s +=	'</table>';
	}
	
	if (w) 
	{
		document.write('<div id="id_building">' + s + '</div>');
	}
	else 
	{
		return s;
	}
}

function buy_product(building_id)
{
	amount = $('id_product').value;
	if (amount > 0)
	{
		doLoad('action=buy_product&building_id=' + building_id + '&amount=' + amount);
	}
	else
	{
//		show_status('так сколько покупаем?');
	}
}

function sale_resource(building_id, resource_id)
{
	amount = $('id_resource_' + resource_id).value;
	if (amount > 0)
	{
		doLoad('action=sale_resource&building_id=' + building_id + '&resource_id=' + (resource_id + 1) + '&amount=' + amount);
	}
	else
	{
//		show_status('так сколько впариваем?');
	}
}

function template_building_adm(a)
{
	if (a.length == 1)
	{
		var s = '<div style="text-align:center;margin-bottom:35px;">Здание не существует</div>';
	}
	else
	{
		var s = '<textarea id="id_name" style="width:740px; height:100px;" class="input">' + a[building_name].replace(/<br \x2f>/g, '\r\n') + '</textarea><br /><br />' +
		'<span class="textG">Тип:</span> <span class="textB">' + building_type_name[a[building_type]] + '</span><br />' +
		'<span class="textG">Район:</span> <span class="textB">' + a[sector_x] + '_' + a[sector_y] + '</span><br />' +
		'<br />' +
		'<span class="textG">Баланс:</span> <span class="res"><span class="rel"><span class="euro"></span></span></span> <input id="id_balance" style="width:50px;" value="' + round_ex(a[balance], 2) + '" /><br />' +
		'<span class="textG">Площадь:</span> <span class="textB">' + a[area] + '</span><br />' +
		'<span class="textG">Зарплата:</span> <span class="res"><span class="rel"><span class="euro"></span></span></span> <span style="font-weight:bold;"> <input id="id_salary" style="width:50px;" value="' + a[salary] + '" /></span><br />' +
		'<br />' +
		'<span class="textG">Продукция:</span>' +
		'<table style="width:100%;margin-bottom:15px;" cellspacing="0">' +
		'<tr>' +
		'<th>Тип</th><th>Выход</th><th>Количество</th><th>Цена</th>' +
		'</tr>' +
		'<tr>' +
		'<td>' + USER.resource_name[a[product_id]] + '</td><td>' + a[product_add] + '</td><td>' + round_ex(a[product_count], 2) + '</td><td>&nbsp;<span class="res"><span class="rel"><span class="euro"></span></span></span> <input id="id_product_price" style="width:50px;" value="' + round_ex(a[product_price], 2) + '" /></td>' +
		'</tr>' +
		'</table>' +
		'<span class="textG">Для производства требуется:</span>' +
		'<table style="width:100%;margin-bottom:15px;" cellspacing="0">' +
		'<tr>' +
		'<th>Тип</th><th>Ед/час</th><th>Закупочная цена</th><th>Количество</th><th>Максимум</th>' +
		'</tr>';
	
		for (i=0; i<5; i++)
		{
			if (a[building_resource + building_resource_id + i * 5] > 0)
			{
				s += '<tr><td>' + USER.resource_name[a[product_id]] + '</td><td>' + a[building_resource + building_resource_need + i * 5] + '</td><td>&nbsp;<span class="res"><span class="rel"><span class="euro"></span></span></span> <input id="id_resource_' + (i + 1) + '_price" style="width:50px;" value="' + round_ex(a[building_resource + building_resource_price + i * 5], 2) + '" /></td><td>' + round_ex(a[building_resource + building_resource_count + i * 5], 2) + '</td><td><input id="id_resource_' + (i + 1) + '_max" style="width:50px;" value="' + a[building_resource + building_resource_max + i * 5] + '" /></td></tr>';
			}
		}
	
		s +=	'</table>';
	}
	
	document.write(s);
}

function template_work(image_id, work, w)
{
	var s = '';
	if (image_id != '')
	{
		s = '<div style="width:749px; overflow:hidden; margin-bottom:15px;" class="table">' +
		'<div style="float:left; width:742px;" class="th">' +
		'Устройство на работу' +
		'</div>' +
		'<div style="float:left; width:150px; height:50px;" class="td">' +
		'<img src="/image.php?id=' + image_id + '" style="width:150px; height:50px;" />' +
		'</div>' +
		'<div style="float:left; width:570px; height:34px; text-align:left; padding-top:20px; padding-left:15px;" class="td">' +
		'<form onsubmit="return submit_work()"><input id="id_key" style="width:100px;" /> <input type="submit" class="button" value="Работать" /></form>' +
		'</div>' +
		'</div>';
	}
	
	s += work == '1' ? '<div style=" margin-bottom:15px;" class="textG">Вы уже работаете</div>' : '';
	
	if (w) 
	{
		document.write('<div id="id_building_work">' + s + '</div>');
	}
	else 
	{
		return s;
	}
}

var resource = 2;
var price = 5;
var leader_name = 6;
var rate_count = 7;
var flash_price = 10;
var time = 11;
var time_end = 12;
var form_selling = 13;
var type_price = 14;
var owner_lot = 15;


/*
var owner = 1;
var owner_name = 2;
var sector_x = 3;
var sector_y = 4;
var area = 5;
var balance = 6;
var salary = 7;
var building_name = 8;
var building_cost = 9;
var building_type = 10;
var building_category = 11;
var product_id = 12;
var product_count = 13;
var product_add = 14;
var product_time = 15;
var product_price = 16;
*/





var exchange_rate = '';

var resource_image = [, 'crystal', 'stone', 'wood', 'iron', 'ore', 'coal'];

function template_exchange(a)
{
//' + (exchange_rate.indexOf(',' + a[id] + ',') != -1 ? ' style="background:red;"' : '') + '
	var s = '<tr>'+
		'<td><div style="float:left; ' + png('', (a[resource] <= 6 ? resource_image[a[resource]] : a[image])) + '" class="slot"></div><div style="float:left; margin-left:5px; width:182px;"><span class="link" onclick="exchange_log(' + a[id] + ')">#' + a[id] + '</span> ' + a[thing_name] + '<br />' + (a[max_wear] > 0 ? 'прочность [' + a[now_wear] + '/' + a[max_wear] + ']<br />' : '') + (a[resource] > 6 ? '' : a[amount] + ' шт') + '</div></td>' +
		'<td>' + (a[form_selling] == 1 ? '<span class="textG">Аукцион</span><br />' + a[rate_count] + ' ставок<br />' + (a[flash_price] > 0 ? 'блиц цена<span class="res"><span class="rel"><span class="euro"></span></span></span> ' + round_ex(a[flash_price], 2) + '<br />' : '') : '<span class="textG">Без торга</span><br />') + (a[owner_lot] == 0 && a[flash_price] > 0 ? '<span class="link" onclick="doLoad(\'action=buy_all&id=' + a[id] + '&category=\' + category + (exchange_node_id > 0 ? \'&shop_id=\' + exchange_node_id : \'\'))">купить лот</span>' : '')  + '</td>' +
		'<td>&nbsp;<span class="res"><span class="rel"><span class="euro"></span></span></span> ' + (a[type_price] == 'one' ? round_ex(a[price], 2) + ' за 1 шт' : round_ex(a[price] * a[amount], 2)) + '</td>' +
		'<td>' + format_time_left(a[time_end], 0, 1) + '</td>' +
		'<td>' + (a[owner_lot] == 0 ? (a[form_selling] == 0 ? '<input id="id_lot_' + a[id] + '_amount" style="width:50px;' + (a[type_price] == 'all' || a[amount] == '1' ? 'display:none;" value="' + a[amount] + '" disabled' : '"') + '> <input type="button" class="button" value="Купить" onclick="doLoad(\'action=buy&id=' + a[id] + '&amount=\' + $(\'id_lot_' + a[id] + '_amount\').value + \'&category=\' + category + (exchange_node_id > 0 ? \'&shop_id=\' + exchange_node_id : \'\'))">' : '<b>' + a[leader_name] + '<b><br /><span class="link" onclick="doLoad(\'action=rate&id=' + a[id] + '&category=\' + category + (exchange_node_id > 0 ? \'&shop_id=\' + exchange_node_id : \'\'))">сделать ставку</span>') : '<span class="textG">Это <b>Ваш</b> лот</span>' + (a[form_selling] == 0 ? '<br /><br /><input type="button" class="button" onclick="doLoad(\'action=delete&id=' + a3[id] + '&category=\' + category + (exchange_node_id > 0 ? \'&shop_id=\' + exchange_node_id : \'\'))" value="Снять лот" />' : '')) + '</td>' +
		'</tr>';
	return s;
}

var exchange_tree = [];
var exchange_tree_name = [['re', 'Ресурсы'], ['we', 'Оружие'], ['ar', 'Куртки'], ['tr', 'Штаны'], 
	['fw', 'Обувь'], ['ac', 'Аксессуары'], ['he', 'Головные уборы'], ['gl', 'Перчатки'], ['tt', 'Транспорт']];

var exchange_node = [];
var exchange_tree_category = '';
var exchange_node_id = '';

function make_exchange_tree(stat)
{
	var s = '';
	for (i2=0; i2<exchange_tree_name.length; i2++)
	{
		value = exchange_tree[exchange_tree_name[i2][0]];

		s += '<li><a href="#" ' + (exchange_tree_category == exchange_tree_name[i2][0] ? 'style="font-weight:bold;"' : '') + ' onclick="select_tab(' + (stat == 0 ? '1' : '5') + ');refresh(\'' + exchange_tree_name[i2][0] + '\',' + (stat == 0 ? '0' : '1') + ')">' + exchange_tree_name[i2][1] + ' (' + (value == undefined ? 0 : value) + ')</a></li>';
		if (exchange_tree_category == exchange_tree_name[i2][0])
		{
			s += '<li><div style="margin-left:10px; font-size:0.8em;"><ol>';
			for (i3=0; i3<exchange_node.length; i3++)
			{
				s += '<<li><a href="#" ' + (exchange_node_id == exchange_node[i3][1] ? 'style="font-weight:bold;"' : '') + ' onclick="select_tab(' + (stat == 0 ? '1' : '5') + ');refresh(\'' + exchange_tree_name[i2][0] + '\',' + (stat == 0 ? '0' : '1') + ',\'' + exchange_node[i3][1] + '\')">' + exchange_node[i3][2] + ' (' + exchange_node[i3][0] + ')</a></li>';
			}
			s += '</ol></div></li>';
		}
	}
	$('id_exchange_left_menu').innerHTML = '<ol>' + s + '</ol>';
}

function exchange_log(id)
{
	if (id > 0)
	{
		window.open('/exchange_log.php?id=' + id);
	}
}

////////////////////////////////////////////////////////////////////////////////

function template_building_list(a2)
{
	var s = '';
	for (i2=0; i2<a2.length-1; i2++)
	{
		a3 = a2[i2].split('\t');
		s += '<tr><td class="link" onclick="location.href=\'building.php?id=' + a3[0] + '\'">' + building_type_name[a3[3]] + '</td><td class="link" onclick="info(\'' + a3[1] + '\')">' + a3[1] + '</td><td>' + round_ex(a3[4], 2) + '</td><td>&nbsp;' + euro(a3[2]) + '</td><td class="link" onclick="location.href=\'building.php?id=' + a3[0] + '\'">&gt;&gt;</td></tr>';
	}
//id, owner_name, salary, type
	
	return '<table style="width:100%;" cellspacing="0"><tr><th>Тип</th><th style="width:150px;">Владелец</th><th style="width:75px;">Ресурс</th><th style="width:75px;">Зарплата</th><th style="width:50px;">-</th></tr>' + s + '</table>';
}

////////////////////////////////////////////////////////////////////////////////

function textarea_value(id)
{
	var value = $(id).value;
	value = value.replace(/\x25/g, '%25');
	value = value.replace(/\x2B/g, '%2B');
	value = value.replace(/\x26/g, '%26');
	return value;
}

function get_value(id)
{
	var value = $(id).value;

	value=value.replace(/\x25/g, '%25');
	value=value.replace(/\x2B/g, '%2B');
	value=value.replace(/\x26/g, '%26');
	return value;
}

////////////////////////////////////////////////////////////////////////////////

function get_button(button)
{
	switch (button)
	{
	case 'buy': return bBuy; break;
	case 'sale': return bSale; break;
	case 'wear': return bWear; break;
	case 'info': return bInfo; break;
	}
}

////////////////////////////////////////////////////////////////////////////////

var bet_1 = ['00 и 0', '0 и 1', '0 и 2', '00 и 3', '00 и 2'];
var bet_2 = [,'0, 1 и 2', '0, 00 и 2', '00, 2 и 3'];

function bet_text(value, bet_type, half)
{
	var s = ' ';
	
	switch (bet_type)
	{
	case 0: s = 'Номер ' + (value == -1 ? '00' : value); break;
	case 1: s = (half ? 'Н' : 'Два н') + 'омера ' + (value > 0 ? (value < 100 ? value + ' и ' + (value + 1) : (value - 100) + ' и ' + (value - 97)) : bet_1[Math.abs(value)]); break;
	case 2: s = (half ? 'Н' : 'Три н') + 'омера ' + (value > 0 ? (value * 3 - 2) + ', ' + (value * 3 - 1) + ' и ' + (value * 3) : bet_2[Math.abs(value)]); break;
	case 3: s = (half ? 'Н' : 'Четыре н') + 'омера ' + value + ', ' + (value + 1) + ', ' + (value + 3) + ' и ' + (value + 4); break;
	case 4: s = (half ? 'Номера 00, 0, 1, 2 и 3' : 'Пять номеров 00, 0, 1, 2 и 3'); break;
	case 5: s = (half ? 'Номера' : 'Шесть номеров') + ' от ' + (value * 3 - 2) + ' до ' + (value * 3 + 3); break;
	case 6: s = value + '-ый ряд'; break; 
	case 7: s = value + '-ая дюжина'; break; 
	case 8: s = (value == 1 ? 'Красное' : 'Черное'); break; 
	case 9: s = (value == 1 ? 'Четные' : 'Нечетые'); break; 
	case 10: s = (value == 1 ? 'Числа от 1 до 18' : 'Числа от 19 до 36'); break; 
	}
	
	return s;
}

var red = ',1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36,'; 

function roulette_number(number)
{
	return '<span style="font-weight:bold; color:' + (number == '00' || number == '0' ? 'green' : (red.indexOf(',' + number + ',') != -1 ? 'red' : 'black')) + '">' + number + '</span>';
}

////////////////////////////////////////////////////////////////////////////////

var demand_id = 0;
var trauma = 1;
var team1 = 2;
var team1_level_min = 3;
var team1_level_max = 4;
var team1_num = 5;
var team1_count = 6;
var team2 = 7;
var team2_level_min = 8;
var team2_level_max = 9;
var team2_num = 10;
var team2_count = 11;
var create_time = 12;
var start_time = 13;
var demand_type = 14;
var timeout = 15;
var battle_id = 16;
var team_won = 17;
var comment = 18;
var world = 19;
var world_x = 20;
var world_y = 21;

var demand_type_name = ['Дуэль', 'Обычный', 'Равномерно', 'Каждый сам за себя', 'Хаотично', 'Вслепую'];

function template_demand(a, param)
{
	if (a[battle_id] > 0)
	{
		return '<div style="margin-top:3px;"><span class="date">' + (a[create_time] == '' ? format_date_time(a[start_time], 1) : format_timestamp(a[create_time])) + '</span>' + (a[trauma] > 0 ? ' <img src="/images/design/trauma_'+a[trauma]+'.gif" alt="Травматичность" /> ' : ' ') +
		(a[demand_type] == 0 || a[battle_id] > 0 ? '' : ' <b>[' + a[team1_count] + '/' + a[team1_num] + ' (' + a[team1_level_min] + '-' + a[team1_level_max] + ') <i>против</i> ' + a[team2_count] + '/' + a[team2_num] + ' (' + a[team2_level_min] + '-' + a[team2_level_max] + ')]</b> бой начнется через <b>' + format_time_left((a[start_time] < 0 ? 0 : parseInt(a[start_time])), 2, 1) + '</b><br /><span style="float:left; width:100%;"><span style="float:left; width:45%;">') +
		team(a[team1], (type_demand == 'finished' ? (a[team_won] == '1' ? 'won_1' : 'lost_1') : 1), '', param) + (a[team1_count] < a[team1_num] && a[battle_id] == 0 ? ' <span class="LeftArrow" style="position:absolute;margin-left:5px;cursor:pointer;" onclick="doLoad(\'action=join&team=1&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')"></span><span style="margin-left:33px;"></span>' : '') +
		(a[battle_id] > 0 ? (a[team2] == '' ? '' : ' против ') : (a[demand_type] == 0 ? ' против ' : '</span><span style="float:right; width:45%;">')) +
		team(a[team2], (type_demand == 'finished' ? (a[team_won] == '2' ? 'won_2' : 'lost_2') : 2), '', param) + (a[team2_count] < a[team2_num] && a[battle_id] == 0 ? ' <span class="LeftArrow" style="position:absolute;margin-left:5px;cursor:pointer;" onclick="doLoad(\'action=join&team=2&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')"></span><span style="margin-left:33px;"></span>' : '') +
		(a[demand_type] == 0 || a[battle_id] > 0 ? '' : '</span></span>') +
		(a[battle_id] > 0 ? ' <a href="/log.php?' + ((type_demand == 'finished') ? 'replay=1&' : '') + 'id=' + a[battle_id] + '" target="_blank" class="link">' + (type_demand == 'finished' ? 'смотреть' : 'наблюдать') + '</a> '+(a[world] == '1' ? '<b>Сектор '+a[world_x]+':'+a[world_y]+'</b>' : '') : '') + '</div>';
	}
	else if (a[demand_type] == 0)
	{
		return '<tr>' +
		'<td>' + team(a[team1], 1) + '</td>' +
		'<td>' + a[timeout] + '</td>' +
		'<td>' + a[team2_level_min] + '-' + a[team2_level_max] + '</td>' +
		'<td>' + a[comment] + '&nbsp;</td>' +
		'<td>' + team(a[team2], 1) + (a[team2] == '' ? '<input type="button" onclick="doLoad(\'action=join&team=2&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')" value="Вступить" />' : '') + '</td>' +
		'</tr>';
	}
	else
	{
		return '<tr>' +
		'<td>' + format_time_left((a[start_time] < 0 ? 0 : parseInt(a[start_time])), 2, 1) + '</td>' +
		'<td>' + a[team1_num] + (a[demand_type] > 2 ? '' : ' vs ' + a[team2_num]) + '</td>' +
		'<td>' + a[team1_level_min] + '-' + a[team1_level_max] + (a[demand_type] > 2 ? '' : ' vs ' + a[team2_level_min] + '-' + a[team2_level_max]) + '</td>' +
		'<td>' + demand_type_name[a[demand_type]] + '</td>' +
		'<td>' + a[timeout] + '</td>' +
		'<td>' + a[comment] + '&nbsp;</td>' +
		'<td>' + team(a[team1], 1) + '<input type="button" onclick="doLoad(\'action=join&team=1&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')" value="Вступить" /> ' + (a[demand_type] > 2 ? '' : ' vs ' + team(a[team2], 1) + '<input type="button" onclick="doLoad(\'action=join&team=2&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')" value="Вступить" /> ') + '</td>' +
		'</tr>';


/*		return '<div style="margin-top:3px;background-image:url(/images/design/ShopBG.jpg);" class="border">' + (a[create_time] == '' ? format_date_time(a[start_time], 1) : format_timestamp(a[create_time])) + ' | Таймаут <b>' + a[timeout] + '</b> сек ' + (a[trauma] > 0 ? ' <img src="/images/design/trauma_3.gif" /> ' : ' ') +
		'| <b><span class="team_1">' + a[team1_count] + '/' + a[team1_num] + ' (' + a[team1_level_min] + '-' + a[team1_level_max] + ')</span>' + (a[demand_type] > 2 ? '' : ' VS <span class="team_2">' + a[team2_count] + '/' + a[team2_num] + ' (' + a[team2_level_min] + '-' + a[team2_level_max] + ')</span>') + '</b> | начало через <b>' + format_time_left((a[start_time] < 0 ? 0 : parseInt(a[start_time])), 2, 1) + '</b><br />' +
		'<div class="hr"></div>' +
		'<input type="button" onclick="doLoad(window.location.href,\'action=join&team=1&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')" value="Вступить" /> ' + team(a[team1], 1) +
		(a[demand_type] > 2 ? '' : '<div class="hr"></div>' +
			'<input type="button" onclick="doLoad(window.location.href,\'action=join&team=2&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')" value="Вступить" /> ' + team(a[team2], 2)
		) +
		'</div>';*/
	}

/*
Начало боя:	
Количество	
Уровни	
Тип	
Таймер	
Описание	
Участники
*/

/*	return '<div style="margin-top:3px;">' + (a[create_time] == '' ? format_date_time(a[start_time], 1) : format_timestamp(a[create_time])) + (a[trauma] > 0 ? ' <img src="/images/design/trauma_3.gif" /> ' : ' ') +
	(a[demand_type] == 0 || a[battle_id] > 0 ? '' : ' <b>[' + a[team1_count] + '/' + a[team1_num] + ' (' + a[team1_level_min] + '-' + a[team1_level_max] + ') <i>против</i> ' + a[team2_count] + '/' + a[team2_num] + ' (' + a[team2_level_min] + '-' + a[team2_level_max] + ')]</b> бой начнется через <b>' + format_time_left((a[start_time] < 0 ? 0 : parseInt(a[start_time])), 2, 1) + '</b><br /><span style="float:left; width:100%;"><span style="float:left; width:45%;">') +
	team(a[team1]) + (a[team1_count] < a[team1_num] && a[battle_id] == 0 ? ' <span class="LeftArrow" style="position:absolute;margin-left:5px;cursor:pointer;" onclick="doLoad(window.location.href,\'action=join&team=1&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')"></span><span style="margin-left:33px;"></span>' : '') +
	(a[battle_id] > 0 ? ' против ' : (a[demand_type] == 0 ? (a[team2_count] == 1 ? ' Заявка принята ' : ' Ожидает соперника ') : '</span><span style="float:right; width:45%;">')) +
	team(a[team2]) + (a[team2_count] < a[team2_num] && a[battle_id] == 0 ? ' <span class="LeftArrow" style="position:absolute;margin-left:5px;cursor:pointer;" onclick="doLoad(window.location.href,\'action=join&team=2&demand_id=' + a[demand_id] + '&type=' + a[demand_type] + '\')"></span><span style="margin-left:33px;"></span>' : '') +
	(a[demand_type] == 0 || a[battle_id] > 0 ? '' : '</span></span>') +
	(a[battle_id] > 0 ? ' <a href="/log.php?' + ((type_demand == 'finished') ? 'replay=1&' : '') + 'id=' + a[battle_id] + '" target="_blank" class="link">' + (type_demand == 'finished' ? 'смотреть' : 'наблюдать') + '</a>' : '') + '</div>';
*/
}

////////////////////////////////////////////////////////////////////////////////

function processdata(responseText)
{
	var a1 = responseText.split('\n\n');
	for (i1 = 0; i1 < a1.length; i1++)
	{
		a2 = a1[i1].split('\n');
		if (a2.length > 1)
		{
			switch (a2[0])
			{
/* системное сообщение  */

			case 'sys_msg':
				a3 = a2[1].split('\t');
				
				if (a3[1] == undefined)
				{
					top.frames['chatline'].sys_msg(a3[0]);
				}
				else
				{
					top.frames['chatline'].sys_msg(a3[0], a3[1]);
					if (top.frames['chatline'] != window)
					{
						top.CHAT.output_messages();
					}
				}
				break;

			case 'status_msg':
				a3 = a2[1].split('\t');
				show_status(a3[0]);
				if (a3[1] == 1)
				{
					scroll(0,0);
				}
				break;

/* чатом */

			case 'online':
				a3 = a2[1].split('\t');
				top.frames['chatonline'].$('idChatLocation').innerHTML = a3[2] + ' [<span class="link header1" onclick="window.open(\'/where.php?room=' + a3[0] + '\',\'\',\'width=600,height=500\')">' + a3[3] + '</span>/<span class="link header1" onclick="window.open(\'/where.php\',\'\',\'width=600,height=500\')">' + a3[1] + '</span>]';

				online_user_list = [];
				for (i2=2; i2<a2.length - 1; i2++)
				{
					online_user_list[i2 - 2] = a2[i2].split('\t');
				}

				set_online_filter();
				if (top.frames['main'].$)
				{
					update_online(a3[1]);
				}
				break;
				
			case 'nologin':
				location.href = '/?nologin';
				break;
			case 'shuted':
				a3 = a2[1].split('\t');
				sys_msg('Вам запрещено общение! ' + formatTimeLeft(a3[0]) + '. Причина: <i>' + msg(a3[1]) + '</i>', a3[2]);
				break; 
			case 'error':
				sys_msg(a2[1]);
				break;

			case 'chat_O':
				chat_mode_refresh[0] = parseInt(a2[1]);
				for (i2=2; i2<a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');

					txt = '<font class="date' + (check_name(a3[1], a3[2]) ? 'M' : 'O') + '">' + format_timestamp(a3[3]) + '</font> ' +
						(a3[1] != '' ? format_names('[' + a3[1] + ']', 1, 0) : '') +
						msg(format_names(a3[2]), 1) + '<br />';

					top.CHAT.add_buffer_message(txt, a3[3]);

					chat_mode_refresh[0] = Math.max(chat_mode_refresh[0], parseInt(a3[0]));
				}
				break;
			case 'chat_L':
				for (i2=1; i2<a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');

					txt = '<font class="dateL">' + format_timestamp(a3[3]) + '</font> ' +
						(a3[1] != '' ? format_names('[' + a3[1] + ']', 1, 1) : '') +
						msg(format_names(a3[2], 0, 1), 1) + '<br />';

					top.CHAT.add_buffer_message(txt, a3[3]);

					chat_mode_refresh[1] = Math.max(chat_mode_refresh[1], parseInt(a3[0]));
				}
				break;
				
/* персонаж в бою */
				
			case 'in_battle':	
				//if (top == window)
				//{
					//if (iframe_href != '/battle.php')
				//	{
				//		top.$('main').src = '/battle.php';
				//	}
			//	}
			//	else
			//	{
					location.href = '/battle.php';
			//	}
				break;

			case 'backpack':
				txt = '';
				var count = 0;
				var t_amount = 1;
				var t_image = 3;
				
//				arr = new Array("action=wear&thing_id=");
				for (i2 = 1; i2 < a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');
					txt += ',' + a3[t_image] + ',' + a3[t_amount];
					//arr.push(a3[t_thing_id]);
					count++;
				}
				
				var h = Math.ceil(count / 7);
				txt = '7,' + h + ',2,2,68,1,0' + txt;
				h = h * 72 - 2;
						
				var f = $f('backpack');
				f.style.height = h + 'px';
				f.thing_update(txt);
				
				//InvContainer.swfData("backpack", "thing", "3," + Math.ceil((a2.length - 2) / 7) + ",2,2,50,1,0" + s, arr);

				/*USER.wear_on = a2[1].split('\t');
				USER.wear_on_list = ',' + USER.wear_on.valueOf() + ',';
				for (i = 0; i < 9; i++)
				{
					if (USER.wear_on[i] == 0 && USER.slot[i] != 0 || i == 5)
					{
						USER.slot[i] = 0;
						wear_slot(i + 1,'design/slot'+((i == 5 ? 3 : i) + 1))
					}
				}*/
				break;

			case 'wear_on':
				txt = '';
				
			/*	var count = 0;
				
				for (i2=2; i2<a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');

					user_thing_visible = USER.wear_on_list.indexOf(',' + a3[2] + ',');
	
					if (user_thing_visible != -1)
					{
						if (button == bWear || button == bInfo)
						{
							thing_slot = 0;
							while (thing_slot <= 9 && USER.wear_on[thing_slot] != a3[2])
							{
								thing_slot++;
							}


						//	if (top.USER.wear_on[thing_slot] == a3[2] && top.USER.slot[thing_slot] != top.USER.wear_on[thing_slot])
						//	{
								USER.slot[thing_slot] = a3[2];
	
								wear_slot(thing_slot + 1, a3[3], 1);
								//if (thing_slot + 1 == 4)
								//{
								//	USER.slot[5] = a3[2];
								//	USER.wear_on[5] = a3[2];
								//	wear_slot(6, a3[3], 1, 1);
								//} 

						//	}
						}
					}
					else
					{
						txt += ',' + (a3[id] > 11 ? '1' : a3[id]) + ',' + a3[amount];
						count++;
					}
				}*/
				
				var t_amount = 1;
				var t_image = 3;
				var t_slot = 5;
				
				arr = ['n,0', 'n,0', 'n,0', 'n,0', 'n,0', 'n,0', 'n,0', 'n,0', 'n,0'];
							
				for (i2 = 1; i2 < a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');
					arr[a3[t_slot] - 1] = a3[t_image] + ',' + a3[t_amount];
				}
							
				txt = '3,3,8,25,50,1,0,' + arr.join(',');
//				$('id_bag').style.height = h + 'px';

				var f = $f('thing');
//				f.style.height = h + 'px';
				f.thing_update(txt);
				
				/*
				var button = get_button(a2[1]);
				for (i2=2; i2<a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');


					user_thing_visible = USER.wear_on_list.indexOf(',' + a3[2] + ',');
	
					if (user_thing_visible != -1)
					{
						if (button == bWear || button == bInfo)
						{
							thing_slot = 0;
							while (thing_slot <= 9 && USER.wear_on[thing_slot] != a3[2])
							{
								thing_slot++;
							}


						//	if (top.USER.wear_on[thing_slot] == a3[2] && top.USER.slot[thing_slot] != top.USER.wear_on[thing_slot])
						//	{
								USER.slot[thing_slot] = a3[2];
	
								wear_slot(thing_slot + 1, a3[3], 1);
								//if (thing_slot + 1 == 4)
								//{
								//	USER.slot[5] = a3[2];
								//	USER.wear_on[5] = a3[2];
								//	wear_slot(6, a3[3], 1, 1);
								//} 

						//	}
						}
					}
					else
					{
						txt += template_thing(a3, 1, button);
					}
				}

				if (txt == '')
				{
					switch (button)
					{
					case bSale:	txt = '<div style="border:#CCCCCC 1px solid; background:white; color:#777777; margin:0 120px 0 0; padding:60px 0 60px 0; text-align:center; font-weight:bold; font-size:1.5em;">У Вас нет вещей для продажи.</div>'; break;
					case bWear:	txt = '<div style="border:#A2C394 1px solid; padding:60px 0 60px 0; text-align:center; margin-right:2px; font-size:1.5em;">Ваша сумка пуста</div>'; break;
					}
				}
				
				if (button != bInfo)
				{
					$((button == bWear ? 'id_bag_content' : 'id_container')).innerHTML = txt;
					//scroll(0,0);
				}*/
				break;
			case 'user_resource':
				USER.load_resource(a2[1]);
				$('id_user_resource').innerHTML = USER.get_resource();
				break;
			case 'user_data':
				a3 = a2[1].split('\t');
				USER.load_user_data(a3);
				USER.refresh_user_data();
				break;
			case 'user_exp':
				a3 = a2[1].split('\t');
				USER.refresh_user_exp(a3);
				break;
			case 'building':
				a3 = a2[1].split('\t');
				$('id_building').innerHTML = template_building(a3, a2[2]);
				break;
			case 'building_work':
				a3 = a2[1].split('\t');
				$('id_building_work').innerHTML = template_work('', a3[1]);
				break;

/* рынок... */

			case 'exchange':
				var txt = '';
				for (i2=1; i2<a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');
					txt += template_exchange(a3);
				}

				if (txt == '')
				{
					switch (selected_tab)
					{
						case 1:	txt = '<div class="info_msg" style="margin:5px 60px 0 60px; padding:60px 0 60px 0; text-align:center; font-size:1.5em;">В данной категории товаров нет.</div>'; break;
						case 4:	txt = '<div class="info_msg" style="margin:5px 60px 0 60px; padding:60px 0 60px 0; text-align:center; font-size:1.5em;">У Вас нет выставленных лотов.</div>'; break;
					//case 1:	txt = '<div style="border:#CCCCCC 1px solid; background:white; color:#777777; margin:5px 60px 0 60px; padding:60px 0 60px 0; text-align:center; font-weight:bold; font-size:1.5em;">В данной категории товаров нет.</div>'; break;
					//case 4:	txt = '<div style="border:#CCCCCC 1px solid; background:white; color:#777777; margin:5px 60px 0 60px; padding:60px 0 60px 0; text-align:center; font-weight:bold; font-size:1.5em;">У Вас нет выставленных лотов.</div>'; break;
					}
					$('id_content').innerHTML = txt;
				}
				else
				{
					$('id_content').innerHTML = '<table style="width:100%;margin-top:5px;" cellspacing="0"><tr><th style="width:270px;">Название</th><th style="width:150px;">-</th><th style="width:100px;">Цена</th><th style="width:100px;">До окончания осталось</th><th style="width:120px;">-</th></tr>' + txt + '</table>';
				}

				break;
			case 'exchange_rate':
				exchange_rate = ',' + a2.slice(1, -1).toString() + ','; 
				break;
			case 'exchange_thing':
				var id_list = $('id_res_thing_list');
				id_list_length = id_list.options.length;
				while (0 < id_list_length--)
				{
					id_list.remove(0);
				}
				
				for (i2=1; i2<=6; i2++)
				{
					if (USER.resource[i2] > 0)
					{
						id_list.options[id_list.options.length] = new Option(USER.resource_name[i2] + ' (' + USER.resource[i2] + ') € 30', i2);
					}
				}
				id_list.options[id_list.options.length] = new Option('-----', '*');

				for (i2=1; i2<a2.length - 1 ; i2++)
				{
					a3 = a2[i2].split('\t');
					id_list.options[id_list.options.length] = new Option(a3[1] + ' [' + a3[3] + '/' + a3[4] + '] € ' + round_ex(a3[5], 2), a3[0]);
				}
	
				id_list.selectedIndex = 0;
				break;
			case 'exchange_tree':
				exchange_tree = [];
				for (i2=2; i2<a2.length-1; i2++)
				{
					a3 = a2[i2].split('\t');
					exchange_tree[a3[1]] = a3[0];
				}
				make_exchange_tree(a2[1]);
				break;
			case 'exchange_node':
				a3 = a2[1].split('\t');
				exchange_tree_category = a3[0];
				exchange_node_id = a3[1];

				exchange_node = [];
				for (i2=2; i2<a2.length-1; i2++)
				{
					exchange_node[exchange_node.length] = a2[i2].split('\t');
				}
				break;
			case 'exchange_my':
				var s = '';
				for (i2=a2.length-1; i2>0; i2--)
				{
					a3 = a2[i2].split('\t');
					switch (a3[8])
					{
					case 'add': s += '<span class="textG">' + format_date_time(a3[9], 1) + '</span> Выставлен на продажу лот <span class="link" onclick="exchange_log(' + a3[0] + ')">#' + a3[0] + '</span> "' + (a3[1] > 6 ? '<span class="link" onclick="show_thing(' + a3[1] + ', 0)">' + a3[2] + '</span>' : a3[2]) + '" ' + (a3[2] > 0 ? '[' + a3[3] + '/' + a3[4] + ']' : '') + ' кол-во <b>' + a3[7] + '</b> шт, ' + euro(a3[5] / a3[7], 1) + ' за 1 шт<br />'; break;
					case 'del': s += '<span class="textG">' + format_date_time(a3[9], 1) + '</span> Снят лот <span class="link" onclick="exchange_log(' + a3[0] + ')">#' + a3[0] + '</span> "' + (a3[1] > 6 ? '<span class="link" onclick="show_thing(' + a3[1] + ', 0)">' + a3[2] + '</span>' : a3[2]) + '" ' + (a3[2] > 0 ? '[' + a3[3] + '/' + a3[4] + ']' : '') + ' кол-во <b>' + a3[7] + '</b> шт<br />'; break;
					case 'buy': s += '<span class="textG">' + format_date_time(a3[9], 1) + '</span> Куплен лот <span class="link" onclick="exchange_log(' + a3[0] + ')">#' + a3[0] + '</span> "' + (a3[1] > 6 ? '<span class="link" onclick="show_thing(' + a3[1] + ', 0)">' + a3[2] + '</span>' : a3[2]) + '" ' + (a3[3] > 0 ? '[' + a3[3] + '/' + a3[4] + ']' : '') + ' кол-во <b>' + a3[7] + '</b> шт, ' + euro(a3[5] / a3[7], 1) + ' за 1 шт<br />'; break;
					case 'flash': s += '<span class="textG">' + format_date_time(a3[9], 1) + '</span> Куплен лот <span class="link" onclick="exchange_log(' + a3[0] + ')">#' + a3[0] + '</span> "' + (a3[1] > 6 ? '<span class="link" onclick="show_thing(\'\',' + a3[1] + ')">' + a3[2] + '</span>' : a3[2]) + '" ' + (a3[4] > 0 ? '[' + a3[3] + '/' + a3[4] + ']' : '') + ' кол-во <b>' + a3[7] + '</b> шт, по блиц цене ' + euro(a3[5] / a3[7], 1) + ' за 1 шт<br />'; break;
					}
				}
			
				if (s == '')
				{
					s = '<div class="info_msg" style="margin:5px 60px 0 60px; padding:60px 0 60px 0; text-align:center; font-size:1.5em;">У Вас нет биржевых операций.</div>'; 
				}

				$('id_exchange_my_log').innerHTML = s;
				break;
			case 'stat_now':
				var s = '';
				
				a3 = a2[1].split('\t');
				s += 'Число выставленных лотов обычной формы продажи <b>' + a3[0] + '</b>, их общая цена ' + euro(a3[1], 1) + '<br />';
				
				a3 = a2[2].split('\t');
				s += 'Число выставленных лотов аукционной формы продажи <b>' + a3[0] + '</b>, сумма их текущих цен ' + euro(a3[1], 1) + '<br />';

				a3 = a2[3].split('\t');
				s += 'Число сделок, совершенных за день <b>' + a3[0] + '</b>, их общая цена ' + euro(a3[1], 1) + ', налог с них ' + euro(a3[2], 1) + '<br />';

				a3 = a2[4].split('\t');
				s += 'Число сделок, совершенных за предыдущий день <b>' + a3[0] + '</b>, их общая цена ' + euro(a3[1], 1) + ', налог с них ' + euro(a3[2], 1) + '<br />';

				$('id_exchange_stat').innerHTML = s;
				break;
			case 'stat':
				var s = '';
				for (i2=1; i2<a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');
					s += '<tr><td style="color:#A58653; font-weight:bold;">' + format_date_time(a3[0]) + '</td><td>' + a3[1] + '</td><td>' + euro(a3[2], 1) + '</td><td>' + euro(a3[4] / a3[1], 1) + '</td><td>' + euro(a3[3], 1) + '</td></tr>'; 
				}

				$('id_exchange_stat').innerHTML = '<table style="width:100%;margin-top:5px;" cellspacing="0"><tr><th style="width:150px;">Дата</th><th style="width:170px;">Сделок за сутки</th><th>Мин. цена</th><th>Ср. цена</th><th>Макс. цена</th></tr>' + s + '</table>';
				break;

/* перемещение по карте... */

			case 'wait':
				$('id_sector').style.display = 'none';
				$('id_map_move').style.display = 'none';
				$('id_to_sector_name').innerHTML = a2[1];
				wait_time_left = a2[2];
				refresh_time();
				$('id_moving').style.display = 'block';
				break;
			case 'building_list':
				$('id_moving').style.display = 'none';
				sector = a2[1].split('\t');
				refresh_sector();
				$('id_sector_name').innerHTML = sector[0] + '_' + sector[1];
				$('id_list').innerHTML = template_building_list(a2.slice(2));
				$('id_sector').style.display = 'block';
				$('id_map_move').style.display = 'block';
			case 'select_sector':
				$('id_moving').style.display = 'none';
				select_sector = a2[1].split('\t');
				refresh_sector();
				$('id_sector_name').innerHTML = select_sector[0] + '_' + select_sector[1];
				$('id_list').innerHTML = template_building_list(a2.slice(2));
				$('id_sector').style.display = 'block';
				$('id_map_move').style.display = 'block';
				break;

/* рулетка... */

			case 'bet_my':
				bet_my(a2);
				break;
			case 'bet_all':
				bet_all(a2);
				break;
			case 'bet_stat':
				bet_stat(a2);
				break;
			case 'server_time':
				$('id_server_time').innerHTML = a2[1];
				break;

/* армия... набор */
				
			case 'army':
				alert(a2[1] + "|" + a2[2].split('\t'));
				break;
			case 'user_army':
				a3 = a2[2].split('\t');
				txt = '';
							
				for (i3 = 0; i3 < 7; i3++)
				{
					if (a3[i3] != '0')
					{
						txt += ',unit' + a2[1] + (i3 + 1) + ',' + a3[i3];
					}
				}
				
				txt = '7,1,2,2,56,0,1' + txt;

				var f = $f('army');
				f.thing_update(txt);
				
				break;
			case 'recruitarmy':
				a3 = a2[1].split('\t');
				for (i3=0; i3<2; i3++)
				{
					trackbar.getObject('recruit_' + (i3 + 1)).updateValue(a3[i3]);
				}					
				break;
			case 'recruitarmy_info':
				a3 = a2[1].split('\t');
				creature(a3);
				break;

/* почта... */

			case 'mailbox':
				var txt = '';
				for (i2=2; i2<a2.length - 1; i2++)
				{
					a3 = a2[i2].split('\t');
					txt += template_mail(a3, a2[1], i2 - 1);
				}
				mail_count = a2.length - 3;
				$('id_mailbox').innerHTML = '<table style="width:100%; margin-bottom:5px;" cellspacing="0"><tr><th style="width:30px;">-</th><th style="width:200px;">Дата</th><th style="width:100px;">' + (a2[1] == 'in' ? 'Отправитель' : 'Адресат') + '</th><th>Заголовок</th></tr>' + txt + '</table>' +
				'<input type="button" class="button" onclick="select_all()" value="Выделить все" /> <input type="button" class="button" onclick="delete_selected(\'' + a2[1] + '\')" value="Удалить выделенное" />';
				$('id_new_mail').style.display = 'none';
				$('id_mailbox').style.display = 'block';
				break;	
			case 'mail':
				var s = '';
				a3 = a2[2].split('\t');
				$('id_new_mail').style.display = 'none';
				$('id_mailbox').style.display = 'block';
				s = '<div style="background:white; border:#CCCCCC 1px solid; margin-bottom:5px; padding:3px;">Дата: ' + format_date_time(a3[5], 1) + '<br />' +
					'От: ' + a3[2] + '<br />' +
					'Кому: ' + a3[3] + '<br />' +
					'Тема: ' + a3[4] + '<br />' +
					'<div class="input">' + a3[6] + '</div></div>'+
					(a2[1] == 'in' ? '<input type="button" class="button" onclick="reply_mail(' + a3[0] + ',\'' + a3[2] + '\',\'' + a3[4] + '\')" value="Ответить" /> ' : '') + '<input type="button" class="button" onclick="delete_mail(\'' + a2[1] + '\', ' + a3[0] + ')" value="Удалить" />' + (a2[1] == 'in' ? ' <input type="button" class="button" onclick="delete_mail(\'' + a2[1] + '\', ' + a3[0] + ', 1)" value="Удалить и автора вбаню" />' : '');

				for (i2=3; i2<a2.length-1; i2++)
				{
					a3 = a2[i2].split('\t');
					s += '<div style="background:white; border:#CCCCCC 1px solid; margin-top:5px; padding:3px;">Дата: ' + format_date_time(a3[5], 1) + '<br />' +
					'От: ' + a3[2] + '<br />' +
					'Кому: ' + a3[3] + '<br />' +
					'Тема: ' + a3[4] + '<br />' +
					'<div class="input">' + a3[6] + '</div></div>';
				}

				$('id_mailbox').innerHTML = s;
				show_status('');
				break;
				
/* арена... заявка */

			case 'demand':
			
				txt = '';
				for (i2=1; i2<a2.length-1; i2++)
				{
					a3 = a2[i2].split('\t');
					txt += template_demand(a3);
				}
				if (txt == '')
				{
					switch (type_demand)
					{
					case 0: s = 'В данном секторе одиночных заявок нет'; break;
					case 1: s = 'В данном секторе групповых заявок нет'; break;
					case 2: s = 'В данном секторе групповых заявок нет'; break;
					case 3: s = 'В данном секторе групповых заявок нет'; break;
					case 4: s = 'В данном секторе групповых заявок нет'; break;
					case 5: s = 'В данном секторе групповых заявок нет'; break;
					case 'fighting': s = 'В данном секторе текущих боев нет'; break;
					case 'finished': s = 'У данного игрока завершенных боев нет'; break;
					}
					txt = '<div style="margin:0 60px 0 60px; padding:60px 0 60px 0; text-align:center; font-weight:bold; color:#A58653; font-size:1.5em;"> '+s+' </div>';
				}
				else if (type_demand >= 0) 
				{
					txt = '<table style="width:100%;margin-bottom:15px;" cellspacing="0">' +
						'<tr>' +
						(type_demand == 0 ? 
							'<th>Игрок 1</th><th>Таймер</th><th>Уровни</th><th style="width:300px;">Описание</th><th>Игрок 2</th>'
							:
							'<th>Начало боя</th><th>Количество</th><th>Уровни</th><th>Тип</th><th>Таймер</th><th style="width:150px;">Описание</th><th style="width:300px;">Участники</th>'
						) +
						'</tr>' +
						txt +
						'</table>';
				}
				
				$('idDemands').innerHTML = '<br />' + txt + '<br />';
				break;
			case 'demand_status':
				a3 = a2[1].split('\t');
				
				$('id_create').className = a3[0] == '0' ? '' : 'hide';
				$('id_in_demand').className = a3[0] == '0' ? 'hide' : '';
				$('id_delete').className = a3[0] != '0' && a3[1] == '1' && a3[3] == '0' ? '' : 'hide';
				$('id_battle').className = a3[0] != '0' && a3[1] == '1' && a3[2] == '0' && a3[3] == '1' ? '' : 'hide';
				$('id_cancel').className = a3[0] != '0' && a3[2] == '0' && a3[3] == '1' ? '' : 'hide';
				
				type = a3[2];
				break;
				
			}
		}
	}
	
	if (top.frames['chatline'] == window)
	{
		top.CHAT.output_messages();
	}
}

function refresh_data()
{
	update_online(online);
	USER.load_resource(user_resource);
}