// ---  WW2Life JS c 2007   ----------
var timerTime;
var delay = 50;	

var red_indicator = 33;	
var white_red_indicator = 20;	
var yellow_indicator = 66; 

var white_yellow_indicator = 50;	

var health_timerOn = -1;	
var stamina_timerOn = -1;	
var moral_timerOn = -1;	
var proposalUpdater = null;
var updaterFreq = 60000;

var deletedSubjId = 0;

/*
    Prototype ajax implementation
*/

function getPage(url, meth, params, container, onCompl) {
    updater_meth(container, meth, url, params, onCompl)
}

//----------------------------
//  Pause
//----------------------------
function pause(ms)
{
 var date = new Date();
 var curDate = null;
 do { curDate = new Date(); }
 while(curDate-date < ms);
}

//-------------------------
//  Window sections
//-------------------------
function open_window(href, name) {
    var w =window.open(href, name);
    w.focus();
}

function open_long_window(href) {
    var wwheight=screen.availHeight-75;
    var wwleft=screen.availWidth-680;
    var w =window.open(href,'Arts','top=10,left='+wwleft+'toolbar=0,height='+wwheight+',width=680,status=0,scrollbars=1,resizable=1,menubar=0,titlebar=0');
    w.focus();
}

function open_map_window(href) {
    var w =window.open(href,'Map','top=0,left=0,toolbar=0,height=600,width=600,status=0,scrollbars=0,resizable=0,menubar=0,titlebar=0');
    w.focus();
}

function open_short_window(href) {
    var wwleft=screen.availWidth-680;
    var w =window.open(href,'Arts','top=10,left='+wwleft+'toolbar=0,height=680,width=680,status=0,scrollbars=1,resizable=1,menubar=0,titlebar=0');
    w.focus();
}

function open_short_window1(href) {
    var wwleft=0;
    var w =window.open(href,'Arts1','top=10,left='+wwleft+'toolbar=0,height=680,width=680,status=0,scrollbars=1,resizable=1,menubar=0,titlebar=0');
    w.focus();
}

function open_art_window(href) {
	var height = 445;
	var width = 837;
	var wwheight=parseInt((screen.availHeight-height)/2);
	var wwleft=parseInt((screen.availWidth-width)/2);
    var w =window.open(href,'onjectInfo','top='+wwheight+',left='+wwleft+'toolbar=0,height='+height+',width='+width+',status=0,scrollbars=1,resizable=1,menubar=0,titlebar=0');
    w.focus();
}

function open_full_window(href) {
    var w =window.open(href,'Arts','toolbar=0,status=0,scrollbars=1,resizable=1,menubar=0,titlebar=0');
    w.focus();
}


function openwin(url, param){
	var height = 20;
	var wwheight=parseInt((screen.availHeight-height));
	var width = 1000;
	var wwleft=parseInt((screen.availWidth-width)/2);
	var wName = "wind_"+parseInt(Math.random(1) * 10000000);
	var win=window.open(url+"?"+param, wName, "top=5,left="+wwleft+",width="+width+",height="+wwheight+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1");
    win.focus();
}


function openAwatarWin(url, param){
	var height = 686;
	var width = 373;
	var wwleft=parseInt((screen.availWidth-width)/2);

	var win=window.open(url+"?"+param, "avatarView", "top=5,left="+wwleft+",width="+width+",height="+height+",toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1");
    win.focus();
}
function hear(url, param){
    var p="top=70,left=100,width=400,height=250,toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0";
    var win=window.open(url+"?"+param, "hear",p);
    win.focus();
}

//--------------
// 
//--------------
function showContent (tagname,adjX,adjY){
   var dx, dy
       dx = (event.clientX + document.body.scrollLeft);
       dy = (event.clientY + document.body.scrollTop);
   object = document.all[tagname].style;
   object.pixelLeft = dx + (adjX || 5);
   object.pixelTop = dy + (adjY || -15);
   object.visibility = "visible";
   return false;
};

function hideContent(tagname){
	object =document.getElementById[tagname];
	if (object){
		object_s =document.getElementById[tagname].style;
    	object_s.visibility = "hidden";
	    object_s.pixelLeft = 0;
    	object_s.pixelTop = 0;
	}	
    return false;
};


function showElement(element)
{
	setElementDisplay(element, true);
};

function hideElement(element)
{
	setElementDisplay(element, false);
};

function isElementVisible(element)
{
	return element.style.display != 'none';
}

function setElementDisplay(element, visible)
{
	element.style.display = visible ? "" : 'none';
};

function switchElementDisplay(element)
{
	setElementDisplay(element, !isElementVisible(element));
};

function hideAllContent(tag_prefics){
	var tagname;
	for (i=1; i < 16; i++){
		tagname = tag_prefics+i;
		hideContent(tagname)
	}
    return false;
};

//--------------
function set_indicator(ind, cur_value, max_value, speed, is_white) {
	var timerOn = eval(ind+'_timerOn');
	if (timerOn >= 0) { clearTimeout(timerOn); 	timerOn=-1; }
	if (speed < 1) speed=1;
	var procent =Math.round((cur_value / max_value) *100);
	if (procent > 100) procent=100;
	var obj, obj_t;
	obj = document.images[ind];
	obj_t = document.getElementById['t_'+ind];
	obj_max_length=  123;
	if (obj){
		obj.width = Math.round(obj_max_length/100 * procent);
		obj.src="/img/bg_"+ind+".gif";
		obj.alt = Math.round(cur_value)+"/"+max_value;
	}

	if (obj_t){
		obj_t.innerHTML = Math.round(cur_value);
	}

	cur_value = cur_value +  (delay/ (speed * 10) )*  max_value; 

	if (cur_value <= max_value){
	 timerOn = eval("setTimeout(\"set_indicator('"+ind+"', "+cur_value+", "+max_value+", "+speed+", "+is_white+");\", delay*100)");
	} else { 
		obj.alt = max_value+"/"+max_value;
		obj.width = Math.round(obj_max_length);
		obj_t.innerHTML = Math.round(max_value);
		timer_on = -1; 
	}
}
//----------------
function set_refresh(url){
	 if (timerOn >=0){
	 	document.location.href=url;
		clearTimeout(timerOn); timerOn=-1;
	 }
	 timerOn = eval("setTimeout(\"refresh('"+url+"');\", 100)");
}


function CreateWnd(URL,Name,w,h)
{
	var ww_top=(screen.availHeight-h)/2;
	var ww_left=(screen.availWidth-w)/2;
  var Wnd;
  param="top="+ww_top+",left="+ww_left+",toolbar=0,directories=no,menubar=0,resizable=1,scrollbars=1,status=0,width="+w+",height="+h;
  Wnd=window.open(URL,Name,param);
  Wnd.focus();
}


function get_height(){
	var height;
	if (self.innerHeight) {	
		 height = self.innerHeight;	
	// IE 6 Strict Mode	
	} else if (document.documentElement && document.documentElement.clientHeight) {	    
		height = document.documentElement.clientHeight;	
	// non IE
	} else if (document.body) {	    
		height = document.body.clientHeight;	
	}	
	return height;
}

function changeCursor(obj,i) {
	t=i;
	if(i==0)t="DEFAULT"
	else if(i==1)t="CROSSHAIR"
	else if(i==2)t="HAND"
	else if(i==3)t="MOVE"
	else if(i==4)t="TEXT"
	else if(i==5)t="WAIT"
	obj.style.cursor=t;
}



//  Button settings
function setButtonHandlers(buttons) {
     for (i in buttons) {
         var obj = document.getElementById(i);
         if (!obj) continue;
         obj.onmouseout  = function() { this.src =  buttons[this.id][0] };
         obj.onmouseover = function() { this.src =  buttons[this.id][1] };
         obj.onmousedown = function() { this.src =  buttons[this.id][2] };
         obj.onmouseup   = function() { this.src =  buttons[this.id][1] };
    }
}

function updater_new(container, url, params, callback){
	
	updater(container, url, params, callback);	
}

//  Ajax section
function updater_meth(container, meth, url, params, callback){

	if (params) {

		if (jQuery.isFunction(params)) {
			callback = params;
			params = null;
		} else if(typeof params === "object") {
			params = jQuery.param(params);
		}
	} else {
	
		params = {};
	}

	$.ajax({
		type: meth,
		dataType: 'html',
		url: url,
		data: params,
		contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
		success: function(html){

			if (typeof container == 'string') {
				container = $("#"+container);
			} else {
				container = $(container);
			}

            container.html(html);

			if (callback)
				container.each(callback, [html]);
		}
	});
}


function updater(container, url, params, callback){
	updater_meth(container, 'POST', url, params, callback)
}

function updater_period(container, url, param) {
	
	if(proposalUpdater!=null){
		window.clearInterval(proposalUpdater);
	}
	
	updater(container, url, param);
	proposalUpdater = window.setInterval(function(){updater(container, url, param)}, updaterFreq)
}

//----------------- Client  Size --- 

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;
}

//----------------- Varnings  --- 
function isIE()
{
  return navigator.appName.indexOf("Microsoft")!=-1;
}

function insWarning(idWarn, warning, handler)
{
   	if (document.getElementById(idWarn) == null) {
		$('#'+handler).after('<SPAN class="warning" id=' + idWarn +'><BR>' + warning + '</SPAN>');
   	}
}

function removeWarning(idWarn)
{
   	if (document.getElementById(idWarn) != null)
		$("#"+idWarn).remove();
}


function trimGaps(str)
{
  if (str != null) {
  	while (str.charAt(str.length - 1) == " ")
  		str = str.substring(0, str.length - 1);
  	while (str.charAt(0) == " ")
  		str = str.substring(1, str.length);
  }
  return str;  	
}


function trimNum(str)
{
  if (str != null) {
  	while ((str.charCodeAt(0) > 47) && (str.charCodeAt(0) < 58))
  		str = str.substring(1, str.length);
  }
  return str;  	
}


//   Location  Section
function locChangeChat(){
	if(parent.frames) {
    	   if(parent.frames.chat)   parent.frames.chat.ChangeLocation();
	}
}


//   Location  Section
function update_info() {
	var rand = Math.random(1);
	var MSIE = (navigator.userAgent.indexOf("Microsoft") != -1);
	var flash = MSIE ?    window["informer"] : document["informer"];
	flash.setVariable("data", "/heroInfo.jsp?"+rand);
}

function privateSay(nic) {
	if (window.opener){
		var cp = window.opener.parent.window.frames["chat"];
		if (cp) {
			cp.PrivateTagCreate(nic);
			return false;
	 	}
	}
	var cp = parent.window.frames["chat"];
	if (cp) 
	{
		cp.PrivateTagCreate(nic);
		return false;
	}
	return false;
}
function toSay(nic) {
	if (window.opener){
		var cp = window.opener.parent.window.frames["chat"];
		if (cp) {
			cp.ToTagCreate(nic);
			return false;
	 	}
	}
	var cp = parent.window.frames["chat"];
	if (cp) 
	{
		cp.ToTagCreate(nic);
		return false;
	}
	return false;
}

function getHeight() {
	if (self.innerHeight) {
		return self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	} else if (document.body) {
		return document.body.clientHeight;
	}
	return NaN;
}

function getWidth() {
	if (self.innerWidth) {
		return self.innerWidth;
	} else if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	} else if (document.body) {
		return document.body.clientWidth;
	}
	return NaN;
}

//   For  proposal requests
function checkLevels(minrnak, maxrank) {
  if (document.getElementById(minrank).value != '' && document.getElementById(maxrank).value != '') {
    if (parseInt(document.getElementById(minrank).value) > parseInt(document.getElementById(maxrank).value)) {
    	alert('Что то там с левелом не то...');
    	document.getElementById(minrank).focus();
    	return false;
    }
  }
  return true;
}

function getAction(subjId, actionName) {
	$('#actionName').html(actionName);
	updater('actionView', '/subjAction.jsp?subj='+subjId+'&'+Math.random())
	$('#actionDiv').css('display', 'block');
}

function openBox(subjId, actionName) {
	$('#actionName').html(actionName);
	updater('actionView', '/actions/boxOpen.jsp?subj='+subjId+'&'+Math.random())
	$('#actionDiv').css('display', 'block');
}


function showSubjectContents(container, subjectId)
{
	updater(container, '/subjects/constructor/main_subject_contents.jsp?subjectId=' + subjectId);
}	

function trInfo(url, img){
//    alert("1");
    updater('transactionDescription', url);
    var info = document.getElementById('transactionInfo');
    var pos = getElementPosition(img);
    info.style.left = pos[0];
    info.style.display = '';
    info.style.top = pos[1] - info.offsetHeight;
}


function CommonShowContents(container, mainSubjectId){
    updater(container, '/hero/subjects/common_contents.jsp',
            'mainSubject=' + mainSubjectId );
}


function img(url, width, height){
    document.write("<img src=\""+path+url+"\" width=\""+width+"\" height=\""+height+"\" >");
}

function imgTitle(url, width, height, title){
    document.write("<img src=\""+path+url+"\" width=\""+width+"\" height=\""+height+"\" title=\""+title+"\">");
}

function GetSynchronousResponse(url, method, param)
 {
    var xmlhttp = null;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP"))
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    xmlhttp.open(method, url, false); //false means synchronous

    if (method == "POST")
        xmlhttp.send(postData);
    else
        xmlhttp.send(null);

    try
    {
        var responseText = xmlhttp.responseText;
    }
    catch (e)
    {
        alert(e.message);
    }
    return responseText;
}

onLangSelect = function() {

	var checkBoxes = document.getElementsByName("chat_lang_id");
	for (var i = 0; i < checkBoxes.length; i++) {
		checkBoxes[i].disabled = false;
	}
	
	var selectedLangId = document.getElementById("lang_id").value;
	var checkBox = document.getElementById("chat_lang_id_" + selectedLangId);
	checkBox.disabled = true;
	checkBox.checked = true;
}

// Actions
function submitAction(url)
{
    var form=document.getElementById('actionForm');
    var fields = form.elements;
    var qs='';
    for (var i=0; i< fields.length; i++){
        qs+=fields[i].name+"="+encodeURIComponent(fields[i].value);
        if (i < fields.length-1)
            qs+="&";
    }
    updater('actionView', url+"?"+qs);
}

// Main Window
function exitMain(retval){
    if(retval)
    {
        if(window.parent.frames)
            window.parent.document.location.href='/logof.jsp';
        else
            document.location.href='/logof.jsp';
    }
}

var isPanelClosed = false;

function wrap() {

	if (!isPanelClosed) {
	
	    var cd = document.getElementById('center');
	    var abilPan = document.getElementById('abilPanelBody');
	    var heroInfo = document.getElementById('informer_box');
	    var closePan = document.getElementById('panelClose');

	    if (cd) cd.style.height = parseInt(cd.style.height) + 104;
	    if (abilPan) abilPan.style.display   = "none";
	    if (heroInfo) heroInfo.style.display  = "none";
	    if (closePan) closePan.style.display  = '';
		
		isPanelClosed = true;
	}
}

function unwrap() {

	if (isPanelClosed) {
	
	    var cd = document.getElementById('center');
	    var abilPan = document.getElementById('abilPanelBody');
	    var heroInfo = document.getElementById('informer_box');
	    var closePan = document.getElementById('panelClose');

	    if (cd) cd.style.height = parseInt(cd.style.height) - 104;
	    if (abilPan) abilPan.style.display   = '';
	    if (heroInfo) heroInfo.style.display  = '';
	    if (closePan) closePan.style.display  = 'none';
		
		isPanelClosed = false;
	}
}

function hideMenu() {
    var cd = document.getElementById('center');
    var abilPan = document.getElementById('abilPanelBody');
    var heroInfo = document.getElementById('informer_box');
    var closePan = document.getElementById('panelClose');

    if (cd) cd.style.height = parseInt(cd.style.height) + 104;
    if (abilPan) abilPan.style.display   = "none";
    if (heroInfo) heroInfo.style.display  = "none";
    if (closePan) closePan.style.display  = "none";
}


function main_onload() {
    updater('center', '/location.jsp');
    updater('informer_box', '/hero/hero_informer.jsp');
    updater("abilPanelBody","/actions/abilPanel.jsp");
}

function serializeForm(form) {
		
	if (typeof form == 'string') {
		return $("#"+form).serialize();
	} else {
		return $(form).serialize();
	}
}


// ------------ Hero Info 
var heroInfo = {

	setBigDivs : function(){

	    var menu = document.getElementById('menuDiv').style;


	    var common = document.getElementById('div_common').style;
	    var height = screen.availHeight - 140;

	    menu.position = 'absolute';
	    menu.top = 20;

	    common.top = 45;
	    common.height= height;
	    common.width = 900;

	    for (i=0;i<tags.length;i++)
	    {
	        var div = document.getElementById('div_'+tags[i]);
	        if(div){
	            div.style.top    = common.top;
	            div.style.left   = common.left;
	            div.style.height = common.height;
	            div.style.width  = common.width;
	        }
	    }

	    document.getElementById('heroview').style.visibility = "hidden";
	    document.getElementById('menuResPlus').style.visibility = "hidden";
	    document.getElementById('menuResMinus').style.visibility = "visible";

	},
	
	setSmallDivs : function(){
	    var menu = document.getElementById('menuDiv').style;
	    var common = document.getElementById('div_common').style;

	    if (isIE()) {

	         var pos = getElementPosition(document.getElementById('etalon'))
	         menu.position = 'relative';
	          menu.top = 0;
	         common.top = pos[1]+55;
	         common.height= 340;
	         common.width = 898;
	    } else {
	        menu.position = null;

	        common.top = null;
	        common.height= 340;
	        common.width = 888;

	    }
	    for (i=0;i<tags.length;i++)
	    {
	         var div = document.getElementById('div_'+tags[i]);
	         if(div){
	             div.style.top    = common.top;
	             div.style.left   = common.left;
	             div.style.height = common.height;
	             div.style.width  = common.width;
	         }
	    }

	    document.getElementById('heroview').style.visibility = "visible";
	    document.getElementById('menuResPlus').style.visibility = "visible";
	    document.getElementById('menuResMinus').style.visibility = "hidden";

	    return false;
	},
	
	bottom_show : function(tag_name) {
	    var div = document.getElementById("div_" + tag_name);
	    if(div) div.style.visibility = "visible";
	},

	bottom_hide : function(tag_name) {
		var div = document.getElementById("div_" + tag_name);
		if(div) div.style.visibility = "hidden";
	},
	
	show : function(tag){
	    for (i=0;i<tags.length;i++)
	    {
	        if(tag == tags[i])
	           heroInfo.bottom_show(tag);
	        else
	           heroInfo.bottom_hide(tags[i]);
	    }
	},
	
	showAwardInfo : function(text, img){
	    document.getElementById('awardDescription').innerHTML=text;
	    var info = document.getElementById('awardInfo');
	    var pos = getElementPosition(img);
	    info.style.left = pos[0];
	    info.style.display = '';
	    info.style.top = pos[1] - info.offsetHeight;
	}
}

function getElementPosition (elem) {
    var offsetLeft = 0;
    var offsetTop = 0;
    while (elem) {
        offsetLeft += elem.offsetLeft;
        offsetTop += elem.offsetTop;
        elem = elem.offsetParent;
    }
    return [offsetLeft, offsetTop];
}

// --- Batle Log
function showLog(bId,pId){
        document.getElementById("tdLog").className = "dark_simple_but w100";
        document.getElementById("tdStat").className = "black_simple_but w100";
        if(document.getElementById("tdViwer")!=null)
            document.getElementById("tdViwer").className = "black_simple_but w100";
        updater('bl', '/battle/historyLog.jsp?battleId='+bId+'&playerId='+pId+'&page=1');
}

function  showStat(bId){
        document.getElementById("tdLog").className = "black_simple_but w100";
        if(document.getElementById("tdViwer")!=null)
            document.getElementById("tdViwer").className = "black_simple_but w100";
        document.getElementById("tdStat").className = "dark_simple_but w100";
        updater('bl', '/battle/historyStat.jsp?battleId='+bId);
}

function showViewer(bId){
        document.getElementById("tdLog").className = "black_simple_but w100";
        document.getElementById("tdStat").className = "black_simple_but w100";
        if(document.getElementById("tdViwer")!=null)
            document.getElementById("tdViwer").className = "dark_simple_but w100";
        updater('bl', '/battle/battleViewer.jsp?battleId='+bId);
}

// quest
var quest = {

	openCloseElem : function(path, contid, imgElem) {

        if (document.getElementById(contid).style.display == "none") {

            document.getElementById(contid).style.display = "block";
            imgElem.src = path+"img/pup/minus.gif";
        }

        else if (document.getElementById(contid).style.display == "block") {

            document.getElementById(contid).style.display = "none";
            imgElem.src = path+"img/pup/plus.gif";
        }
    },

    openCloseCompleted : function(path, groupId) {

        var contId = 'group_'+groupId+'_completed'
        var imgId = 'im_'+groupId+'_completed'

        if (document.getElementById(contId).style.display == "none") {

            document.getElementById(contId).style.display = "block";
            document.getElementById(imgId).src = path+"img/pup/minus.gif";
        }

        else if (document.getElementById(contId).style.display == "block") {

            document.getElementById(contId).style.display = "none";
            document.getElementById(imgId).src = path+"img/pup/plus.gif";
        }
    },

    selectTab : function (questGroupType) {

        updater('center', '/QuestStatus?command=view&quest_group_type=' + questGroupType);
    },

    decline : function(historyQuestId) {
        getPage('/QuestStatus?command=decline', 'get', {historyQuestId: historyQuestId}, 'questStatusContainer');
    },

    accomplish : function(questId) {
        getPage('/QuestStatus?command=accomplish', 'get', {questId: questId}, 'questStatusContainer');
    }
}
   
//  Clan
var outfit = {

	moveItems : function (dir) {

	    var cid = dir.name;
	    var src = null;
	    var dst = null;
	    var id;
	    var items = cid.split('#');
	    var parent = dir.parentNode;
		
	    while (parent.nodeType != 1 || parent.tagName != 'TABLE')
	        parent = parent.parentNode;

	    var selects = parent.getElementsByTagName('SELECT');
	    for (var i = 0; i < selects.length; i++) {
	        if (selects[i].id.indexOf(items[0]) != -1)
	            src = selects[i];
	        if (selects[i].id.indexOf(items[1]) != -1)
	            dst = selects[i];
	    }
		
	    if (src != null && dst != null) {
	        
			var opts = src.options;
	        var move = new Array();
			
	        for (var i = 0; i < opts.length; i++) {
	            if (opts[i].selected)
	                move.push(opts[i]);
	        }
			
	        for (var i = 0; i < move.length; i++) {
	            dst.appendChild(src.removeChild(move[i]));
	        }
	    }
		
	    var inputs = parent.getElementsByTagName('input');
	    for (var i=0; i< inputs.length; i++){
	        if (inputs[i].type == 'hidden' && inputs.name=='c_changed')
	            inputs[i].value=true;
	    }
		
	    outfit.checkForChangesAdm(dir);
	},
	
	sendTransfer : function(){

		document.getElementById('transferResult').innerHTML='';
		var heroId = document.getElementById('nameToFriendly').value;

		var groupId = document.getElementById('friendlyGroup').value;

		updater_new('res', "/TransferToFriendly?op=create&heroId="+heroId+"&groupId="+groupId,'',
				function(){updater('transfersFrom', "/outfit/transfers/transfersFrom.jsp");});
	},
	
	checkForChangesAdm : function(input) {
	    
		var tr = input.parentNode;
	    while (tr.nodeType != 1 || tr.tagName != 'TR' || tr.className == '')
	        tr = tr.parentNode;

	    var inputs = tr.getElementsByTagName('input');
	    var c_changed = false;
	    var t_changed = false;
	    var saveBTN;

	    for (var i = 0; inputs[i]; i++) {
	        var inp = inputs[i];
	        if (inp.type != 'hidden') {
	            var oldVal = inp.nextSibling;
	            while (oldVal && oldVal.name != 'o_' + inp.name)
	                oldVal = oldVal.nextSibling;
	        }
	        if (inp.type == 'text') {
	            if (oldVal && oldVal.value != inp.value) {
	                inp.style.border = "1px solid red";
	                t_changed = true;
	            } else
	                inp.style.border = "none";
	        }
	        if (inp.type == 'hidden') {
	            if (inp.name == 'c_changed')
	                c_changed = inp.value;
	        }
	        if (inp.type == 'button') {
	            if (inp.name == "saveButton")
	                saveBTN = inp;
	        }
	    }

	    if (c_changed || t_changed) {
	        tr.getElementsByTagName('table')[0].style.border = "1px solid red";
	        saveBTN.style.display = '';
	    } else {
	        tr.getElementsByTagName('table')[0].style.border = "none";
	        saveBTN.style.display = 'none';
	    }
	},
	
	checkForChanges : function(input) {
	    var tr = input.parentNode;
	    while (tr.nodeType != 1 || tr.tagName != 'TR' || tr.className == '')
	        tr = tr.parentNode;

	    var inputs = tr.getElementsByTagName('input');
	    var c_changed = false;
	    var t_changed = false;
	    var saveBTN;
	    for (var i = 0; inputs[i]; i++) {
	        var inp = inputs[i];
	        if (inp.type != 'hidden') {
	            var oldVal = inp.nextSibling;
	            while (oldVal && oldVal.name != 'o_' + inp.name)
	                oldVal = oldVal.nextSibling;
	        }
	        if (inp.type == 'text') {
	            if (oldVal && oldVal.value != inp.value) {
	                inp.style.border = "1px solid red";
	                t_changed=true;
	            } else
	                inp.style.border = "none";
	        }
	        if (inp.type == 'checkbox') {
	            if (oldVal && oldVal.value != String(inp.checked)) {
	                c_changed = true;
	            }
	        }
	        if (inp.type == 'button') {
	            if (inp.name == "saveButton")
	                saveBTN = inp;
	        }
	    }

	    if (c_changed || t_changed) {
	        tr.getElementsByTagName('table')[0].style.border = "1px solid red";
	        saveBTN.style.display='';
	    } else {
	        tr.getElementsByTagName('table')[0].style.border = "none";
	        saveBTN.style.display='none';
	    }
	},
	
	appendRoleAdm : function() {
	
	    var tbl = document.getElementById('rolesList');
	    var tbody = tbl.firstChild;
	    while (tbody.nodeType != 1)
	        tbody = tbody.nextSibling;

	    var row = tbody.lastChild;
	    while (row.nodeType != 1)
	        row = row.previousSibling;

	    var newRow = row.cloneNode(true);

	    var inputs = newRow.getElementsByTagName('input');
	    for (var i = 0; i < inputs.length; i++) {
	        inputs[i].disabled = false;
	        if (inputs[i].type == 'text') {
	            inputs[i].value = '';
	            inputs[i].className = 'inner_inp w300';
	            inputs[i].style.border = "1px solid red";
	        }
	        if (inputs[i].type == 'hidden')
	            inputs[i].value = null;
	    }

	    // Заменяем склонированые селекты своими
	    var selects = newRow.getElementsByTagName('select');
	    var newSelects = document.getElementById('rolesPattern').getElementsByTagName('select');
	    var avail = null;
	    var cur = null;
	    for (var i = 0; i < newSelects.length; i++) {
	        if (newSelects[i].nodeType == 1) {
	            if (newSelects[i].id == 'availActs0')
	                avail = newSelects[i];
	            if (newSelects[i].id == 'selActs0')
	                cur = newSelects[i];
	        }

	    }
		
	    if (avail != null && cur != null) {
	        for (var i = 0; i < selects.length; i++) {
	            if (selects[i].nodeType == 1) {
	                selects[i].disabled=false;
	                if (selects[i].id.indexOf('availActs') != -1)
	                    selects[i].innerHTML = avail.innerHTML;
	                if (selects[i].id.indexOf('selActs') != -1)
	                    selects[i].innerHTML = cur.innerHTML;
	            }
	        }
	    }

	    var imgs = newRow.getElementsByTagName('img');
	    for (var i = 0; i < imgs.length; i++)
	        imgs[i].style.display = '';

	    var tbls = newRow.getElementsByTagName('table');
	    for (var i = 0; i < tbls.length; i++)
	        tbls[i].style.border = '1px solid red';
	    tbody.appendChild(newRow);
	},
	
	appendRole : function() {
	
	    var tbl = document.getElementById('rolesList');
	    var tbody = tbl.firstChild;
	    while (tbody.nodeType != 1)
	        tbody = tbody.nextSibling;

	    var row = tbody.lastChild;
	    while (row.nodeType != 1)
	        row = row.previousSibling;

	    var newRow = row.cloneNode(true);
		
	    var inputs = newRow.getElementsByTagName('input');
	    for (var i = 0; i < inputs.length; i++) {
	        inputs[i].disabled = false;
	        if (inputs[i].type == 'checkbox') {
	            inputs[i].checked = false;
	            inputs[i].disabled = false;
	        }
	        if (inputs[i].type == 'text') {
	            inputs[i].value = '';
	            inputs[i].className = 'inner_inp w300';
	            inputs[i].style.border = "1px solid red";
	        }
	        if (inputs[i].type == 'hidden')
	            inputs[i].value = null;
	    }
		
	    var imgs = newRow.getElementsByTagName('img');
	    for (var i = 0; i < imgs.length; i++)
	        imgs[i].style.display = '';

	    var tbls = newRow.getElementsByTagName('table');
	    for (var i = 0; i < tbls.length; i++)
	        tbls[i].style.border = '1px solid red';
	    tbody.appendChild(newRow);
	},
	
	removeRoleAdm : function(img, confirmText) {
	    
		var tr = img.parentNode;
	    while (tr.nodeType != 1 || tr.tagName != 'TR')
	        tr = tr.parentNode;
	    var r_id;

	    var inputs = tr.getElementsByTagName('INPUT');
	    for (var i = 0; i < inputs.length; i++) {
	        if (inputs[i].name == 'roleId')
	            r_id = inputs[i].value;
	    }
		
	    if (typeof(r_id) != 'undefined' && r_id != null && r_id != '') {
	        if (confirm(confirmText))
	            updater('center', '/RemoveRole?curPage=posts&id=' + r_id);
	    } else
	        tr.parentNode.removeChild(tr);
	},
	
	removeRole : function(img, confirmText){
    
	    var tr = img.parentNode;
	    while (tr.nodeType != 1 || tr.tagName != 'TR')
	        tr = tr.parentNode;
	    var r_id;

	    var inputs = tr.getElementsByTagName('INPUT');
	    for (var i = 0; i < inputs.length; i++) {
	        if (inputs[i].name == 'roleId')
	            r_id = inputs[i].value;
	    }
	    
	    if (typeof(r_id) != 'undefined' && r_id != null && r_id != ''){
	        if (confirm(confirmText))
	            updater('center', '/RemoveRole?curPage=posts&id='+r_id);
	    }else
	        tr.parentNode.removeChild(tr);
	},
	
	saveChangesAdm : function(img, alertText) {
	    
		var tr = img.parentNode;
	    while (tr.nodeType != 1 || tr.tagName != 'TR')
	        tr = tr.parentNode;

	    var name;
	    var r_id;
	    var inputs = tr.getElementsByTagName('INPUT');

	    for (var i = 0; i < inputs.length; i++) {
	        if (inputs[i].name == 'postName')
	            name = inputs[i].value;
	        if (inputs[i].name == 'roleId')
	            r_id = inputs[i].value;
	    }
		
	    var selects = tr.getElementsByTagName('SELECT');
	    var select = null;
	    for (var i = 0; i < selects.length; i++) {
	        if (selects[i].id.indexOf('selActs') != -1)
	            select = selects[i]
	    }
		
	    var params = '';
	    var options = select.options;
	    for (var i = 0; i < options.length; i++) {
	        params += "action=" + options[i].value + "&";
	    }
		
	    if (typeof(name) == 'undefined' || name == null || name == '') {
	        modal.alert(alertText);
	        return;
	    } else
	        params += 'name=' + encodeURIComponent(name);

	    if (typeof(r_id) != 'undefined' && r_id != null && r_id != '')
	        params += '&id=' + r_id;
	    updater('center', '/OUpdateAdminRole?curPage=posts&' + params);
	},

	saveChanges : function(img, alertText) {
	    
		var tr = img.parentNode;
	    while (tr.nodeType != 1 || tr.tagName != 'TR')
	        tr = tr.parentNode;

	    var name;

	    var r_addmbr;
	    var r_prommbr;
	    var r_addpost;
	    var r_resign;
	    var r_id;
	    var r_banker;
	    var r_capter;
	    var r_give_medals;
	    var inputs = tr.getElementsByTagName('INPUT');

	    for (var i = 0; i < inputs.length; i++){
	        if (inputs[i].name == 'postName')
	            name = inputs[i].value;
	        if (inputs[i].name == 'addmbr')
	            r_addmbr = inputs[i].checked;
	        if (inputs[i].name == 'prommbr')
	            r_prommbr = inputs[i].checked;
	        if (inputs[i].name == 'addpost')
	            r_addpost = inputs[i].checked;
	        if (inputs[i].name == 'resign')
	            r_resign = inputs[i].checked;

	        if (inputs[i].name == 'banker')
	            r_banker = inputs[i].checked;
	        if (inputs[i].name == 'capter')
	            r_capter = inputs[i].checked;
	        if (inputs[i].name == 'give_medals')
	            r_give_medals = inputs[i].checked;

	        if (inputs[i].name == 'roleId')
	            r_id = inputs[i].value;
	    }
		
	    var params = '';
	    if (typeof(name) == 'undefined' || name == null || name == '') {
	        modal.alert(alertText);
	        return;
	    } else
	        params += 'name=' + encodeURIComponent(name);

	    if (typeof(r_id) != 'undefined' && r_id != null && r_id != '')
	        params += '&id=' + r_id;
			
	    params += '&addmbr=' + r_addmbr;
	    params += '&prommbr=' + r_prommbr;
	    params += '&addpost=' + r_addpost;
	    params += '&resign=' + r_resign;
	    params += '&banker=' + r_banker;
	    params += '&capter=' + r_capter;
	    params += '&give_medals=' + r_give_medals;
	    updater('center', '/OUpdateRole?curPage=posts&' + params);
	},
	
	showInviteForm : function(elem) {
        var pos = getElementPosition(elem);
        var form = document.getElementById('inviteForm');
        var input = document.getElementById('nameToInvite');
        if (input) {
            input.value = '';
        }
        if (form) {
            form.style.left = pos[0] + elem.offsetWidth;
            form.style.top = pos[1];
            form.style.display = '';
        }
    },

    hideInviteForm : function() {
        document.getElementById('inviteForm').style.display = 'none';
    },

    sendInvitation : function(alertText) {
        document.getElementById('inviteResult').innerHTML = '';
        var name = document.getElementById('nameToInvite').value;
        if (!name) {
            modal.alert(alertText);
            return;
        }
        name = encodeURIComponent(name);
        updater('inviteResult', "/InviteMember?name=" + name);
    },
	
	checkRole : function(id){
        
		var tr = document.getElementById('hero'+id);
        var select = tr.getElementsByTagName("select")[0];
        var hids = tr.getElementsByTagName("input");
        var oldRole;
        
		for (var i=0; i< hids.length; i++)
            if (hids[i].name=='oldPost')
                oldRole=hids[i];

        var imgs = tr.getElementsByTagName('button');
        var img;
        for (var i=0; i < imgs.length; i++)
            if (imgs[i].name == "saveButton")
                img=imgs[i];

        if(select.options[select.selectedIndex].value == oldRole.value){
            img.style.display="none";
        }else{
            img.style.display="";
        }
    }
}

