/**
 * Race object, mostly just a prepopulated array with proper keys.
 */
function races() {
	this.Human = false;
	this['Night Elf'] = false;
	this.Undead = false;
	this.Random = false;
	this.Orc = false;
	this.iter = function () {
		var keys = new Array('Human', 'Night Elf', 'Random', 'Orc', 'Undead');
		var current = 0;
		var next = function () {
			if (current > keys.length) {
				return false;
			}
			return keys[current++];
		}
		return next;
	}
}
/**
 * Some global arrays that can be manipulated by both JS
 * and PHP to set which races should be checked in the search
 * form.
 */
var basicRaces = new races();
var racesOne = new races();
var racesTwo = new races();

function updateRaceObj(objName, race, checked) {
	var obj;
	if (objName == 'basicRaces') {
		obj = basicRaces;
	} else if (objName == 'racesOne') {
		obj = racesOne;
	} else if (objName == 'racesTwo') {
		obj = racesTwo;
	}
	obj[race] = checked;
}

function addHeroFilter(hero_id) {
	var thing = $("#clone-hero-select").clone().addClass("cloned-hero-select").removeAttr("disabled");
	if (hero_id != null) {
		thing.val(hero_id);
	}
	$("#dynamic-filter-box").append(thing);
	$(".cloned-hero-select:last").fadeIn("slow");
	$(".cloned-hero-select:last").wrap("<div class='cloned-hero-select-wrap'></div>");
	$(".cloned-hero-select-wrap:last").append("<a href='javascript:doNothing();' onclick='javascript:removeHeroSelect(this);'>remove</a>");
}

function doNothing() {}

function removeHeroSelect(link) {
	$(link).parent('.cloned-hero-select-wrap').remove();
}

function updateRaceSelection() {
	var o = document.getElementById("gameType");
	var t = $(o.options[o.selectedIndex]).text();
	if (t == 'Any' || t == 'FFA') {
		// show basic race selector and check the saved values for which boxes to check
		$("#race-select-target").html(
			$("#basic-race-select-container").clone().addClass('current-race-select')
		);
		setCheckboxesFor($('.current-race-select').find('.race-item-basic'), basicRaces);
	} else {
		// show "vs" race selector
		$("#race-select-target").html(
			$("#vs-race-select-container").clone().addClass('current-race-select')
		);
		setCheckboxesFor($('.current-race-select').find('.race-item-one'), racesOne);
		setCheckboxesFor($('.current-race-select').find('.race-item-two'), racesTwo);
	}
	$('.current-race-select').fadeIn("slow");
}


function setCheckboxesFor(children, obj) {
	children.each(function () {
		// e.g: if (racesOne['Night Elf']) 
		if (obj[$(this).val()]) {
			$(this).attr('checked', 'checked');
		} else {
			$(this).removeAttr('checked');
		}
	});
}

function toggleSearchBox() { 
	var box = $("#search-box");
	if (box.css("display") == 'none') {
		box.slideDown("slow");
	} else {
		box.slideUp("slow");
	}
}
