var c_stat;
var UPG_20 = Math.pow(1.007, 20) - 1;
var times = [1, 24, 168, 730, 8766];
var SERVER = {
	T2_5:0,
	T3_5:1, T3_5_X3:2,
	T3_51:3, T3_51X3:4,
	T3_6:5,
	T3_X5:6, T3_X10:1,
	build_speeds: [
		[1,	1,		1],
		[1,	1,		1],
		[3,	3,		3],
		[1.25,1.25,	1],
		[3.75,3.75,	3],
		[2.5,	2.5,	2],
		[6.25,6.25,	5],
		[12.5,12.5,	10]
	],
	is_3_5: function(type) {
		return type != SERVER.T2_5;
	},
	has_heroes: function (type) {
		return type != SERVER.T2_5;
	}
};
var has_heroes = false;
var state;
var sliders = [null, null, null, null];
var b_names = ['b','gb','s','gs','ws'];
var builging_lvl_selects;
function createSlider(id, p_idx) {
	var _el = $(id);
	var _slider = new Slider(_el, _el.getElement('.knob'), {
		steps: 100,	
		range: [0],
		onChange: function(value){
			_el.getElement('.left').firstChild.innerHTML = (100-value) + '/';
			_el.getElement('.right').firstChild.innerHTML = value;
			state.p[p_idx] = value;
/*			col = new Color(
				c_stat[p_idx*2].color
			).mix(
				c_stat[p_idx*2+1].color,
				value
			);
			_el.getElement('.knob').style.background = col.hex;*/
			update_all_stats();
		},
		onComplete: function(step){
			StateSaver.save();
		}
	});
	return _slider;
}
function createArtSlider(id) {
	var _el = $(id);
	var _slider = new Slider(_el, _el.getElement('.knob'), {
		steps: 100,	
		range: [0],
		onChange: function(value){
			state.art = value;
			update_all_stats();
		},
		onComplete: function(step){
			StateSaver.save();
		}
	});
	return _slider;
}

window.addEvent('domready', function(){
	// Create the new slider instance
	sliders[0] = createSlider('inf_slider', 0, 'i');
	sliders[1] = createSlider('cav_slider', 1, 'c');
	sliders[2] = createSlider('siege_slider', 2, 's');
	sliders[3] = createArtSlider('artifact_slider');
	$('i0').		addEvent('click', function(){sliders[0].set(0)});
	$('i100').	addEvent('click', function(){sliders[0].set(100)});
	$('c0').		addEvent('click', function(){sliders[1].set(0)});
	$('c100').	addEvent('click', function(){sliders[1].set(100)});
	$('s0').		addEvent('click', function(){sliders[2].set(0)});
	$('s100').	addEvent('click', function(){sliders[2].set(100)});
	// init building lvls array
	builging_lvl_selects = $$('select.building_lvl');
	// init selects and event handlers
	builging_lvl_selects.each(function(elt){
		elt.addEvent('change', function() {
			update_build_speed()
		});
	});
	b_names.each(function(id){
		id = 'b_'+id;
		$$('.'+id).each(function(item){
			item.addEvent('click', function(){
				$(id).value = item.get('text').trim();
				$(id).fireEvent('change');
			});
		});
	});
	$('race').addEvent('change', function() {
		update_race();
		StateSaver.save();
	});
	var general_update = function() {
		update_all_stats();
		StateSaver.save();
	};
	$('times').addEvent('keyup', general_update);
	$('time').addEvent('change', general_update);
	$('art_speed_up').addEvent('change', general_update);
	$('plus').addEvent('click', general_update);
	$('hero_bonus').addEvent('keyup', function(){
		state.hb = read_with_feedback(this);
		update_all_stats();
		StateSaver.save();
	});
	$$("input.server").each(function(elt){
		elt.addEvent('click', function(){update_server_type(this.value)})
	});
	$('b_hd').addEvent('change', function() {
		state.h = parseInt(this.value);
		update_build_speed();
		StateSaver.save();
	});
	$$('.b_hd').addEvent('click', function(){
		val = this.innerHTML;
		var elt = $('b_hd');
		elt.value = isNaN(val)?"0":val;
		elt.fireEvent('change');
	});
	
	// Create and init state object
	state = {
		b:[0,0,0,0,0],
		p:[0,0,0],
		r:1,
		t:1,
		s:SERVER.T3_51,
		h:0,
		po:true,
		hb:0,
		art:0,
		ac:0
	};
	StateSaver.bind(state, {
		b:'a',
		p:'a',
		r:'i',
		t:'i',
		s:'i',
		h:'i',
		po:'b',
		hb:'i',
		art:'i',
		ac:'i'
	});
	StateSaver.load();
	
	// Set switchers to proper states
	for (var sl=0; sl<3; sl++) {
		sliders[sl].set(state.p[sl]);
	}
	sliders[3].set(state.art);
	builging_lvl_selects.each(function(elt){
		elt.value = state.b[b_names.indexOf(elt.id.replace('b_', ''))];
	});
	$$("input.server [value="+state.s+"]").checked = true;
	$('hero_bonus').value = state.hb;
	$('race').value = state.r;
	$('plus').checked = state.po;

	// init times
	var time_opts = $$('#time option');
	for(var i = 0; i < times.length; i++) {
		time_opts[i].value = times[i];
	}
	var i = 0;
	for (var j = 0; j < times.length; j++) {
		if (state.t % times[j] == 0)
			i = j;
	}
	while  ((i < times.length)
	&&		(state.t > 999*times[i])) { i++; }
	if (state.t > 999*times[i]) state.t = 999*times[i];
	$('times').value = Math.round(state.t / times[i]);
	$('time').value = times[i];
	
//	model hack, set upgrades to lvl20
	for (r=0; r<3; r++) {
		cs = stats[r];
		for (i=0; i<6; i++) {
			if (cs[i] && cs[i].off)
				cs[i].off = cs[i].off + (cs[i].off + 300*cs[i].upkeep/7) * UPG_20;
		}
	}
	update_race();
	update_server_type(state.s);
});

function lvl_spd(lvl) { return (lvl!='0')?Math.pow(0.9, 1-lvl):0 }

function horsedrinker_applies() {
	return (state.r == 1) && SERVER.is_3_5(state.s);
}

function artifact_applies() {
	return SERVER.is_3_5(state.s);
}

function _horse() {
	$('horsedrinker').style.display = 
		horsedrinker_applies() ? 'block' : 'none';
}

function _art() {
	$('art_holder').style.display = 
		artifact_applies() ? '' : 'none';
}

function update_server_type(serv_type) {
	
	var display = SERVER.has_heroes(serv_type)?"":"none";
	$('army').rows[0].cells[10].style.display = display;
	$('army').rows[0].cells[11].style.display = display;
	$('army').rows[1].cells[10].style.display = display;
	$('army').rows[1].cells[11].style.display = display;
	
	state.s = serv_type;
	_horse();
	_art();
	update_build_speed();
}

function update_build_speed() {
	builging_lvl_selects.each(function(elt){
		state.b[b_names.indexOf(elt.id.replace('b_', ''))] = parseInt(elt.value);
	});
	StateSaver.save();
	update_all_stats();
}

function update_img(images, n) {
	if (c_stat[n].idx != -1) {
		images[n].className = "unit u"+c_stat[n].idx;
		images[n].style.display = 'block';
		return true;
	} else {
		images[n].style.display = 'none';
		return false;
	}
}

function update_race() {
	state.r = $('race').value;
	_horse();
	c_stat = stats[state.r-1];
	var images = $$('.content img.unit');
	for(var unit_type = 0; unit_type < 3; unit_type++) {
		var i0 = update_img(images, unit_type*2+0);
		var i1 = update_img(images, unit_type*2+1);
		$$('div.slider')[unit_type].style.display =
			(i0 && i1) ? 'block' : 'none';
		if (!i0) sliders[unit_type].set(100);
		if (!i1) sliders[unit_type].set(0);
	}
	var xrow = $('army').rows[0].cells;
	for (u=0; u<10; u++) {
		xrow[u].firstChild.className = "unit u"+(state.r*10+u-9);
	}
	update_all_stats();
}

function update_all_stats() {
	// time
	state.t = $('time').value * $('times').value;
	state.po = $('plus').checked;
	var t = $('time');
	var tdim = t.options[t.selectedIndex].innerHTML;
	$(sliders[3].knob).getElement('.middle').innerHTML =
		($('times').value * state.art / 100).toFixed(2) + " " + tdim;
	state.ac = $('art_speed_up').value;
	// all stats
	var c_stat = stats[state.r-1];
	var x = SERVER.build_speeds[state.s];
	var ax = 1;
	if (artifact_applies()) {
		var ap = state.art / 100;
		ax = 4 / (4 - state.ac);
		ax = 1 * (1-ap) + ax * ap; 
	}
	var spd = {
		amount:[
			lvl_spd(state.b[0])+lvl_spd(state.b[1]),
			lvl_spd(state.b[2])+lvl_spd(state.b[3]),
			lvl_spd(state.b[4])
		],
		cost:[
			lvl_spd(state.b[0])+3*lvl_spd(state.b[1]),
			lvl_spd(state.b[2])+3*lvl_spd(state.b[3]),
			lvl_spd(state.b[4])
		]
	}
	var xh = 1;
	if (horsedrinker_applies()) {
/*		spd.amount[1] /= g41_build_time(state.h);
		spd.cost[1] /= g41_build_time(state.h);*/
		xh = g41_build_time(state.h);
	}
	var data = {
		cost:[0,0,0,0],
		cu:0,
		off:0
	}
	var time_ = [
		24*(c_stat[1].time*state.p[0] + c_stat[0].time*(100-state.p[0]))/x[0]/ax,
		24*(c_stat[3].time*state.p[1] + c_stat[2].time*(100-state.p[1]))/x[1]/ax*xh,
		24*(c_stat[5].time*state.p[2] + c_stat[4].time*(100-state.p[2]))/x[2]/ax
	];
	for(r=0; r<4; r++) {
		data.cost[r] =
			spd.cost[0]*(c_stat[1].cost[r]*state.p[0]+c_stat[0].cost[r]*(100-state.p[0])) / time_[0] +
			spd.cost[1]*(c_stat[3].cost[r]*state.p[1]+c_stat[2].cost[r]*(100-state.p[1])) / time_[1] +
			spd.cost[2]*(c_stat[5].cost[r]*state.p[2]+c_stat[4].cost[r]*(100-state.p[2])) / time_[2]
	}
	data.cu = 
		spd.amount[0]*(c_stat[1].upkeep*state.p[0]+c_stat[0].upkeep*(100-state.p[0])) / time_[0] +
		spd.amount[1]*(c_stat[3].upkeep*state.p[1]+c_stat[2].upkeep*(100-state.p[1])) / time_[1] +
		spd.amount[2]*(c_stat[5].upkeep*state.p[2]+c_stat[4].upkeep*(100-state.p[2])) / time_[2];
	data.cu2 = data.cu;
	if (horsedrinker_applies()) {
		if (state.h >= 15) data.cu2 -= spd.amount[1]*(100-state.p[1]) / time_[1];
		if (state.h >= 20) data.cu2 -= spd.amount[1]*(state.p[1]) / time_[1];
	}
	data.off_i = 
		spd.amount[0]*(c_stat[1].off*state.p[0]+c_stat[0].off*(100-state.p[0])) / time_[0] +
		spd.amount[2]*(c_stat[5].off*state.p[2]+c_stat[4].off*(100-state.p[2])) / time_[2];
	data.off_c =
		spd.amount[1]*(c_stat[3].off*state.p[1]+c_stat[2].off*(100-state.p[1])) / time_[1];
	var m = 1;
	if (SERVER.has_heroes(state.s)) m *= (1 + state.hb / 500); //hero
	m *= state.po ? 1.1 : 1; //plus
	data.off_i *= m;
	data.off_c *= m;
	data.off = data.off_i + data.off_c;
	out_results(data);
	var xrow = $('army').rows[1].cells;
	for (u=0; u<10; u++) {
		xrow[u].innerHTML = 0;
		xrow[u].className = "c";
	}
	var hash = "a:r" + state.r;
	var units_hash = [];
	for(var unit_type=0; unit_type<3; unit_type++) {
		var k = state.t*spd.amount[unit_type]/time_[unit_type];
		var c0 = (c_stat[2*unit_type+1].idx-1)%10;
		var c1 = (c_stat[2*unit_type+0].idx-1)%10;
		if (c0 >= 0) {
			var val = Math.round(state.p[unit_type]*k);
			xrow[c0].innerHTML = val;
			xrow[c0].className = val == "0" ? "c" : "";
			units_hash[c0] = val;
		}
		if (c1 >= 0) {
			var val = Math.round((100-state.p[unit_type])*k);
			xrow[c1].innerHTML = val;
			xrow[c1].className = val == "0" ? "c" : "";
			units_hash[c1] = val;
		}
	}
	for (var u = 0; u < 10; u++) {
		if (!units_hash[u]) {
			units_hash[u] = "";
		}
	}
	hash += "u" + units_hash.join(",").replace(/,+$/, "");
	hash += "U!20";
	if (SERVER.has_heroes(state.s)) {
		hash += "h";
		if (state.hb) {
			hash += "0,0,"+state.hb+",100";
		}
	}
	$('warsim').href = "warsim.php#" + hash + "#";
}
function out_results(data) {
	var xtable = $('result');
	for(r=0; r<4; r++) {
		xtable.rows[r+1].cells[1].innerHTML = Math.round(state.t * data.cost[r]).toLocaleString();
	}
	xtable.rows[5].cells[1].innerHTML = Math.round(state.t * eval(data.cost.join('+'))).toLocaleString();
	xtable.rows[7].cells[1].innerHTML = Math.round(state.t * data.off_i).toLocaleString();
	xtable.rows[8].cells[1].innerHTML = Math.round(state.t * data.off_c).toLocaleString();
	xtable.rows[9].cells[1].innerHTML = Math.round(state.t * data.off).toLocaleString();
	var h_cu = SERVER.has_heroes(state.s) ? 6 : 0;;
	xtable.rows[10].cells[1].innerHTML = Math.round(state.t * data.cu  + h_cu).toLocaleString();
	xtable.rows[10].cells[2].innerHTML = Math.round(state.t * data.cu2 + h_cu).toLocaleString();
//	xtable.rows[7].cells[1].innerHTML = Math.round(state.t*state.t*(data.cu+6)/2);
}