// $Id: common.js,v 1.30 2010-10-11 11:33:29 r.berezkin 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 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(txt){
	if(document.body.createTextRange) {
		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 {
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect')
		var gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper)
		gClipboardHelper.copyString(txt)
	} catch (e) {}
}

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 showMsg("error.php?error="+error);
}

function showMsgModal(url, title, w, h) {
	w=w||480
	h=h||300
	var win = top.window;
	if (win.showModalDialog ) {
		var sFeatures = 'dialogWidth:' + w + 'px; dialogHeight:' + h + 'px; center:yes; help:no; status:no; unadorned:yes; scroll:no;';
		return win.showModalDialog("msg.html", {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, modal=yes');
	}
}

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.html", {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 showUserInfo(nick) {
	var url = "/user_info.php?nick="+nick;
	window.open(url, "", "width=920,height=700,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

function showUnitInfo(artikul_id){
	var url = "/unit_info.php";
	if (artikul_id) url += "?artikul_id="+artikul_id;
	else return;
	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) {
	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 showFightInfo(fight_id) {
	var url = "/fight_info.php?fight_id="+fight_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?no_redirect=1";
	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) {
	var url = "/bot_info.php";
	if (bot_id) {
		if (bot_id > 1000000000) bot_id -= 1000000000;
		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 userPrvTag() {
	var win = window
	try { win = dialogArguments || window } catch(e) {}
	while (win.opener) win = win.opener;
	if (win.closed) return;
	try {
		for (i=0; i<arguments.length; i++) win.top.frames['chat'].chatPrvTag(arguments[i]);
	}
	catch (e) {}	
}

function userToTag() {
	var win = window;
	try { win = dialogArguments || window } catch(e) {}
	while (win.opener) win = win.opener;
	if (win.closed) return;
	try {
		for (i=0; i<arguments.length; i++) win.top.frames['chat'].chatToTag(arguments[i]);
	}
	catch (e) {}	
}


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

function userAttack(nick, url_error, bot_id) {
	var urlATTACK;
	var rnd = Math.floor(Math.random()*1000000000);
	var url_success = 'fight.php?'+rnd;
	
	if(bot_id) {
		urlATTACK = 'action_run.php?code=ATTACK_BOT&url_success='+url_success+'&url_error='+escape(url_error||'area.php');
		urlATTACK += '&bot_id=' + bot_id;
	} else {
		urlATTACK = 'action_run.php?code=ATTACK&url_success='+url_success+'&url_error='+escape(url_error||'area.php')+'&in[nick]='+nick;
		if (!nick) return;
	}
	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 botAttack(bot_id, url_error, area_bot_id) {
	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');
	if (bot_id) urlATTACK += '&bot_id='+bot_id;
	if (area_bot_id) urlATTACK += '&in[area_bot_id]='+area_bot_id;
	if (!bot_id && !area_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 show_slaughter_stat(instance_id, finish) {
	var url = '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 artifactAlt(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) {artifactAlt(obj, e||event, 1)} 
		div.style.display = 'block';
		if (act1 || act2) {
			if (obj.tagName == 'IMAGE') {
				obj.src = ("images/itemact-"+ act1) + (act2 +".gif")
			} else {
				obj.style.backgroundImage = 'url(' + ("images/itemact-"+ act1) + (act2 +".gif") + ')'
			}
		}
	}
	if (!show) {
		if (act1 || act2) {
			if (obj.tagName == 'IMAGE') {
				obj.src = "images/d.gif"
			} else {
				obj.style.backgroundImage = 'url(' + "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'
		if (obj.getAttribute('arid')) {
			obj.onclick = function(){showArtifactInfo(0, obj.getAttribute('arid'))}
		} else if (obj.getAttribute('aid')) {
			obj.onclick = function(){showArtifactInfo(obj.getAttribute('aid'))}
		} else {
			obj.onclick = function(){}
		}
		var coord = getCoords(obj)
		var cont = gebi("item_list")
		
		var rel_y = (ey + cont.scrollTop - coord.t)
		if (rel_y < 19) {
			var rel_x = (ex + cont.scrollLeft - coord.l)
			if (act1 != 0 && rel_x < 19) {
				obj.onclick = function(){try{artifactAct(obj, act1)}catch(e){}}
				try{obj.style.cursor = 'hand'} catch(e){}
				try{obj.style.cursor = 'pointer'} catch(e){}
			}
			if (act2 != 0 && rel_x >= 36) {
				obj.onclick = function(){try{artifactAct(obj, act2)}catch(e){}}
				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;
	div.style.zIndex = 10;
}

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, force) {
	if (!force && top.frames["main_frame"].frames["main"].__area_php_walk__) return;
	if (top.__lastFightId && (top.__lastFightId >= fight_id)) return;
	var rnd = Math.floor(Math.random()*1000000000);
	var url = 'fight.php?'+rnd;
	top.__lastFightId = fight_id;
	top.frames["main_frame"].frames["main"].location.href = url;
}

function areaRedirect(force) {
	if (!force && top.frames["main_frame"].frames["main"].__area_php_walk__) return;
	var rnd = Math.floor(Math.random()*1000000000);
	var url = 'area.php?'+rnd;
	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 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 =
		(name == 'lvl' ? top.frames.main_frame:
		(name == 'left' ? top.frames.main_frame:
		(name == 'right' ? top.frames.main_frame:
		(name == 'mail' ? top.frames.main_frame:
		(name == 'battle' ? top.frames.main_frame.frames.main:
		(name == 'mem' ? top.frames.main_frame.frames.main:
		(name == 'inventory' ? top.frames.main_frame.frames.main:
		(name == 'magic' ? top.frames.main_frame.frames.main:
		(name == 'army' ? top.frames.main_frame.frames.main:
		(name == 'walk' ? 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 showWorldMap() {
	var url = "/world_map.php";
	window.open(url, "world", "location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
}

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;
}

