// $Id: common.js,v 1.156 2010-02-04 08:34:34 s.ignatenkov Exp $

var undefined;

Number.prototype.toFixed = Number.prototype.toFixed || function(fractionDigits){
	return Math.floor( this * Math.pow(10, fractionDigits) + .5) / Math.pow(10, fractionDigits)
};
function str_trim(str) {
	return str.replace(/^\s*/, "").replace(/\s*$/, "");
}
function array_filter(arr, fun) {
	var len = arr.length;
	if (typeof fun != "function")
		throw new TypeError();
	var res = new Array();
	var thisp = arguments[1];
	for (var i = 0; i < len; i++) {
		if (i in arr) {
			var val = arr[i];
			if (fun.call(thisp, val, i, arr))
				res.push(val);
		}
	}
	return res;
}
function array_unique (arr) {
	var res = [];
	var len = arr.length;
	for (var i = 0; i < len; i++) {
		for (var j = i + 1; j < len; j++) {
			if (arr[i] === arr[j]) {
				j = ++i;
			}
		}
		res.push(arr[i]);
	}
	return res;
}
function gebi(id){
	return document.getElementById(id)
}

function jsquote(str){
	return str.replace(/'/g,'&#39;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/&/g,'&amp;') //'
}

function copyBoard(obj, txt){
	if (document.body.createTextRange) { // IE
		var d=document.createElement('INPUT');
		d.type='hidden';
		d.value=txt;
		document.body.appendChild(d).createTextRange().execCommand("Copy");
		document.body.removeChild(d);
		return;
	} else try { // FireFox
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		var gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
		gClipboardHelper.copyString(txt);
	} catch (e) { // Google Chrome
		
	}
}

function getCoords(obj){
	var o=typeof(obj) == 'string' ? gebi(obj) : obj
	var ret={'l':o.offsetLeft,'t':o.offsetTop,'w':o.offsetWidth,'h':o.offsetHeight}
	while(o=o.offsetParent){
		ret.l+=o.offsetLeft
		ret.t+=o.offsetTop
	}
	return ret
}
var waitFuncId=0
function waitObj(id,evFunc){
	if(document.getElementById){
		if(typeof evFunc=='function'){
			window['waitFunc'+waitFuncId]=evFunc
			evFunc='waitFunc'+waitFuncId
			waitFuncId++
		}
		var obj=(id=='body')?document.body:document.getElementById(id)
		if(obj) window[evFunc]()
		else setTimeout("waitObj('"+id+"','"+evFunc+"')",100)
	}else{
		onload=evFunc
	}
}

function preloadImages() {
	var d = document;
	if(!d._prImg) d._prImg = new Array();
	var i, j = d._prImg.length, a = preloadImages.arguments;
	for (i=0; i<a.length; i++) {
		d._prImg[j] = new Image;
		d._prImg[j++].src = a[i];
	}
}

function checkbox_set(pfx, val) {
  var chk=document.getElementsByTagName('INPUT');
  for(var i=0;i<chk.length;i++){
    if(chk[i].name.indexOf(pfx)==0 || chk[i].getAttribute('grp')==pfx){
      chk[i].checked = (val == undefined ? !chk[i].checked: val);
    }
  }
}

// ==============================================================================

function showError(error) {
	return showMsg2("error.php?error="+error);
}

function luckyMsg(text, url) {
	var error_div = top.window.gebi('error_div');
	
	error_div.errorCloseCallback = function() {
		top.frames["main_frame"].frames["main"].location.href = url;
		error_div.errorCloseCallback = null;
	}
	
	showMsg2("error.php?error="+encodeURIComponent(text), "Сообщение");

}

function error_close() {
	try {
		var win = top.window;
		var obj = top.gebi('error');
		var div = top.gebi('error_div');
		if (!obj || !div) return false;
		obj.style.display = 'none';
		div.style.display = 'none';
		obj.src='';
		obj.width = 1;
		obj.height = 1;
		obj.style.left = 0;
		obj.style.top = 0;

		if (div.errorCloseCallback) {
			div.errorCloseCallback();
		}
		
	} catch(e) {}

	return true;
}

function showMsg2(url, title, w, h) {
	try {
		w=w||480;
		h=h||300;
		var win = top.window;
		var doc = top.document;
		var width = doc.body.clientWidth;
		var height = doc.body.clientHeight;
		var div_width = Math.max(doc.compatMode != 'CSS1Compat' ? doc.body.scrollWidth : doc.documentElement.scrollWidth,width);
		var div_height = Math.max(doc.compatMode != 'CSS1Compat' ? doc.body.scrollHeight : doc.documentElement.scrollHeight,height);
		var obj = top.gebi('error');
		var div = top.gebi('error_div');
		if (!obj || !div) return false;
		obj.src=url;
		
		div.style.width = div_width;
		div.style.height = div_height;
		
		obj.width = w;
		obj.height = h;
		obj.style.left = ((width-w)/2);
		obj.style.top = ((height-h)/2);
		div.style.display = 'block';
		obj.style.display = 'block';
		win.scrollTo(0,0);
//		obj = top.gebi('artifact_alt');
//		if (obj) obj.innerHTML='';
	} catch(e) {}
	return true;
}

function showMsg(url, title, w, h) {
	w=w||480
	h=h||300
	var win = top.window;
	if (win.showModelessDialog) {
		var sFeatures = 'dialogWidth:' + w + 'px; dialogHeight:' + h + 'px; center:yes; help:no; status:no; unadorned:yes; scroll:no;';
		return win.showModelessDialog("msg.php", {win: win, src: url, title: title}, sFeatures);
	} else {
		return win.open(url, "", 'width=' + w + ',height=' + h + ',location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no');
	}
}

function changeDivDisplay(div_id, display) {
	if (!div_id || !display) return false;
	div = gebi(div_id);
	if (!div) return false;
	div.style.display = display;
}

function showUserInfo(nick, server_url) {
	var url = "/user_info.php?nick="+nick;
	if (server_url) url = server_url+url;
	window.open(url, "", "width=920,height=700,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showArtifactInfo(artifact_id,artikul_id,set_id,evnt) {
	if (evnt && evnt.shiftKey && artifact_id) {
		chat_add_artifact_macros(artifact_id);
		return;
	}
	var url = "/artifact_info.php";
	if (artifact_id) url += "?artifact_id="+artifact_id;
	else if (artikul_id) url += "?artikul_id="+artikul_id;
	else if (set_id) url += "?set_id="+set_id;
	else return;
	window.open(url, "", "width=730,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showPetInfo(pet_id,artikul_id) {
	var url = "/pet_info.php";
	if (pet_id) url += "?pet_id="+pet_id;
	else if (artikul_id) url += "?artikul_id="+artikul_id;
	else return;
	window.open(url, "", "width=730,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showSmsForm(nick) {
	var url = "/area_post.php?&mode=sms&hide=1&nick=" + nick;
	window.open(url, "", "width=920,height=500,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function dialogEventCheck(event,param,close) {
	if (!param) param = '0';
	if (!top.dialogOn && event != 'FAQ' && event != null) return false;
	if (event) {
		var id = top.dialogEvent[event+'_'+param];
		if (id && id.length && id.length > 0) {
			for(var i=0;i<id.length;i++) {
				if (top.dialogShow[id[i]]) continue;
				var k = false;
				for(var j=0;j<top.dialogNeed.length;j++) {
					if (top.dialogNeed[j] == id[i]) {
						k = true;
						break;
					}
				}
				if (top.showNow == id[i]) k=true;
				if (!k) top.dialogNeed.push(id[i]); 
			}
		}
	}
	try {
		var div = top.frames['main_frame'].gebi('dialog_div');
		//var frame = top.frames['main_frame'].gebi('dialog_frame');
		if (div.style.display == 'none' || close) {
			var id = top.dialogNeed.shift();
			if (id) {
				updateSwf({'dialog': 'id='+id});
				//swfTransfer('id','dialog',id);
				//frame.src='tests.php?id='+id;
				div.style.display = '';
				if (id > 1) top.dialogShow[id] = id;
				top.showNow = id;
			} else {
				div.style.display = 'none';
				//frame.src='';
				top.showNow = 0;
			}
		}
	} catch(e) {}
}

function showFightInfo(fight_id, server_id) {
	var url = "/fight_info.php?fight_id="+fight_id;
	if (server_id) url += "&server_id="+server_id;
	window.open(url, "", "width=990,height=700,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
}
function showInstInfo() {
	var url = "/instance_stat.php";
	window.open(url, "", "width=990,height=700,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
}
function showInstanceInfo(instance_id, server_id) {
	var url = "/instance_stat.php?instance_id="+instance_id+'&outside=1';
	if (server_id) url += "&server_id="+server_id;
	window.open(url, "", "width=990,height=700,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
}
function showClanBattleInfo(clan_battle_id, server_id) {
	var url = "/clan_battle_info.php?clan_battle_id="+clan_battle_id+'&server_id='+server_id;
	window.open(url, "", "width=990,height=700,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
}
function showBotInfo(bot_id, artikul_id, fight_id) {
	var url = "/bot_info.php";
	if (bot_id) {
		if (fight_id) {
			url += "?fight_user_id="+bot_id+"&fight_id="+fight_id;
		} else {
			url += "?bot_id="+bot_id;
		}
	}	
	else if (artikul_id) url += "?artikul_id="+artikul_id;
	window.open(url, "", "width=915,height=700,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showPunishmentInfo(nick) {
	var url = "/punishment_info.php?nick="+nick;
	window.open(url, "", "width=730,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showInjuryInfo(nick) {
	var url = "/injury_info.php?nick="+nick;
	window.open(url, "", "width=730,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showEffectInfo(nick) {
	var url = "/effect_info.php?nick="+nick;
	window.open(url, "", "width=730,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showClanInfo(clan_id) {
	var url = "/clan_info.php?clan_id="+clan_id;
	window.open(url, "", "width=730,height=650,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showFriendsInfo() {
	var url = "/friend_list.php";
	window.open(url, "contacts", "width=730,height=650,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showAchievementInfo(achievement_id) {
	var url = "/achievement_info.php?id="+achievement_id;
	window.open(url, "", "width=730,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function userPrvTag() {
	var chatFrame = getChatFrame();
	try {
		for (i=0; i<arguments.length; i++) chatFrame.chatPrvTag(arguments[i]);
	}
	catch (e) {}	
}

function userToTag() {
	var chatFrame = getChatFrame();
	try {
		for (i=0; i<arguments.length; i++) chatFrame.chatToTag(arguments[i]);
	}
	catch (e) {}	
}


function userIgnore(name,status) {
	var chatFrame = getChatFrame();
	try {
		chatFrame.chatSyncIgnore(name,status);
	}
	catch (e) {}
}

function userAttack(nick, url_error) {
	var rnd = Math.floor(Math.random()*1000000000);
	var url_success = 'fight.php?'+rnd;
	var urlATTACK = 'action_run.php?code=ATTACK&url_success='+url_success+'&url_error='+escape(url_error||'area.php')+'&in[nick]='+(nick ? nick : '');
	try {
		if (!top.frames["main_frame"].frames["main"].__fight_php__) top.frames["main_frame"].frames["main"].location.href = urlATTACK;
	}
	catch (e) {}
}
function confirm_friend(url) {
	try {
		top.frames['main_frame'].frames['main_hidden'].location.href = url;
	}
	catch (e) {}
}

function confirm_bg(area_id) {
	try {
		top.frames['main_frame'].frames['main'].location.href = 'area_bgs.php?area_id=' + area_id + '&action=confirm';
	}
	catch (e) {}
}

function confirm_slaughter(area_id) {
	try {
		top.frames['main_frame'].frames['main'].location.href = 'area_bgs.php?area_id=' + area_id + '&action=confirm_slaughter';
	}
	catch (e) {}
}

function show_slaughter_stat(instance_id, finish, baseurl) {
	if (baseurl+'' == 'undefined') baseurl = '';
	var url = baseurl + 'instance_stat.php?outside=1&instance_id=' + instance_id + '&finish=' + finish;
	window.open(url, "", "width=730,height=550,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
//	try {
//		top.frames['main_frame'].frames['main'].location.href = 'instance_stat.php?instance_id=' + instance_id + '&finish=' + finish;
//	}
//	catch (e) {}
}

function getChatFrame() {
	var win = window
	try {win = dialogArguments || window} catch(e) {}
	while (win.opener) win = win.opener;
	if (win.closed) return;
	
	return win.top.frames['chat'];
}

function fightHelpRequest() {
	var chatFrame = getChatFrame();
	try {
		chatFrame.chatSendMessage('/FIGHTHELP');
	} catch(e) {}
}

// fight_id where `target_nick` need help  
function fightHelp(fight_id, target_nick, confirm_msg) {
	if (!confirm(confirm_msg + ' ' + target_nick + '?'))
		return;
	try {
	var rnd = Math.floor(Math.random()*1000000000);
	var err_url = top.frames["main_frame"].frames["main"].location;
	var url = 'action_run.php?code=FIGHT_HELP'+
			'&in[fight]=' + escape(fight_id) +
			'&in[target_nick]=' + target_nick +
			'&url_success=' + escape('fight.php?'+rnd) +  
			'&url_error=' + escape(err_url) +
			'&' + rnd;
		top.frames["main_frame"].frames["main"].location.href = url;
	}
	catch (e) {
	}
}

function botAttack(bot_id, url_error) {
	var rnd = Math.floor(Math.random()*1000000000);
	var url_success = 'fight.php?'+rnd;
	var urlATTACK = 'action_run.php?code=ATTACK_BOT&url_success='+url_success+'&url_error='+escape(url_error||'area.php')+'&bot_id='+bot_id;
	if (!bot_id) return;
	try {
		if (!top.frames["main_frame"].frames["main"].__fight_php__) top.frames["main_frame"].frames["main"].location.href = urlATTACK;
	}
	catch (e) {}
}

function huntAttack(bot_id) {
	botAttack(bot_id,'hunt.php');
}

function _background(obj, name) {
	if (obj.tagName == 'IMAGE') {
		obj.src = name;
	} else {
		obj.style.backgroundImage = 'url('+name+')'
	}
}

function getIframeShift(obj){
	var obj = obj || window;
	var ret={'l':0,'t':0};
	while(o=obj.frameElement){
		obj=obj.parent;
		ret.l+=o.offsetLeft - obj.document.body.scrollLeft;
		ret.t+=o.offsetTop - obj.document.body.scrollTop;
		while(o=o.offsetParent){
			ret.l+=o.offsetLeft;
			ret.t+=o.offsetTop;
		}
	}
	return ret;
}

function artifactAlt(obj, evnt, show) {
	var art_id = obj.getAttribute('div_id');
	var artifact_alt = top.gebi('artifact_alt');
	if (!artifact_alt) return;

	var act1 = obj.getAttribute('act1');
	var act2 = obj.getAttribute('act2');
	var act3 = obj.getAttribute('act3');
	if (act3 == 0) act3 = '' // костыль что бы не переименовывать картинки в локализациях
	if (show == 2) {
		document.onmousemove=function(e) {artifactAlt(obj, e||event, 1);}
		
		if (!artifact_alt.getAttribute('art_id') || obj.getAttribute('div_id') != artifact_alt.getAttribute('art_id')) {
			if (art_alt[art_id] && art_alt[art_id] != undefined) {
				artifact_alt.innerHTML = renderArtifactAlt(art_id);
			}
			artifact_alt.setAttribute('art_id',obj.getAttribute('div_id'));
		}
		
		artifact_alt.style.display = 'block';
		if (act1 || act2 || act3) {
			_background(obj, (top.locale_path + "images/itemact-"+ act1) + act2 + (act3 +".gif"));
		}
		
		top.obj = obj;
		if (top.show_alt) {
			top.show_alt();
		}
	}
	if (!show) {
		if (act1 || act2 || act3) {
			_background(obj, 'images/d.gif');
		}
		artifact_alt.style.display = 'none';
		document.onmousemove=function(){}
		return;
	}

	var coor = getIframeShift();
	var ex = evnt.clientX+coor.l;
	var ey = evnt.clientY+coor.t;

	if (top.noIframeAlt) {
		ex = evnt.clientX + top.document.body.scrollLeft;
		//ey = evnt.clientY + top.document.body.scrollTop + 200;
		ey = evnt.clientY + top.document.body.scrollTop;
	}

	if (act1 || act2 || act3) {
		obj.style.cursor = 'pointer'
		obj.onclick = (act1 != 0 ? function(e){try{artifactAct(obj, act1, e||event)}catch(e){}} : function(e){showArtifactInfo(obj.getAttribute('aid'), obj.getAttribute('art_id'), null, e||event)});
		_background(obj, (top.locale_path + "images/itemact-"+ act1) + act2 + (act3 + ".gif"));
		var coord = getCoords(obj)
		var cont = gebi("item_list")
		var rel_x = (ex + cont.scrollLeft - coord.l - coor.l)
		if (rel_x >= 40) {
			var rel_y = (ey + cont.scrollTop - coord.t - coor.t)
			if (rel_y < 20) {
				if (obj.getAttribute('store')) { // в магазине при клике на info необходимо выводить товар по артикулу
					obj.onclick = function(e){showArtifactInfo(false, obj.getAttribute('art_id'), null, e||event)};
				} else { 
					obj.onclick = function(e){showArtifactInfo(obj.getAttribute('aid'), null, null, e||event)}
				}
				_background(obj, top.locale_path + 'images/itemact_info' + act2 + (act3 + '.gif'));
				try{obj.style.cursor = 'hand'} catch(e){}
				try{obj.style.cursor = 'pointer'} catch(e){}
			}
			if (act2 != 0 && rel_y >= 40) {
				obj.onclick = function(e){try{artifactAct(obj, act2, e||event)}catch(e){}}
				_background(obj, top.locale_path + 'images/itemact_drop' + act2 + (act3 + '.gif'));
				try{obj.style.cursor = 'hand'} catch(e){}
				try{obj.style.cursor = 'pointer'} catch(e){}
			}
		}
		if (act3 > 0 && rel_x < 20) {
			var rel_y = (ey + cont.scrollTop - coord.t - coor.t);
			if (rel_y < 20) {
				obj.onclick = function(e){try{artifactAct(obj, act3, e||event)}catch(e){}};
				_background(obj, top.locale_path + 'images/itemact_use' + act2 + (act3 + '.gif'));
				try {obj.style.cursor = 'hand'} catch(e){}
				try {obj.style.cursor = 'pointer'} catch(e){}
			}
		}
	}
	var x = ex + artifact_alt.offsetWidth > top.document.body.clientWidth - 20 ? ex - artifact_alt.offsetWidth - 10 : ex + 10;
	var y = ey + artifact_alt.offsetHeight - top.document.body.scrollTop > top.document.body.clientHeight - 20 ? ey - artifact_alt.offsetHeight - 10 : ey + 10;

	if (x < 0 ) {
		x = ex - artifact_alt.offsetWidth/2;
	}
	if (x < 7 ) {
		x = 7;
	}
	if (x > top.document.body.clientWidth - artifact_alt.offsetWidth - 20) {
		x= top.document.body.clientWidth - artifact_alt.offsetWidth - 20;
	}

	artifact_alt.style.left = x;
	artifact_alt.style.top = y;
	return;
}

function userAlt(obj, evnt, show) {
	var soc_id = obj.getAttribute('soc_id');
	var soc_user_id = obj.getAttribute('soc_user_id');
	var user_alt = top.gebi('artifact_alt');
	if (!user_alt) return;

	if (show == 1) {
		document.onmousemove=function(e) {userAlt(obj, e||event, 1);}

		if (!user_alt.getAttribute('soc_id') || !user_alt.getAttribute('soc_user_id') || obj.getAttribute('soc_id') != user_alt.getAttribute('soc_id') || obj.getAttribute('soc_user_id') != user_alt.getAttribute('soc_user_id') ) {
			if (soc_user_alts[soc_id] && soc_user_alts[soc_id] != undefined || soc_user_alts[soc_user_id] && soc_user_alts[soc_user_id] != undefined) {
				user_alt.innerHTML = renderUserAlt(soc_id, soc_user_id);
			}
			user_alt.setAttribute('soc_id',obj.getAttribute('soc_id'));
			user_alt.setAttribute('soc_user_id',obj.getAttribute('soc_user_id'));
		}

		user_alt.style.display = 'block';
		
		top.obj = obj;
		if (top.show_alt) {
			top.show_alt();
		}
	}
	if (!show) {
		user_alt.style.display = 'none';
		document.onmousemove=function(){}
		return;
	}

	var coor = getIframeShift();
	var ex = evnt.clientX+coor.l;
	var ey = evnt.clientY+coor.t;

	if (top.noIframeAlt) {
		ex = evnt.clientX + top.document.body.scrollLeft;
		ey = evnt.clientY + top.document.body.scrollTop;
	}

	var x = ex + user_alt.offsetWidth > top.document.body.clientWidth - 20 ? ex - user_alt.offsetWidth - 10 : ex + 10;
	var y = ey + user_alt.offsetHeight - top.document.body.scrollTop > top.document.body.clientHeight - 20 ? ey - user_alt.offsetHeight - 10 : ey + 10;

	if (x < 0 ) {
		x = ex - user_alt.offsetWidth/2;
	}
	if (x < 7 ) {
		x = 7;
	}
	if (x > top.document.body.clientWidth - user_alt.offsetWidth - 20) {
		x= top.document.body.clientWidth - user_alt.offsetWidth - 20;
	}

	user_alt.style.left = x;
	user_alt.style.top = y;

	return;
}

function renderUserAlt(soc_id, soc_user_id) {
	var a = soc_user_alts[soc_id][soc_user_id];
	var content = '';
	
	content += '<table width="200" border="0" cellspacing="0" cellpadding="0" style="background-color:#FBD4A4;">';
	content += '<tr><td width="14" class="aa-tl"><img src="images/d.gif" width="14" height="24"><br></td>';
	content += '<td class="aa-t" align="center" style="vertical-align:middle"><b>' + a.name + '</b></td>';
	content += '<td width="14" class="aa-tr"><img src="images/d.gif" width="14" height="24"><br></td></tr>';
	content += '<tr><td class="aa-l" style="padding:0;"></td><td style="padding:0;">';
	content += '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center">';
	content += '<img src="' + a.avatar + '" alt="">';
	content += '</td></tr></table>';
	content += '</td><td class="aa-r" style="padding:0px"></td></tr>';
	content += '<tr><td class="aa-bl"></td><td class="aa-b"><img src="images/d.gif" width="1" height="5"></td><td class="aa-br"></td></tr>';
	content += '</table>';
	
	return content;
}

function renderArtifactAlt(id) {
	var a = art_alt[id];
	var bg = true;
	var i = 0;
	var content = '';

	content += '<table width="300" border="0" cellspacing="0" cellpadding="0" style="background-color:#FBD4A4;">';
	content += '<tr><td width="14" class="aa-tl"><img src="images/d.gif" width="14" height="24"><br></td>';
	content += '<td class="aa-t" align="center" style="vertical-align:middle"><b style="color:' + a.color + '">' + a.title + '</b></td>';
	content += '<td width="14" class="aa-tr"><img src="images/d.gif" width="14" height="24"><br></td></tr>';
	content += '<tr><td class="aa-l" style="padding:0;"></td><td style="padding:0;">';
	content += '<table width="275" style=" margin: 3px" border="0" cellspacing="0" cellpadding="0"><tr>';
	content += '<td align="center" valign="top" width="60">';
	content += '<table width="60" height="60" cellpadding="0" cellspacing="0" border="0" style="margin: 2px" background="' + a.image + '"><tr><td valign="bottom">';
	if (a.count && a.count != undefined) {
		content += '<div class="bpdig">' + a.count + '</div>';
	} else if (a.enchant_icon && a.enchant_icon != undefined) {
		content += a.enchant_icon;
	} else {
		content += '&nbsp;';
	}
	content += '</td></tr></table>';
	content += '</td><td>';
	content += '<div><img src="images/tbl-shp_item-icon.gif" width="11" height="10" align="absmiddle">&nbsp;' + a.kind + '</div>';
	if (a.dur && a.dur != undefined) {
		content += '<div><img src="images/tbl-shp_item-iznos.gif" width="11" height="10" align="absmiddle"> <span class="red">' + a.dur + '</span>/' + a.dur_max + '</div>';
	}
	if (a.price && a.price != undefined) {
		content += '<div class="b red">' + a.price + '</div>';
	}
	if (a.com && a.com != undefined) {
		content += '<div class="b red">' + a.com.title + ' ' + a.com.value + '</div>';
	}
	if (a.owner && a.owner != undefined) {
		content += '<div><b class="b red">' + a.owner.title + '</b>' + a.owner.value + '</div>';
	}
	content += '</td><td>';
	if (a.lev && a.lev != undefined) {
		content += '<div><img src="images/tbl-shp_level-icon.gif" width="11" height="10" align="absmiddle"> ' + a.lev.title + ' <b class="red">' + a.lev.value + '</b></div>';
	}
	if (a.trend && a.trend != undefined) {
		content += '<div><img src="images/tbl-shp_item-trend.gif" width="11" height="10" align="absmiddle">&nbsp;' + a.trend + '</div>';
	}
	if (a.cls && a.cls != undefined) {
		content += '<div><img src="images/class.gif" width="11" height="10" align="absmiddle"> ';
		for (i in a.cls) {
			content += a.cls[i];
		}
		content += '</div>'
	}
	content += '</td></tr></table>';
	content += '<table width="100%" cellpadding="0" cellspacing="0" border="0">';
	if (a.skills && a.skills != undefined) {
		for (i in a.skills) {
			content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td>' + a.skills[i].title + '</td><td class="red" align="right">' + a.skills[i].value + '</td></tr>';
			bg = !bg;
		}
	}
	if (a.skills_e && a.skills_e != undefined) {
		for (i in a.skills_e) {
			content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td>' + a.skills_e[i].title + '</td><td class="red" align="right">' + a.skills_e[i].value + '</td></tr>';
			bg = !bg;
		}
	}
	if (a.enchant && a.enchant != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td>' + a.enchant.title + '</td><td class="red" align="right">' + a.enchant.value + '</td></tr>';
		bg = !bg;
	}
	if (a.enchant_mod && a.enchant_mod != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td>' + a.enchant_mod.title + '</td><td class="red" align="right">' + a.enchant_mod.value + '</td></tr>';
		bg = !bg;
	}
	if (a.set && a.set != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td>' + a.set.title + '</td><td class="red" align="right">' + a.set.value + '</td></tr>';
		bg = !bg;
	}
	if (a.exp && a.exp != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td>' + a.exp.title + '</td><td class="grnn b" align="right">' + a.exp.value + '</td></tr>';
		bg = !bg;
	}
	if (a.change && a.change != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td colspan="2" class="redd b">' + a.change + '</td></tr>';
		bg = !bg;
	}
	if (a.boe && a.boe != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td colspan="2" class="redd b">' + a.boe + '</td></tr>';
		bg = !bg;
	}
	if (a.note && a.note != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td colspan="2">' + a.note + '</td></tr>';
		bg = !bg;
	}
	if (a.engrave && a.engrave != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td colspan="2">' + a.engrave + '</td></tr>';
		bg = !bg;
	}
	if (a.desc && a.desc != undefined) {
		content += '<tr class="skill_list ' + (bg ? 'list_dark' : '') + '"><td colspan="2">' + a.desc + '</td></tr>';
		bg = !bg;
	}
	content += '</table>';
	content += '</td><td class="aa-r" style="padding:0px"></td></tr>';
	content += '<tr><td class="aa-bl"></td><td class="aa-b"><img src="images/d.gif" width="1" height="5"></td><td class="aa-br"></td></tr>';
	content += '</table>';

	return content;
}

function updateBag() {
	var win = window
	try {win = dialogArguments ?  dialogArguments.win || dialogArguments : window} catch(e) {}
	while (win.opener) win = win.opener;
	if (win.closed) return false;
	
	try{
		var win_main = win.top.frames['main_frame'].frames['main']
		if(win_main.is_userphp) {
				win_main.location.href = win_main.urlMODE + '&update_swf=1'
			return true;	
		}
	}
	catch (e) {}
	return false;
}
function updateSwf(params) {
	var win = window
	try {win = dialogArguments ?  dialogArguments.win || dialogArguments : window} catch(e) {}
	while (win.opener) win = win.opener;
	if (win.closed) return;
	
	var url = 'main_iframe.php?mode=update_swf';
	if (!params) return;
	try {
		for (i in params) {
	  		url += '&tar[]='+i;
	  		if (params[i]) url += '&add['+i+']='+escape(params[i]);
		}
		win.top.frames['main_frame'].frames['main_hidden'].location.href = url;
	}
	catch (e) {}
}

function updateHP() {
	updateSwf({'lvl': '' ,'items': ''});
}
function fightRedirect(fight_id, cd) {
	if (!cd || isNaN(cd)) cd = false;
	else {
		setTimeout(function(){
			fightRedirect(fight_id);
		}, cd);
		return;
	}
	var rnd = Math.floor(Math.random()*1000000000);
	var url = 'fight.php?'+rnd;
	if (top.__lastFightId && (top.__lastFightId >= fight_id)) return;
	top.__lastFightId = fight_id;
	top.frames["main_frame"].frames["main"].location.href = url;
}

function updatePartyLoot() {
	try {
		top.frames['main_frame'].frames['main_hidden'].location.href = 'main_iframe.php?mode=update_party';
	} catch (e) {};
}

function fightUpdateLog(ctime, nick1, level1, nick2, level2, code, i1, i2, i3, s1) {
	try {
		top.frames['main_frame'].frames['main'].fightUpdateLog(ctime, nick1, level1, nick2, level2, code, i1, i2, i3, s1);
	} catch (e) {};
}

function resurrect() {
	top.frames["main_frame"].frames["main"].location.href = 'action_run.php?code=RESURRECT&url_success=area.php&url_error=area.php';
	}

// =======================================================================================

function js_money_input_assemble(id_prefix) {
	var m1 = gebi(id_prefix+'1').value;
	var m2 = gebi(id_prefix+'2').value;
	var m3 = gebi(id_prefix+'3').value;

	if (m1.match(/[^0-9.]/)) m1 = m1.replace(/[^0-9].*$/, '');
	if (m2.match(/[^0-9.]/)) m2 = m2.replace(/[^0-9].*$/, '');
	if (m3.match(/[^0-9.]/)) m3 = m3.replace(/[^0-9].*$/, '');
	v = m1/100.0 + m2*1.0 + m3*100.0;
	res = (isNaN(v) || v <= 0) ? 0 : (1.0 * (1.0*v).toFixed(2)).toFixed(2);
	return res*1.0;
}

function js_money_input_fill(id_prefix, amount) {
	var m1 = gebi(id_prefix+'1');
	var m2 = gebi(id_prefix+'2');
	var m3 = gebi(id_prefix+'3');

    var str = ' ';
	var t=[];
	amount = amount * 100;
	for (i = 0; i < 2; i++) {
		t[i] = (amount % 100);
		amount = (amount - t[i]) / 100;
	}
	t[2] = amount;
	m1.value = t[0].toFixed(0);
	m2.value = t[1].toFixed(0);
	m3.value = t[2].toFixed(0);
}

// ========= swf data transfer functions ===============================================================

function getSWF(name) {
	var win = window;
	try {win = dialogArguments || window} catch(e) {}
	while (win.opener) win = win.opener;
	if (win.closed) return;
	win =
		(name == 'top_mnu' ? win.top.frames.main_frame:
		(name == 'lvl' ? win.top.frames.main_frame:
		(name == 'items' ? win.top.frames.main_frame:
		(name == 'dialog' ? win.top.frames.main_frame:
		(name == 'items_right' ? win.top.frames.main_frame:
		(name == 'game' ? win.top.frames.main_frame.frames.main:
		(name == 'mem' ? win.top.frames.main_frame.frames.main:
		(name == 'inventory' ? win.top.frames.main_frame.frames.main:
		(name == 'magic' ? win.top.frames.main_frame.frames.main:
		(name == 'area' ? win.top.frames.main_frame.frames.main:
		(name == 'instance' ? win.top.frames.main_frame.frames.main:
		window)))))))))));
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return win[name];
	} else {
		return win.document[name];
	}
}

function swfTransfer(name,tar,data) {
	try {
		getSWF(tar).swfData(name,data);
		return true;
	}
        catch (e) {};
	return false;
}

function moveMedals(shift) {
	if (((shift < 0) && (position > 0)) || ((shift > 0) && (medals[position + MedalsOnPage]))) {
		position += shift;
		showMedals();
	}
}
function showMedals() {
	for(i=0;i<MedalsOnPage;i++) {
		document.getElementById('medal_' + i).innerHTML = medals[i + position] ? medals[i + position] : '&nbsp;';
	}
	if (position > 0) {
		document.getElementById('medal_l').src = "/images/medal_l_act.gif";
		document.getElementById('medal_l').style.cursor = "pointer";
	} else {
		document.getElementById('medal_l').src = "/images/medal_l.gif";
		document.getElementById('medal_l').style.cursor = "default";
	}
	if (medals[position + MedalsOnPage]) {
		document.getElementById('medal_r').src = "/images/medal_r_act.gif";
		document.getElementById('medal_r').style.cursor = "pointer";
	} else {
		document.getElementById('medal_r').src = "/images/medal_r.gif";
		document.getElementById('medal_r').style.cursor = "default";
	}
	return 1;
}

function ShowDiv(obj, evnt, show) {
	var div = gebi(obj.getAttribute('div_id'));
	if (!div) return;
	if (show == 2) {
		document.onmousemove=function(e) {artifactAlt(obj, e||event, 1)} 
		div.style.display = 'block';
	}
	if (!show) {
		div.style.display = 'none';
		document.onmousemove=function(){}
		return;
	}
	
	var ex = evnt.clientX + document.body.scrollLeft;
	var ey = evnt.clientY + document.body.scrollTop;
	
	var x = evnt.clientX + div.offsetWidth > document.body.clientWidth - 7 ? ex - div.offsetWidth - 10 : ex + 10;
	var y = evnt.clientY + div.offsetHeight > document.body.clientHeight - 7 ? ey - div.offsetHeight - 10 : ey + 10;

	if (x < 0 ) {
		x = ex - div.offsetWidth/2
	}
	if (x < 7 ) {
		x = 7
	}
	if (x > document.body.clientWidth - div.offsetWidth - 7) {
		x= document.body.clientWidth - div.offsetWidth - 7
	}

	div.style.left = x;
	div.style.top = y;
}

function refreshEvent (id) {document.location.href = 'user_event.php?mode=events&event_id='+id;}
function enterGreatFights () {document.location.href = 'area_fights.php?mode=great';}

function common_is_email_valid(email,all) {
	if (!email && !all) {
		return true;
	}
	var re = '';
	if (all) {
		re = /^([A-z0-9_\-]+\.)*[A-z0-9_\-]+@([A-z0-9][A-z0-9\-]*[A-z0-9]\.)+[A-z]{2,4}$/i;
	} else {
		re = /^([A-z0-9_\-]+\.)*[A-z0-9_\-]+(@)?([A-z0-9][A-z0-9\-]*[A-z0-9]\.)*(\.)?[A-z]{0,4}$/i;
	}
	if (!re.test(email)) {
		return false;
	}
	return true;
}

function petAlt(obj, evnt, show) {
	var div = gebi(obj.getAttribute('div_id'));
	if (!div) return;
	var act1 = obj.getAttribute('act1');
	var act2 = obj.getAttribute('act2');
	if (show == 2) {
		document.onmousemove=function(e) {petAlt(obj, e||event, 1)} 
		div.style.display = 'block';
		if (act1 || act2) {
			_background(obj, (top.locale_path + "images/itemact-"+ act1) + (act2 +".gif"));
		}
	}
	if (!show) {
		if (act1 || act2) {
			_background(obj, 'images/d.gif');
		}
		div.style.display = 'none';
		document.onmousemove=function(){}
		return;
	}
	
	var ex = evnt.clientX + document.body.scrollLeft;
	var ey = evnt.clientY + document.body.scrollTop;

	if (act1 || act2) {
		obj.style.cursor = 'default'
		obj.onclick = (act1 != 0 ? function(){try{petAct(obj, act1)}catch(e){}} : function(){showPetInfo(obj.getAttribute('aid'), obj.getAttribute('art_id'))});
		_background(obj, (top.locale_path + "images/itemact-"+ act1) + (act2 +".gif"));
		var coord = getCoords(obj)
		var cont = gebi("item_list")
		var rel_x = (ex + cont.scrollLeft - coord.l)
		if (rel_x >= 40) {
			var rel_y = (ey + cont.scrollTop - coord.t)
			if (rel_y < 20) {
				obj.onclick = function(){showPetInfo(obj.getAttribute('aid'))}
				_background(obj, top.locale_path + 'images/itemact_info' + act2 +'.gif');
				try{obj.style.cursor = 'hand'} catch(e){}
				try{obj.style.cursor = 'pointer'} catch(e){}
			}
			if (act2 != 0 && rel_y >= 40) {
				obj.onclick = function(){try{petAct(obj, act2)}catch(e){}}
				_background(obj, top.locale_path + 'images/itemact_drop' + act2 +'.gif');
				try{obj.style.cursor = 'hand'} catch(e){}
				try{obj.style.cursor = 'pointer'} catch(e){}
			}
		}
	}
	var x = evnt.clientX + div.offsetWidth > document.body.clientWidth - 7 ? ex - div.offsetWidth - 10 : ex + 10;
	var y = evnt.clientY + div.offsetHeight > document.body.clientHeight - 7 ? ey - div.offsetHeight - 10 : ey + 10;

	if (x < 0 ) {
		x = ex - div.offsetWidth/2
	}
	if (x < 7 ) {
		x = 7
	}
	if (x > document.body.clientWidth - div.offsetWidth - 7) {
		x= document.body.clientWidth - div.offsetWidth - 7
	}

	div.style.left = x;
	div.style.top = y;
}

function fb_feed(lock_id,feed_id, data) {
	try{
		top.frames['main_frame'].wall(lock_id,feed_id, data)
	} catch(e) {}
}


function updateMount(mount_id) {
	top.frames['main_frame'].mountID = mount_id;
}

function switchSkillPanel(current, list) {
	for (i = 0; i <= list.length; ++i) {
		var item = gebi(list[i]);
		var link = gebi(list[i] + '_lnk');
		var left = gebi(list[i] + '_left');
		var right = gebi(list[i] + '_right');
		var bg = gebi(list[i] + '_bg');
		if (item) item.style.display = 'none';
		if (link) link.className = 'tbl-shp_menu-link_inact';
		if (left) left.src = 'images/tbl-shp_menu-left-inact.gif';
		if (right) right.src = 'images/tbl-shp_menu-right-inact.gif';
		if (bg) bg.className = 'tbl-shp_menu-center-inact';
	}
	for (i = 0; i <= current.length; ++i) {
		var item = gebi(current[i]);
		var link = gebi(current[i] + '_lnk');
		var left = gebi(current[i] + '_left');
		var right = gebi(current[i] + '_right');
		var bg = gebi(current[i] + '_bg');
		if (item) item.style.display = '';
		if (link) link.className = 'tbl-shp_menu-link_act';
		if (left) left.src = 'images/tbl-shp_menu-left-act.gif';
		if (right) right.src = 'images/tbl-shp_menu-right-act.gif';
		if (bg) bg.className = 'tbl-shp_menu-center-act';
	}
}

function getKeyCode(e) {
	return (window.event) ? event.keyCode : e.keyCode;
}

function toggle_visibility(id) {
	var obj = gebi(id);
	if (obj) {
    	obj.style.display = obj.style.display=='' ? 'none' : '';
      	return obj.style.display=='none';
    }
	return false;
}

function explode(str, delimeter) {
	return str ? str.split(delimeter ? delimeter : '') : [];
}

function implode(array, delimeter) {
	var str = '';
	if(array) {
		var array_length = array.length ? array.length-1 : 0;
		for(var id in array)
			str = str + array[id] + (array_length-- ? delimeter : '');
	}
	return str;
}

// Применительно к объектам Array
// IE сцуко не поддерживает Array::indexOf
function indexOf(arr, value) {
	for(var id in arr)
		if(arr[id] == value) 
			return id;
	return -1;
}

function getXmlHttp(){
	try {
		return new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			return new ActiveXObject("Microsoft.XMLHTTP");
		} catch (ee) {
		}
	}
	if (typeof XMLHttpRequest!='undefined') {
		return new XMLHttpRequest();
	}
}

function getUrl(url, cb) { 
	var xmlhttp = getXmlHttp();
	xmlhttp.open("GET", url);
	if (cb) {
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				cb(
				xmlhttp.status, 
				xmlhttp.getAllResponseHeaders(), 
				xmlhttp.responseText
				);
			}
		}
	}
	xmlhttp.send(null);
}

function doPost(actionUrl, params) {
	var newF = document.createElement("form");
	newF.action = actionUrl;
	newF.method = 'POST';
	var parms = params.split('&');
	for (var i=0; i<parms.length; i++) {
	  var pos = parms[i].indexOf('=');
	  if (pos > 0) {
		   var key = parms[i].substring(0,pos);
		   var val = parms[i].substring(pos+1);
		   var newH = document.createElement("input");
		   newH.name = key;
		   newH.type = 'hidden';
		   newH.value = val;
		   newF.appendChild(newH);
	  }
	}
	document.getElementsByTagName('body')[0].appendChild(newF);
	newF.submit();
}

document.write('<script src="\/js\/console_log.js"><\/' + 'script>');

function updateAltEffects(effects) {
	top.frames['main_frame'].temp_effects = effects;
}


function moveToClanBattleLobby() {
	try {
		top.frames['main_frame'].frames['main'].location.href = 'clan_battle_conf.php?clan_battle_request_confirm=1';
	}
	catch (e) {}
}

function tutorialHook(step, end){
	top.frames['main_frame'].tutorialShow(step);
	if (end) {
		top.frames['main_frame'].tutorialEnd();
	}
}

function getClientWidth()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function chat_add_artifact_macros(id, end_space) {
	return chat_add_macros('artifact_'+id, end_space);
}

function chat_add_macros(name, end_space) {
	if (end_space === undefined)
		end_space = true;
	var text = '[['+name+']]';
	if (end_space)
		text += ' ';
	var win = window;
	if (!win.top.frames['chat']) return false;
	win.top.frames['chat'].chatAddToMsg(text);
	return true;
}

function change_select_color(element) {
	var option = element.options[element.selectedIndex];
	if (option.style.color!=""){
		var color = rgb2hex(option.style.color);
		element.style.color = color;
		}
	else element.style.color = "";
	
}

function check_select_color() {
var change_select = gebi('change_select_id');
if(change_select){ 
	change_select_color(change_select);
	}
}

function rgb2hex(rgb)
    {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
    return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }

