//$Id: jxweb.js 135 2009-09-30 14:43:18Z hnguyen $
/*******************************************************************************
 * JXwebAuto
 ******************************************************************************/

function JXwebAuto() {
	this.images = ['/Img/o/2.gif', '/Img/o/3.gif'];
	this.options = {
			minFloor: 3,
			maxFloor: 5,
			autoSkill: true,
			autoLevel: true,
			TrainSkill: 6,
			TrainLevel: 7,
			autoRob: true,
			robTimeMin: 0,
			robTimeMax: 1800,
			robLvlMin: 3,
			robLvlMax: 9,
			delay: 1000,
			maxTraining: 90
	};
	this.Heros = {
			lastupdate: 0,
			count: 0,
			countType: null,
			countState: null,
			HK: null,
			needRecruit: null,
			needTrain: null,
			ready: false
	};
	this.Lands = {
			lastupdate: 0,
			spaces: null,
			cities: null,
			friends: null,
			NPC: null
	};
	this.Friends = [];
	this.Victims = [];
	this.Params = {
			TrainSkillPos: 0,
			TrainLevelPos: 0,
			Refresh: 0
	};
	this.Groups = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]];
	this.TTready = false;
	this.enabled = false;
	this.waiting = false;
	this.ControlPanel();
	this.Timers = {update: 0, hero:0, land:0, unit:0, event:0, victim:0, attack:0};
	this.debugInfo = '';

	setInterval('jxw.update()', this.options.delay * 3);
	setInterval('jxw.AutoSmart()', this.options.delay * 5);
	this.jxc = new JXwebConfig();
	setTimeout('jxw.jxc.CookieToConfig();', 500);
	setTimeout('jxw.jxc.ConfigToForm();', 1000);
}

JXwebAuto.prototype.addToggle = function(tarObjId) {
	var ctrlObj = document.createElement('div');
	$(ctrlObj).css({
		'float': 'left',
		'cursor': 'pointer',
		'padding': '1px'
	});
	$(ctrlObj).click(function() {
		$(this).next('div').toggle();
		var img = $(this).find('img')[0];
		if (img.src.match(jxw.images[0])) {
			img.src = jxw.images[1];
		}
		else {
			img.src = jxw.images[0];
		}
	});
	$('<img src="' + this.images[1] + '" style="width:16px;height:16px">').appendTo($(ctrlObj));
	$(ctrlObj).prependTo($('#' + tarObjId));
};

JXwebAuto.prototype.ControlPanel = function() {
	var str = 'div.jxwAuto {position:absolute;z-index:100;border:2px #888 solid;background:#cff;}';
	str += '.jxwAuto input {color:#781351;background:#fee3ad;border:1px solid #781351;text-align:center;}';
	str += '.jxwButton {cursor:pointer;color:#f33}';
	$('style').html($('style').html() + str);
	var str = '<div id="jxwContainer" style="bottom:2px;right:2px;" class="jxwAuto">';
	str += '<div style="width:240px;"><div id="jxwTitle" style="background-color:#ccf;text-align:center;padding:2px;">JXweb autoplay viết bởi jcisio (<span class="jxwButton" id="jxwOnOff">Tắt</span>)</div>';
	str += '<div style="padding:3px;text-align:center;">';
	str += '<input id="jxwOptLevel" name="jxwOpt" value="Level" type="radio"/>Level &nbsp; ';
	str += '<input id="jxwOptSkill" name="jxwOpt" value="Skill" type="radio"/>Skill &nbsp; ';
	str += '<input id="jxwOptRob" name="jxwOpt" value="Rob" type="radio"/>Cướp &nbsp; ';
	str += '<p><span id="jxwRecruit" class="jxwButton">Chiêu mộ</span> - <span id="jxwChange" class="jxwButton">Đổi đội hình</span> - <span id="jxwBophong" class="jxwButton">Bố phòng</span></p>';
	str += '<p id="jxw_HKinfo" style="text-align:left;font-style:italic;font-size:90%;padding-top:5px;"></p>';
	str += '</div></div>';
	$(str).appendTo('body');
	var str = '<div id="jxwContainer2" style="top:2px;left:2px;" class="jxwAuto">';
	str += '<div style="width:320px;"><div id="jxwTitle" style="background-color:#ccf;text-align:center;padding:2px;">Bảng theo dõi/cấu hình (<span class="jxwButton" onclick="CreatePage()">Refresh</span>) $Rev: 135 $</div>';
	str += '<span class="jxwButton" id="jxwCmdSaveConfig" style="bottom:1px;right:1px;position:absolute;">Lưu cấu hình</span>';
	str += '<div style="font-size:90%;">';
	str += '<p>Skill <input name="jxw_SkillXY" type="text" style="width:40px"/> <input type="checkbox" name="jxw_SkillAuto"/> Tu chon ST <select name="jxw_SkillLevel">' + this.HtmlMarkup('level') + '</select> Min <input name="jxw_minFloor" type="text" style="width:10px"/>/<input name="jxw_maxFloor" type="text" style="width:10px"/> Max</p>';
	str += '<p>Level <input name="jxw_LevelXY" type="text" style="width:40px"/> <input type="checkbox" name="jxw_LevelAuto"/> Tu chon ST <select name="jxw_LevelLevel">' + this.HtmlMarkup('level') + '</select></p>';
	str += '<p>Cướp <input name="jxw_RobXYZ" type="text" style="width:120px"/> <input type="checkbox" name="jxw_RobAuto"/> Tu chon</p>';
	str += '<p>Level <input name="jxw_lvlRobMin" type="text" style="width:20px"/>/<input name="jxw_lvlRobMax" type="text" style="width:20px"/> <span class="jxwButton" id="jxwCmdVictims">Tìm</span>. Thời gian <input name="jxw_minRob" type="text" style="width:20px"/>/<input name="jxw_maxRob" type="text" style="width:30px"/> <span class="jxwButton" id="jxwCmdRobReduce">Thu gọn</span></p>';
	str += '<p>Bạn bè <input name="jxw_Friends" type="text" style="width:200px"/> <span class="jxwButton" id="jxwCmdShowVictims">Xem</span></p>';
	str += '<p>Chọn <input name="jxw_ItemName" type="text" style="width:60px" value="(Xe|ti|tr|Ch)"/> để <select name="jxw_ItemAction"><option value="mua">Mua</option><option value="ban">Bán</option><option value="sua">Sua</option><option value="suaki">Sua ki</option><option value="sudung" selected>Sử dụng</option><option value="an">HK ăn</option><option value="thao">Thao</option><option value="thuhoi">Thu hồi</option><option value="huyban">Hủy bán</option></select> giá <input name="jxw_ItemPrice" type="text" style="width:30px"/> xu: <span class="jxwButton" id="jxwCmdItemAction">Thực hiện</span>.';
	str += '<p>HK cần <a href="javascript:void(jxw.simpleAuto(\'recruit\'));">chiêu mộ</a>:<span id="jxw_HKrecruit"></span></p>';
	str += '<p>HK cần <a href="javascript:void(jxw.simpleAuto(\'train\'));">huấn luyện</a>:<span id="jxw_HKtrain"></span></p>';
	str += '</div></div></div>';
	$(str).appendTo('body');
	this.addToggle('jxwContainer');
	this.addToggle('jxwContainer2');
	$('#jxwChange').click(function() {
		jxw.HK_chuyendoihinh();
		alert('Chuyen doi hinh xong!');
	});
	$('#jxwBophong').click(function() {
		jxw.HK_bophong();
	});
	$('#jxwRecruit').click(function() {
		if (jxw.simpleAuto('recruit') == 0) {
			jxw.simpleAuto('train');
			alert('Huan luyen xong!');
		}
		else {
			alert('Chieu mo xong!');
		}
	});
	$('#jxwOnOff').click(function() {
		$(this).text($(this).text() == 'Bật' ? 'Tắt': 'Bật');
		jxw.enabled = !jxw.enabled;
	});
	$('#jxw_SkillLevel').change(function() {
    jxw.Params.TrainSkillPos = (jxw.ST_timkiem($(this).val())).Pos;
	}); 
  $('#jxw_LevelLevel').change(function() {
    jxw.Params.TrainLevelPos = (jxw.ST_timkiem($(this).val())).Pos;
  }); 
	$('#jxwCmdSaveConfig').click(function() {
		jxw.jxc.FormToConfig();
		jxw.jxc.ConfigToCookie();
		alert('Luu cau hinh thanh cong.');
	});
	$('#jxwCmdItemAction').click(function() {
		jxw.Item_tudong($('select[name=jxw_ItemAction]').val(), $('input[name=jxw_ItemName]').val(), $('input[name=jxw_ItemPrice]').val());
	});
	$('#jxwCmdVictims').click(function() {
		if (!jxw.checkTimers('victim', 30)) return;
		alert('Bat dau tim. Xin vui long doi mot lat.');
		var Victims = jxw.SearchVictims(2, jxw.options.robLvlMin, jxw.options.robLvlMax);
		if (jxw.Victims == null) jxw.Victims = [];
		for (var k=0; k<Victims.length; k++) {
			var exists = false;
			for (var j=0; j<jxw.Victims.length; j++) {
				if (jxw.Victims[j].Pos==Victims[k].Pos) {
					Victims[k].LastAttack = jxw.Victims[j].LastAttack;
					jxw.Victims[j] = Victims[k];
					exists = true;
					break;
				}
			}
			if (! exists) {
				jxw.Victims.push(Victims[k]);
			}
		}
		jxw.jxc.updateVictims();
		alert('Da cap nhat danh sach');
	});
	$('#jxwCmdShowVictims').click(function() {
		if ($('#jxwListVictims').length == 0) {
			var str = '<div id="jxwListVictims" class="jxwAuto" style="position:absolute;top:100px;left:200px">';
			str += '<div style="width:400px;"><div id="jxwVictimsTitle" style="background-color:#ccf;text-align:center;padding:2px;">Danh sach nan nhan (<span id="jxwVictimsOnOff" class="jxwButton">Bat/Tắt</span>)</div>';
			str += '<div style="padding:3px;text-align:center;height:300px;overflow-y:scroll;" id="jxwVictimsContent">';
			str += '</div></div>';
			$(str).appendTo('body');
			$('#jxwListVictims').toggle();
			$('#jxwVictimsOnOff').click(function() {$('#jxwListVictims').toggle();});
		}
		var html = '<table width="100%"><tr><th>Ten</th><th>City</th><th>Level</th><th>Last attack (h)</th><th>Pos</th><th>Time</th></tr>';
		var now = Number(new Date());
		var vic = jxw.Victims.slice();
		vic.sort(function(a,b) {return a.LastAttack-b.LastAttack;});
		for (var k=0; k<vic.length; k++) {
			var xy = jxw.posxy(vic[k].Pos);
			html += '<tr><td>' + vic[k].UserName + '</td><td>' + vic[k].Name + '</td>';
			html += '<td>' + jxw.JXlevel(vic[k].Level) + '</td><td>' + (vic[k].LastAttack > 10000 ? Math.round((now-vic[k].LastAttack)/1000/360)/10 : 'N/A') + '</td>';
			html += '<td>' + xy.x + ',' + xy.y + '</td><td>' + jxw.TravelTime(jxw.posxy(vic[k].Pos)) + '</td></tr>';
		}	
		html += '</table>';
		$('#jxwVictimsContent').html(html);
		$('#jxwListVictims').toggle();
	});
	// xoa, giu danh sach theo thoi gian di
	$('#jxwCmdRobReduce').click(function() {
		var newVictims = [];
		var tTime = 0;
		for (var j=0; j<jxw.Victims.length; j++) {
			var robTime = jxw.TravelTime(jxw.posxy(jxw.Victims[j].Pos));
			if ((robTime>=jxw.options.robTimeMin && robTime<=jxw.options.robTimeMax) || (jxw.Victims[j].Level-(robTime-jxw.options.robTimeMax)/150>=jxw.options.robLvlMin+3 && jxw.Victims[j].Level<=jxw.options.robLvlMax)) {//heuristics
				newVictims.push(jxw.Victims[j]);
				tTime += robTime;
			}
		}
		jxw.Victims = newVictims.slice();
		alert('Loc xong. Tong thoi gian cuop khoang: ' + Math.round(tTime*2/360)/10 + ' gio.');
	});
};
JXwebAuto.prototype.HtmlMarkup = function(option) {
	var str = '';
	switch (option) {
	case 'level':
		var lvl = [1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95];
		for (var k = 0; k < lvl.length; k++) {
			str += '<option value="' + (k + 1) + '">' + lvl[k] + '</option>';
		}
	}
	return str;
};

JXwebAuto.prototype.checkTimers = function(what, duration) {
	var now = Number(new Date());
	if (now > eval('jxw.Timers.'+what) + duration*1000) {
		eval('jxw.Timers.'+what+' = '+now);
		return true;
	}
	else {
		return false;
	}
}

// check nv thu thap
JXwebAuto.prototype.checkCollect = function() {
	return MapUnitInfo == null ? false: (HasEventSerach() < 0);
};
JXwebAuto.prototype.JXlevel = function(level) {
	return (level > 0 && level < 21) ? Lang['Main_' + level] : 'Unknown';
};
JXwebAuto.prototype.updateLands = function() {
	var now = Number(new Date());
	if (this.Lands.lastupdate > now - 10 * 1000) return; // update every 5
	// seconds
	if (MapUnitInfo == null || LandformInfo == null) {
		if (ViewNumX == 1 && ViewNumY == 1) {
			var xy = this.posxy(UserInfo.CityList[0].Pos);
			ViewNumX = xy.x-4;
			ViewNumY = xy.y-4;
		}
		if (LandformInfo == null && jxw.checkTimers('land', 30)) {
			var pos = (ViewNumY + 4 - 1) * 400 + ViewNumX + 4;
			Main.GetWorldLandform(CityID, pos, function(result) {
				if (DataValidate(result) == false) return;
				LandformInfo = result.value;
			});
		}
		if (MapUnitInfo == null && jxw.checkTimers('unit', 30)) {
			var pos = (ViewNumY + 4 - 1) * 400 + ViewNumX + 4;
			Main.GetMapUnitInfo(CityID, 3, pos, function(result) {
				if (DataValidate(result) == false) return;
				MapUnitInfo = result.value;
			});
		}
		return;
	}
	else {
		var Lands = LandformInfo;
		var Units = MapUnitInfo;
	}
	this.Lands.lastupdate = now;
	this.Lands.spaces = new Array();
	this.Lands.cities = new Array();
	this.Lands.friends = new Array();
	this.Lands.NPC = new Array();

	var UnitList = new Array(Units.length);
	for (var k = 0; k < Units.length; k++) {
		UnitList[k] = Units[k].Pos;
	}
	UnitList.sort(function(a, b) {
		return a - b;
	});
	k = 0;
	for (var j = 0; j < Lands.length; j++) {
		if (Lands[j].Pos == UnitList[k]) {
			if (Units[k].Type == 5) {
				this.Lands.cities.push(Units[k]);
			}
			else {
				this.Lands.NPC.push(Units[k]);
			}
			k++;
		}
		else {
			this.Lands.spaces.push(Lands[j]);
		}
	}
	for (var j = 0; j < this.Friends.length; j++) {
		this.Lands.friends.push(this.xypos(this.Friends[j].x, this.Friends[j].y));
	}
}
JXwebAuto.prototype.updateHeros = function() {
	var now = Number(new Date());
	//this.debug('Update hero');
	if (this.Heros.lastupdate > now - 3000) return; // update every 5
	// seconds
	if (HeroInfo == null) {
		if  (this.checkTimers('hero', 30)) {
			this.debug('Get hero');
			Main.GetCityHero(CityID, cb_GetCityHero);
			this.Heros.lastupdate = now;			
		}
		return;
	}
	this.Heros.HK = HeroInfo;
	this.Heros.count = CityInteriorInfo == null ? 0 : CityInteriorInfo.EngageHeroNum; // equals
	// to
	// Heros.HK.length
	this.Heros.countType = [0, 0, 0, 0, 0, 0];
	/* 1,2,3 haubi tancong bophong */
	this.Heros.countState = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
	/* 1binhthuong 2trongthuong 3chieumo 4huanluyen 5taingoai 7trogiup 8bequan */
	this.Heros.needRecruit = '';
	this.Heros.needTrain = '';
	this.Heros.ready = true;

	for (var k = 0; k < this.Heros.count; k++) {
		if (HeroInfo[k] == null) continue;
		var H = HeroInfo[k];
		this.Heros.countType[H.ListType]++;
		this.Heros.countState[H.State]++;
		if (H.PrenticeNum < H.MaxPrenticeNum && H.State == 1) {
			this.Heros.needRecruit += ' ' + H.Name + '(' + H.PrenticeNum + '/' + H.MaxPrenticeNum + ')';
		}
		if (H.Training < this.options.maxTraining && H.State == 1) {
			this.Heros.needTrain += ' ' + H.Name + '(' + H.Training + '%)';
		}
		if (H.ListType == 2 && H.State != 1) {
			this.Heros.ready = false;
		}
	}
}
JXwebAuto.prototype.update = function() {
	var info = '';
	this.TTready = this.checkCollect();
	this.updateLands();
	this.updateHeros();
	var flag = false;
	if (EventInfo != null) for (var j = 0; j < EventInfo.length; j++) {
		if (EventInfo[j].RemainTime < 1) flag = true;
	}
	if (flag && jxw.checkTimers('event', 30)) Main.GetValidEvent(CityID, cb_GetValidEvent);       

	if (HeroInfo == null || MapUnitInfo == null) {
		info = 'Không thấy dữ liệu.';
	}
	else if (this.Heros != null) {
		var H = this.Heros;
		info = 'Trạng thái: ' + Math.round((Number(new Date()) - this.Lands.lastupdate) / 1000) + ' giây. ';
		info += 'HK: ' + (H.countState[1] + H.countState[2] + H.countState[8]) + ' home, ' + (H.countState[5] + H.countState[7]) + ' out, ' + (H.countState[3] + H.countState[4]) + ' busy. ';
		info += (H.ready ? 'Sẵn sàng': 'Không sẵn sàng') + ' xuất trận. ';
		info += (this.TTready ? 'Có thể': 'Đang') + ' thu thập.';
		$('#jxw_HKrecruit').text(this.Heros.needRecruit);
		$('#jxw_HKtrain').text(this.Heros.needTrain);
	}
	$('#jxw_HKinfo').text(info);
}
JXwebAuto.prototype.wait = function(s, t) {
	this.timer.general = setTimeout('jxw.' + s + '()', t * this.options.delay);
}
JXwebAuto.prototype.xypos = function(x, y) {
	return x + (y - 1) * 400;
}
JXwebAuto.prototype.posxy = function(pos) {
	var x = (pos - 1) % 400 + 1;
	var y = Math.round((pos - x) / 400) + 1;
	return {
		x: x,
		y: y
	};
}
JXwebAuto.prototype.xyindex = function(x, y) {
	return (x - ViewNumX) + (y - ViewNumY) * 9;
}
JXwebAuto.prototype.debug = function(msg) {
	this.debugInfo += (new Date()) + " " + msg + "\n";
}
/* click on a city (in the same screen) */
JXwebAuto.prototype.ClickCity = function(x, y) {
	ClickCity('world_landform_5_' + ((x - ViewNumX) + (y - ViewNumY) * 9));
}
/* get city info (tree command) */
JXwebAuto.prototype.InfoCity = function(x, y) {
	// var cmd = HtmlTreeCommand(this.xyindex(x,y), NodeBlank,
	// this.xyindex(x,y));
}
JXwebAuto.prototype.SearchVictims = function(range, minLevel, maxLevel) {
	var PosArray = [];
	var Victims = [];
	var xy = this.posxy(UserInfo.CityList[0].Pos);
	var c = {x:0,y:0};
	for (var k=0; k<range; k++) {
		if (k == 0) {
			PosArray = [[0,0]];
		} 
		else {
			PosArray = [];
			for (var l=0; l<2*k; l++) {
				PosArray.push([-k+l, -k]);
				PosArray.push([k, l-k]);
				PosArray.push([k-l, k]);
				PosArray.push([-k, k-l]);
			}
		}

		for (var j=0; j<PosArray.length; j++) {
			// set up the center
			c.x = Math.max(5, Math.min(396, xy.x + PosArray[j][0]*9));
			c.y = Math.max(5, Math.min(396, xy.y + PosArray[j][1]*9));
			// get cities
			var ret = Main.GetMapUnitInfo(CityID, 3, this.xypos(c.x, c.y));
			if (ret.error != null) continue;
			var Units = ret.value;
			if (Units!=null)
				o:for (var jj=0; jj<Units.length; jj++) {
					var U = Units[jj];
					var iTime = this.TravelTime(this.posxy(U.Pos));
					if (U.Type == 5 && U.Level <= maxLevel && U.Level >= minLevel && U.Pos != UserInfo.CityList[0].Pos) {
						// kiem tra thoi gian & bang hoi
						if ((U.JuntaName!=UserInfo.Organise)) {
							// check duplicate
							for (var i=0; i<Victims.length; i++) {
								if (Victims[i].Pos == U.Pos) continue o;
							}
							Victims.push({Pos:U.Pos, Level:U.Level,Name: U.Name, UserName:U.UserName, LastAttack:iTime});
						}
					} 
				}
		}
	}
	return Victims;
}
JXwebAuto.prototype.GetCityID = function(x, y) {
	if (typeof(MapUnitInfo) == 'undefined' || x < ViewNumX || y < ViewNumY || x > ViewNumX + 8 || y > ViewNumY + 8) {
		alert(0);
	}
	else {
		var pos = this.xypos(x, y);
		for (var k = 0; k < MapUnitInfo.length; k++) {
			if (MapUnitInfo[k].Pos == pos) {
				alert(MapUnitInfo[k].ID);
			}
		}
	}
}

/* click on a given text link */
JXwebAuto.prototype.ClickText = function(text) {
	var cmdId = null;
	$('.node_handle_a').each(function(i) {
		if (this.innerText.indexOf(text) > -1) {
			cmdId = this.id;
		}
	});
	if (cmdId) {
		TreeCommand(cmdId);
		return true;
	}
	else {
		return false;
	}
}

JXwebAuto.prototype.TravelTime = function(xy) {
	var homeland = this.posxy(UserInfo.CityList[0].Pos);
	return Math.round(18 * Math.sqrt(Math.pow(homeland.x - xy.x, 2) + Math.pow(homeland.y - xy.y, 2))) * 5 + 210;
}

JXwebAuto.prototype.HK_haubi = function(idx) {
	Main.ChangeHeroListType(CityID, this.Heros.HK[idx].ID, 1, null);
}
JXwebAuto.prototype.HK_xuatchien = function(idx) {
	Main.ChangeHeroListType(CityID, this.Heros.HK[idx].ID, 2, null);
}
JXwebAuto.prototype.HK_chieumo = function(idx) {
	Main.AddHeroEvent(CityID, 10, 4, this.Heros.HK[idx].ID, this.Heros.HK[idx].MaxPrenticeNum - this.Heros.HK[idx].PrenticeNum, null);
}
JXwebAuto.prototype.HK_huanluyen = function(idx) {
	Main.AddHeroEvent(CityID, 9, 4, this.Heros.HK[idx].ID, 0, null);
}
JXwebAuto.prototype.HK_chuyendoihinh = function() {
	var HK = this.Heros.HK;
	for (var k = 0; k < HK.length; k++) {
		if (HK[k].ListType == 2) this.HK_haubi(k);
	}
	for (var k = 0; k < HK.length; k++) {
		if (HK[k].ListType != 2) this.HK_xuatchien(k);
	}
	Main.GetCityInteriorInfo(CityID, cb_GetCityInteriorInfo);
}
JXwebAuto.prototype.HK_bophong = function() {
	var ViTri = [160, 161, 162, 163, 164];
	var j = 0;
	for (var k = 0; k < this.Heros.count; k++) {
		if (this.Heros.HK[k].ListType == 1 && j < 5) {
			Main.SetHeroDefence(CityID, this.Heros.HK[k].ID, ViTri[j++], null);
		}
	}
	if (j > 0) {
		Main.GetCityInteriorInfo(CityID, cb_GetCityInteriorInfo);
		alert('Bo phong xong!');
	}
}
JXwebAuto.prototype.HK_thucluc = function(idx) {
	var H = this.Heros.HK[idx];
	var ATT = H.Attack;
	var DEF = H.Defence;
	var RES = 0;
	var PRE = H.PrenticeNum*H.Training;
	var DOD = H.CrushBlow + H.Dodge;
	for (var k=0; k<H.ItemList.length; k++) {
		ATT += H.ItemList[k].Attack;
		DEF += H.ItemList[k].Defence;
		RES += H.ItemList[k].CR + H.ItemList[k].DR + H.ItemList[k].FR + H.ItemList[k].LR;
	}
	ATT += H.SkillList[0].EffValue*H.SkillList[0].SkillLevel*0;
	return ATT*66 + DEF*66 + RES*66 + PRE; 
}

JXwebAuto.prototype.ST_tancong = function(pos) {
	EventPopTemp = '11_5_0_' + pos;
	AddAttackEvent();
}
JXwebAuto.prototype.ST_dotham = function(pos) {
	EventPopTemp = '48_5_0_' + pos;
	AddAttackEvent();
}
JXwebAuto.prototype.ST_timkiem = function(level) {
	var NPCeval = new Array(this.Lands.NPC.length);
	for (var j = 0; j < this.Lands.NPC.length; j++) {
		// 600 sec = 4 lv
		NPCeval[j] = Math.abs(this.Lands.NPC[j].Level - level) + this.TravelTime(this.posxy(this.Lands.NPC[j].Pos)) / 150;
	}
	var minIdx = 0;
	for (var j = 1; j < NPCeval.length; j++) {
		if (NPCeval[j] < NPCeval[minIdx]) {
			minIdx = j;
		}
	}
	return this.Lands.NPC[minIdx];
}
JXwebAuto.prototype.ST_kiemtra = function(pos) {
	var ST = {
			pos: pos,
			NPC: false,
			currentStage: 0,
			maxStage: 0
	};
	if (MapUnitInfo == null) return ST;
	for (var k = 0; k < MapUnitInfo.length; k++) {
		if (MapUnitInfo[k].Pos == ST.pos) break;
	}
	if (k < MapUnitInfo.length) {
		ST.NPC = true;
		ST.curFloor = MapUnitInfo[k].NpcFloor;
		ST.maxFloor = MapUnitInfo[k].NpcFloorMax;
	}
	return ST;
}

JXwebAuto.prototype.Item_tudong = function(action, pattern, price) {
// alert('Hanh dong '+action+ ' mau ' + pattern + ' gia tri "'+value+'"');
	if (ItemInfo == null) return;
	var re = new RegExp(pattern);
	price = parseInt(price);
	var total = 0;
	for (var k = 0; k < ItemInfo.length; k++) {
		TheItemInfo = ItemInfo[k];
		if (!TheItemInfo.Name.match(re) && !('USER'+TheItemInfo.UserName).match(re) && !('LEVEL'+TheItemInfo.Level==pattern)) continue;
		total++;

		switch (action) {
		case 'sudung':
			if (TheItemInfo.UseType == 3) {
				Main.UseItemRes(CityID, TheItemInfo.ID, null);
			}
			else if (TheItemInfo.UseType == 2) {
				Main.UseItem(CityID, TheItemInfo.ID, null);
			}
			else if (TheItemInfo.UseType == 4) {
				Main.UseFeastItem(CityID, TheItemInfo.ID, null);
			}
			break;
		case 'an':
			if (TheItemInfo.UseType == 5) {
				Main.UseItemHeroExp(CityID, TheItemInfo.ID, HeroInfo[price-1].ID);
			}
			break;
		case 'huyban':
			Main.CancleSellItem(CityID, TheItemInfo.ID, null);
			break;
		case 'ban':
			if (TheItemInfo.State == 1) { // from 1: ["Bình thường", "Vận chuyển",
				// "Trang bị", "Đang bán", "Mang ra
				// ngoài"]
				Main.SellItem(CityID, TheItemInfo.ID, price, null);
			}
			break;
		case 'thuhoi':
		  if (TheItemInfo.State == 1) {
		    Main.DonateItem(CityID, TheItemInfo.ID, null);
		  }
			break;
		case 'thao':
		  if (TheItemInfo.State == 1) {
		    Main.DisassembleItem(CityID, TheItemInfo.ID, TheItemInfo.StaticIndex, null);
		  }
			break;
		case 'mua':
			if ((TheItemInfo.State == 4) && (TheItemInfo.Price<=price)) {
				Main.BuyItem(CityID, TheItemInfo.ID, TheItemInfo.Price, null);
			}
		case 'sua':
		case 'suaki':
			if (TheItemInfo.State == 3) {// chi sua trang bi tren nguoi
				if (action=='sua') {
					Main.RepairItemGeneral(CityID, TheItemInfo.ID, null);
				}
				else {
					Main.RepairItem(CityID, TheItemInfo.ID, null);
				}
				// tree_a_9_36_0_0 sua ki ItemRepair()
				// tree_a_9_37_0_0 sua CommonItemRepair()
			}
			break;
		default:
		}
	}
	if (total > 0) FreshItemPage(true);
}

JXwebAuto.prototype.City_tancong = function(pos, uid) {
	// var xy = this.posxy(pos);
	// console.log('Tan cong '+this.TravelTime(xy)+ ' ('+xy.x+','+xy.y+')');
	// return;
	EventPopTemp = '11_5_' + uid + '_' + pos;
	AddAttackEvent();
}

JXwebAuto.prototype.Blank_thuthap = function() {
	if (this.Lands.spaces == null) {
		return false;
	}
	Main.AddSearchEvent(CityID, this.Lands.spaces[0].Pos, cb_AddEvent);
}

JXwebAuto.prototype.simpleAuto = function(action) {
	var j = 0;
	switch (action) {
	case 'rob':
		if (! this.checkTimers('attack', 10)) break;
		if (this.options.autoRob) {
			if (this.Victims==null) this.Victims = [];
			if (this.Victims.length==0) {
				if (this.checkTimers('victim', 60))
					this.Victims = this.SearchVictims(2, this.options.robLvlMin, this.options.robLvlMax);
				else
					return;
			}
			var minIdx = 0;
			var now = Number(new Date());
			for (var k=1; k<this.Victims.length; k++) {
				if (this.Victims[k].LastAttack < now-86400000) {
					this.Victims[k].LastAttack = now-86400000+this.TravelTime(this.posxy(this.Victims[k].Pos));
				}
				if ((this.Victims[k].LastAttack < this.Victims[minIdx].LastAttack) && ($.inArray(this.Victims[k].Pos, this.Lands.friends)==-1)) {
					minIdx = k;
				}
			}
			var LastAttack = $.cookie('LastAttack') ? $.json.decode($.cookie('LastAttack')) : null;
			if (LastAttack != null && LastAttack.Time+20000>now) {// duplicate,
				// lag...
				minIdx = LastAttack.Idx;
			}
			else {
				LastAttack = {Idx:minIdx, Time:now};
				this.Victims[minIdx].LastAttack = now;
				$.cookie('LastAttack', $.json.encode(LastAttack), {expires:30});
			}
			this.City_tancong(this.Victims[minIdx].Pos, this.Victims[minIdx].ID);
			Main.GetCityHero(CityID, cb_GetCityHero);
			this.jxc.updateVictims();
		}
		break;
	case 'collect':
		this.Blank_thuthap();
		break;
	case 'train':
		var j = 0;
		for (var k = 0; k < this.Heros.HK.length; k++) {
			if (this.Heros.HK[k].Training < this.options.maxTraining && this.Heros.HK[k].State == 1) {
				jxw.HK_huanluyen(k);
				j++;
			}
		}
		if (j>0) Main.GetCityHero(CityID, cb_GetCityHero);
		break;
	case 'recruit':
		var j = 0;
		for (var k = 0; k < this.Heros.HK.length; k++) {
			if (this.Heros.HK[k].PrenticeNum < this.Heros.HK[k].MaxPrenticeNum && this.Heros.HK[k].State == 1) {
				jxw.HK_chieumo(k);
				j++;
			}
		}
		if (j>0) {alert('Da chieu mo '+j+' HK');Main.GetCityHero(CityID, cb_GetCityHero);}
		break;
	case 'level':
		if (! this.checkTimers('attack', 10)) break;

		if (this.options.autoLevel) {
			if (this.Params.TrainLevelPos == 0) { // auto detect ST
				this.Params.TrainLevelPos = (this.ST_timkiem(this.options.TrainLevel)).Pos;
			}
			this.ST_tancong(this.Params.TrainLevelPos);
		}
		else {
			this.ST_tancong(this.xypos(this.NPC[1].x, this.NPC[1].y));
		}
		Main.GetCityHero(CityID, cb_GetCityHero);
		break;
	case 'skill':
		if (! this.checkTimers('attack', 10)) break;

		var pos;
		if (this.options.autoSkill) {
			if (this.Params.TrainSkillPos == 0) { // auto detect ST
				this.Params.TrainSkillPos = (this.ST_timkiem(this.options.TrainSkill)).Pos;
			}
			pos = this.Params.TrainSkillPos;
		}
		else {
			pos = this.xypos(this.NPC[2].x, this.NPC[2].y)
		}
		var ST = this.ST_kiemtra(pos);
		if (ST.NPC) {
			if (ST.curFloor == 0 || ST.maxFloor < this.options.minFloor || ST.curFloor > this.options.maxFloor) {
				this.ST_tancong(ST.pos);
			}
			else {
				this.ST_dotham(ST.pos);
			}
		}
		Main.GetCityHero(CityID, cb_GetCityHero);
		break;
	default:
		break;
	}
	return j;
}
JXwebAuto.prototype.AutoSmart = function() {
	if (this.checkCollect()) {
	//	setTimeout("jxw.simpleAuto('collect')", this.options.delay);
	}
	if (this.Heros.ready && this.enabled) {
		var options = $("input[name='jxwOpt']:checked").val();
		switch (options) {
		case 'Skill':
			this.simpleAuto('skill');
			break;
		case 'Level':
			setTimeout("jxw.simpleAuto('level')", this.options.delay);
			break;
		case 'Rob':
			this.simpleAuto('rob');
			break;
		}
	}
}

/*******************************************************************************
 * JXwebConfig
 ******************************************************************************/
function JXwebConfig() {}

JXwebConfig.prototype.CookieToConfig = function() {
	var tmp = $.cookie('options');
	if (tmp != null) jxw.options = $.json.decode(tmp);
	tmp = $.cookie('Friends');
	if (tmp != null) jxw.Friends = $.json.decode(tmp);
	tmp = $.cookie('Victims');
	if (tmp != null) {
		jxw.Victims = [];
		tmp = $.json.decode(tmp);
		for (var k=0; k<tmp.length; k++) {
			if (tmp[k].Pos > 0) {jxw.Victims.push(tmp[k]);}
			else {jxw.Victims.push({Pos:tmp[k].P, LastAttack:tmp[k].L, Name:'', UserName:'', Level:0});}
		}
	}
};

JXwebConfig.prototype.ConfigToCookie = function() {
	$.cookie('options', $.json.encode(jxw.options), {
		expires: 30
	});
	$.cookie('Friends', $.json.encode(jxw.Friends), {
		expires: 30
	});
	// due to cookie limit of 4Kb, we store only Pos, LastAttack
	var tmp = [];
	for (var k=0; k<jxw.Victims.length;k++) {tmp.push({P:jxw.Victims[k].Pos,L:jxw.Victims[k].LastAttack});}
	$.cookie('Victims', $.json.encode(tmp), {
		expires: 30
	});
}

JXwebConfig.prototype.updateVictims = function() {
// $.cookie('Victims', $.json.encode(jxw.Victims), {expires: 30});
	this.ConfigToCookie();
}

JXwebConfig.prototype.FormToConfig = function() {
	jxw.options.autoSkill = $('input[name=jxw_SkillAuto]').attr('checked');
	jxw.options.autoLevel = $('input[name=jxw_LevelAuto]').attr('checked');
	jxw.options.autoRob = $('input[name=jxw_RobAuto]').attr('checked');
	jxw.options.minFloor = parseInt($('input[name=jxw_minFloor]').val());
	jxw.options.maxFloor = parseInt($('input[name=jxw_maxFloor]').val());
	jxw.options.robTimeMin = parseInt($('input[name=jxw_minRob]').val());
	jxw.options.robTimeMax = parseInt($('input[name=jxw_maxRob]').val());
	jxw.options.robLvlMin = parseInt($('input[name=jxw_lvlRobMin]').val());
	jxw.options.robLvlMax = parseInt($('input[name=jxw_lvlRobMax]').val());
	jxw.options.TrainSkill = parseInt($('select[name=jxw_SkillLevel]').val());
	jxw.options.TrainLevel = parseInt($('select[name=jxw_LevelLevel]').val());
	var tmp = $('input[name=jxw_Friends]').val().split(';');
	jxw.Friends = [];
	if (tmp[0] != '')// empty
		for (var k=0; k<tmp.length; k++) {
			var t2 = tmp[k].split(',');
			jxw.Friends.push({x:Number(t2[0]),y:Number(t2[1])});
		}	  
}

JXwebConfig.prototype.ConfigToForm = function() {
	$('input[name=jxw_SkillAuto]').attr('checked', jxw.options.autoSkill);
	$('input[name=jxw_LevelAuto]').attr('checked', jxw.options.autoLevel);
	$('input[name=jxw_RobAuto]').attr('checked', jxw.options.autoRob);
	$('input[name=jxw_RobXYZ]').val('');
	$('input[name=jxw_minFloor]').val(jxw.options.minFloor);
	$('input[name=jxw_maxFloor]').val(jxw.options.maxFloor);
	$('input[name=jxw_minRob]').val(jxw.options.robTimeMin);
	$('input[name=jxw_maxRob]').val(jxw.options.robTimeMax);
	$('input[name=jxw_lvlRobMin]').val(jxw.options.robLvlMin);
	$('input[name=jxw_lvlRobMax]').val(jxw.options.robLvlMax);
	$('select[name=jxw_SkillLevel]').val(jxw.options.TrainSkill);
	$('select[name=jxw_LevelLevel]').val(jxw.options.TrainLevel);
	var tmp = [];
	for (var k=0; k<jxw.Friends.length; k++) {
		tmp.push(jxw.Friends[k].x + ',' + jxw.Friends[k].y);
	}
	$('input[name=jxw_Friends]').val(tmp.join(';'));
}

/*******************************************************************************
 * JSON plugin
 ******************************************************************************/
$.json = {
		encode: function(value, replacer, space) {
	var i;
	gap = '';
	var indent = '';

	if (typeof space === 'number') {
		for (i = 0; i < space; i += 1) {
			indent += ' ';
		}
	} else if (typeof space === 'string') {
		indent = space;
	}

	rep = replacer;
	if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
		throw new Error('JSON.encode');
	}

	return this.str('', {
		'': value
	});
},

decode: function(text, reviver) {
	var j;
	var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

	function walk(holder, key) {
		var k, v, value = holder[key];

		if (value && typeof value === 'object') {
			for (k in value) {
				if (Object.hasOwnProperty.call(value, k)) {
					v = walk(value, k);
					if (v !== undefined) {
						value[k] = v;
					} else {
						delete value[k];
					}
				}
			}
		}
		return reviver.call(holder, key, value);
	}

	cx.lastIndex = 0;

	if (cx.test(text)) {
		text = text.replace(cx, function(a) {
			return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice( - 4);
		});
	}

	if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
		j = eval('(' + text + ')');
		return typeof reviver === 'function' ? walk({
			'': j
		},
		'') : j;
	}

	throw new SyntaxError('JSON.parse');
},

f: function(n) {
	return n < 10 ? '0' + n: n;
},

DateToJSON: function(key) {
	return this.getUTCFullYear() + '-' + this.f(this.getUTCMonth() + 1) + '-' + this.f(this.getUTCDate()) + 'T' + this.f(this.getUTCHours()) + ':' + this.f(this.getUTCMinutes()) + ':' + this.f(this.getUTCSeconds()) + 'Z';
},

StringToJSON: function(key) {
	return this.valueOf();
},

quote: function(string) {
	var meta = {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"': '\\"',
			'\\': '\\\\'
	};
	var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

	escapable.lastIndex = 0;
	return escapable.test(string) ? '"' + string.replace(escapable, function(a) {
		var c = meta[a];
		return typeof c === 'string' ? c: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice( - 4);
	}) + '"': '"' + string + '"';
},

str: function(key, holder) {
	var indent = '',
	gap = '',
	i, k, v, length, mind = gap,
	partial, value = holder[key];

	if (value && typeof value === 'object') {
		switch ((typeof value)) {
		case 'date':
			this.DateToJSON(key);
			break;
		default:
			this.StringToJSON(key);
		break;
		}
	}

	if (typeof rep === 'function') {
		value = rep.call(holder, key, value);
	}
	switch (typeof value) {
	case 'string':
		return this.quote(value);
	case 'number':
		return isFinite(value) ? String(value) : 'null';
	case 'boolean':
	case 'null':
		return String(value);
	case 'object':
		if (!value) {
			return 'null';
		}
		gap += indent;
		partial = [];

		if (Object.prototype.toString.apply(value) === '[object Array]') {
			length = value.length;

			for (i = 0; i < length; i += 1) {
				partial[i] = this.str(i, value) || 'null';
			}

			v = partial.length === 0 ? '[]': gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']': '[' + partial.join(',') + ']';
			gap = mind;
			return v;
		}

		if (rep && typeof rep === 'object') {
			length = rep.length;
			for (i = 0; i < length; i += 1) {
				k = rep[i];
				if (typeof k === 'string') {
					v = this.str(k, value);
					if (v) {
						partial.push(this.quote(k) + (gap ? ': ': ':') + v);
					}
				}
			}
		} else {
			for (k in value) {
				if (Object.hasOwnProperty.call(value, k)) {
					v = this.str(k, value);
					if (v) {
						partial.push(this.quote(k) + (gap ? ': ': ':') + v);
					}
				}
			}
		}

		v = partial.length === 0 ? '{}': gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}': '{' + partial.join(',') + '}';
		gap = mind;
		return v;
	}
}
};
/*******************************************************************************
 * COOKIE plugin
 ******************************************************************************/
$.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute,
			// max-age is not supported
			// by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure': '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

/********************
 * INIT
 ********************/
function Teacher_Reshow() {// overload to hide teacher
  $('#teacher').hide();
};

$('#logo').hide();// ugly logo

var jxw = new JXwebAuto();
$('#jxwOptRob').attr('checked', true);
//var hh=470;$('#warpaper_content').css('height', hh+'px');$('.warpaper_popup1').css('height', (hh+79)+'px');

function cb_ProcessOverdueEvent(result) {
	jxw.debug('Overdue '+result.value);
	if(DataValidate(result)==false) return false;
					 
	if(result.value==0)
	{        
			 if(IsFlash==0)
					 Main.GetCityInteriorInfo(CityID,cb_GetCityInteriorInfo);
			 else
					 Main.GetCityInteriorInfo(CityID,cb_EventUpdate);
			 
			 if(EventNeedMail==1)
					 Main.GetNewMailNum(cb_GetNewMailNum);
	}
	else
	{
			 EventNeedMail=0;
			 if(result.value==1)
					Main.GetValidEvent(CityID,cb_GetValidEvent);
			 else if(result.value==2)
					Main.GetCityInteriorInfo(CityID,cb_EventUpdate);
			 else   
					DataTranslateEnd();   
	}
}

function cb_GetValidEvent(result) {
	jxw.debug('Get events');
	if(DataValidate(result)==false) return;
			
	EventInfo=result.value;
	if(EventInfo!=null && EventInfo[0].ID==-1)
			EventInfo=null;    
				
	ShowEvent();
	
	ShowEventMapUnit();//显示事件地图布局
		
	UpdateControlTarget();//更新当前控制对象
	
	PageInitState=1;//页面初始化完毕
	
	Main.GetPersistEffectGroup(CityID,cb_GetPersistEffectGroup);
	
	Main.KickUser(); 
	IsFlash==0;
	
	HasCanQuickReturn();
	
	HideTips();
}

function EventNeedFlash(objType) {// override the flash function to update HeroInfo, independant on PageNum
	jxw.debug('Checkevent type '+objType);
	if (jxw.checkTimers('hero', 5)) setTimeout('Main.GetCityHero(CityID, cb_GetCityHero);', 5000);
  switch(objType) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
      return 1;
      break;
  }
  return false;
}
//function EventNeedFlash(objType) {return false;}

