// $Id: common.js,v 1.18 2009/06/08 10:33:08 vadim_b 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 openWindow(url, title, width, height, status, toolbar, menubar) {
	  var leftvar = (screen.width-width)/2;
	  var topvar = (screen.height-height)/2;
	  
	  if (typeof status == "undefined") status = "no"; else status = "yes";
	  if (typeof toolbar == "undefined") toolbar = "no"; else toolbar = "yes";
	  if (typeof menubar == "undefined") menubar = "no"; else menubar = "yes";	  

	  newWindow = window.open(
		url, 
		title, 
		"width="+width+
		", height="+height+
		", left="+leftvar+
		", top="+topvar+
		", status="+status+
		", toolbar="+toolbar+
		"  menubar="+menubar
	  );
	  
	  return newWindow;
}

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 getOffsetSum(elem) {
	var top=0, left=0
	while(elem) {
		top = top + parseInt(elem.offsetTop)
		left = left + parseInt(elem.offsetLeft)
		elem = elem.offsetParent
	}
	return {top: top, left: left}
}

function getOffsetRect(elem) {
	var box = elem.getBoundingClientRect()
	var body = document.body
	var docElem = document.documentElement
	var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
	var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
	var clientTop = docElem.clientTop || body.clientTop || 0
	var clientLeft = docElem.clientLeft || body.clientLeft || 0
	var top  = box.top +  scrollTop - clientTop
	var left = box.left + scrollLeft - clientLeft
	return { top: Math.round(top), left: Math.round(left) }
}



function getCoords(obj){
	var o=typeof(obj) == 'string' ? gebi(obj) : obj
	
//	if (elem.getBoundingClientRect) {
//		return getOffsetRect(elem)
//	} else {
//		return getOffsetSum(elem)
//	}
	
	var ret={'l':o.offsetLeft,'t':o.offsetTop,'w':o.offsetWidth,'h':o.offsetHeight};
	if (o.getBoundingClientRect ) {
		ret = o.getBoundingClientRect();
		ret={'l':ret.left,'t':ret.top,'w':o.offsetWidth,'h':o.offsetHeight};
		console_log('1',ret);
		return ret;
	}
	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;
	}
	console_log('2',ret);
	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 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;
	} 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.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 showMsg2(url, title, w, h) {
	try {
		w=w||480;
		h=h||300;
		var win = top.window;
		//win.scrollTo(0,0);
		var doc = top.document;
		var width = doc.body.scrollWidth;
		var height = doc.body.scrollHeight;
		
		//var width = 0, height = 0;
		if( typeof( top.window.innerWidth ) == 'number' ) {
			//Non-IE
			width = top.window.innerWidth;
			height = top.window.innerHeight;
		} else if( top.document.documentElement && ( top.document.documentElement.clientWidth || top.document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			width = top.document.documentElement.clientWidth;
			height = top.document.documentElement.clientHeight;
		} else if( top.document.body && ( top.document.body.clientWidth || top.document.body.clientHeight ) ) {
			//IE 4 compatible
			width = top.document.body.clientWidth;
			height = top.document.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)+'px';
		obj.style.top = ((height-h)/2)+'px';
		div.style.display = 'block';
		obj.style.display = 'block';
	} catch(e) {}
	return true;
}

function showUserRating(nick) {
	frames['main'].location.href = "rating.php?search="+nick;
}

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(unit_id){
	var url = "/unit_info.php?unit_id="+unit_id;
	window.open(url, "", "width=600,height=350,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 showFightFinish(fight_id) {
	var url = "/fight_finish.php?inner=0&fight_id="+fight_id;
	window.open(url, "", "width=990,height=700,location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");
}


function showTournamentInfo(tournament_id,artikul_id) {
	var url = "/tournament_info.php";
	if (tournament_id) url += "?tournament_id="+tournament_id;
	else if (artikul_id) url += "?artikul_id="+artikul_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) {
	return false
	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 = "/user_info.php?mode=punishment&nick="+nick;
	window.open(url, "", "width=920,height=700,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) {
	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;
	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 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 - document.body.scrollTop)
		if (rel_y < 20) {
			var rel_x = (ex + cont.scrollLeft - coord.l - document.body.scrollLeft);
			if (act1 != 0 && rel_x < 20) {
				obj.onclick = function(){try{artifactAct(obj, act1)}catch(e){}}
				try{obj.style.cursor = 'pointer'} catch(e){}
			}
			if (act2 != 0 && rel_x >= 43) {
				obj.onclick = function(){try{artifactAct(obj, act2)}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 + document.body.scrollLeft) {
		x= document.body.clientWidth - div.offsetWidth - 7 + document.body.scrollLeft
	}

	div.style.left = x;
	div.style.top = y;
}

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) {
	console_group(updateSwf,true);
	console_log(params);
	var win = window
	try { win = dialogArguments ?  dialogArguments.win || dialogArguments : window } catch(e) {}
	while (win.opener) win = win.opener;
	if (win.closed) {
		console_groupEnd();
		return;
	}
	var url = 'main_iframe.php?mode=update_swf';
	if (!params) {
		console_groupEnd();
		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) {}
	console_groupEnd();
}

function updateHP() {
	updateSwf({'lvl': '' ,'items': '', 'left': ''});
}

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 m = gebi(id_prefix).value;
	if (m.match(/[^0-9.]/)) m = m.replace(/[^0-9].*$/, '');
	v = m*1.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 m = gebi(id_prefix);
	
	var str = ' ';
	var t=0;
	amount = amount * 1;
	t = amount;
	m.value = t.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) {
	console_group('swfTransfer('+tar+')',true);
	console_log(name,tar,data);
	try {
		getSWF(tar).swfData(name,data);
		console_groupEnd();
		return true;
	} catch (e) {};
	console_groupEnd();
	return false;
}

function formationUpdate(next_tour,form_ready,current_time) {
	alert(" next_tour: " + next_tour + "\n form_ready: " + form_ready + "\n current_time: " + current_time);
	top.frames["main_frame"].document["topmenu"].updateAlarm(next_tour,form_ready,current_time);
}

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;
}

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 {
		if (top.dialogOpen == false || close) {
			var id = top.dialogNeed.shift();
			if (id) {
				updateSwf({'left': '&id='+id });
				top.dialogOpen = true;
				top.dialogShow[id] = id;
				top.showNow = id;
				
			} else if (top.dialogOpen == true) {
				updateSwf({'left': '&id=0' });
				top.dialogOpen = false;
				top.showNow = 0;
				
			}
		}
	} catch(e) {}
}


document.write('<script src="\/js\/console_log.js"><\/' + 'script>');