var trade = {

    updateTradeData : function(JSONobj) {
        if (JSONobj) {
		
			var mainFr = window.parent.document.getElementById('main_frame');
			var chatFr = window.parent.document.getElementById('chat');
	
			if (mainFr!=null && chatFr!=null) {
			
				var mainFrameDoc = mainFr.contentWindow.document;
				var chatFrame = chatFr.contentWindow;
				
	            if (typeof(JSONobj.op_coins) != 'undefined') {
	                mainFrameDoc.getElementById('offeredMoney').innerHTML = JSONobj.op_coins;
	            }
	            if (typeof(JSONobj.m_coins) != 'undefined'){
	                mainFrameDoc.getElementById('money').value=JSONobj.m_coins;
	            }
	            if (typeof(JSONobj.op_status) != 'undefined') {
	                mainFrameDoc.getElementById('targetReady').checked = JSONobj.op_status;
	            }
	            if (typeof(JSONobj.m_status) != 'undefined') {
	                mainFrameDoc.getElementById('playerReady').checked = JSONobj.m_status;
	            }

	            if (typeof(JSONobj.op_curr) != 'undefined') {
	                mainFrameDoc.getElementById('targetCurrency').innerHTML = JSONobj.op_curr;
	            }
	            if (typeof(JSONobj.duty) != 'undefined') {
	                mainFrameDoc.getElementById('duty').innerHTML = JSONobj.duty;
	            }
	            if (typeof(JSONobj.m_curr) != 'undefined') {
	                var opts = mainFrameDoc.getElementById('currencies').options;
	                for (var i = 0; i < opts.length; i++) {
	                    if (opts[i].value == JSONobj.m_curr)
	                        mainFrameDoc.getElementById('currencies').selectedIndex = i;
	                }
	            }

	            if (typeof(JSONobj.pSubjects) != 'undefined') {
	                var html = '';
	                for (var i = 0; i < JSONobj.pSubjects.length; i++) {
	                    var subj = eval(JSONobj.pSubjects[i]);
	                    if (i > 0)
	                        html += "<hr>";

	                    html += '<table border="0" width="100%">\n' +
	                            '   <tr>\n' +
	                            '       <td colspan="3" class="t_darkGreen">' + subj.name + '</td>\n' +
	                            '   </tr>\n' +
	                            '   <tr>\n' +
	                            '       <td valign="top">\n' +
	                            '           <img src="' + subj.icon + '" class="t_black">\n' +
	                            '       </td>\n' +
	                            subj.info + '\n' +
	                            '   </tr>' +
	                            '</table>';
	                }
	                mainFrameDoc.getElementById('targetSubjects').innerHTML = html;
	            }
	            if (typeof(JSONobj.mSubjects) != 'undefined') {
	                var html = '';
	                for (var i = 0; i < JSONobj.mSubjects.length; i++) {
	                    var subj = eval(JSONobj.mSubjects[i]);
	                    if (i > 0)
	                        html += "<hr>";

	                    html += '<table border="0" width="100%">\n' +
	                            '   <tr>\n' +
	                            '       <td colspan="3" class="t_darkGreen">' + subj.name + '</td>\n' +
	                            '   </tr>\n' +
	                            '   <tr>\n' +
	                            '       <td valign="top">\n' +
	                            '           <a href="#" onClick="trade.removeSubject(' + subj.id + ')">' +
	                            '               <img src="' + subj.icon + '" class="t_black">\n' +
	                            '           </a>' +
	                            '       </td>\n' +
	                            subj.info + '\n' +
	                            '   </tr>' +
	                            '</table>';
	                }
	                mainFrameDoc.getElementById('playerSubjects').innerHTML = html;
	            }

	            mainFrameDoc.getElementById('acceptButton').disabled = !(mainFrameDoc.getElementById('playerReady').checked &&
	                                                                 mainFrameDoc.getElementById('targetReady').checked);
			}
        }
    },

    removeSubject : function(id) {
        trade.showSubject(id);
        sendTradeCmd('rm_subj', id);
    },

    selectSubject : function(id){
        trade.hideSubject(id);
        sendTradeCmd('add_subj', id);
        document.getElementById('bagBrowser').style.display='none';
    },

    showBag : function(elem){
        var pos = getElementPosition(elem);
        var bag = document.getElementById('bagBrowser');
        bag.style.display='';
        bag.style.left=pos[0]+180;
        bag.style.top=pos[1]-25;
    },

    hideBag : function(){
        document.getElementById('bagBrowser').style.display='none';
    },

    hideSubject : function (id){
        document.getElementById('subjItemTable'+id).style.display='none';
    },

    showSubject : function (id){
        document.getElementById('subjItemTable'+id).style.display='';
    },
	
    showAllSubjects : function(){
        var t = document.getElementsByTagName('TABLE');
        for (var i=0; i < t.length; i++){
            if (t[i].id.indexOf('subjItemTable')==0)
                t[i].style.display = '';
        }
    }
}

selectLangOnIndex = function(lang) {
	
	$.ajax({
		type: 'POST',
		dataType: 'json',
		url: '/ChangeLangServlet?index_lang_id=' + lang,
		data: {},
		success: function(data){
			document.location.href = document.location.href;
		}
	});
}
