function getAnother() {
	howmany = $("#teamnumber").val();
	if (howmany < 1 || howmany > 9) {
		alert("You must have between 1 and 9 team members");
		return;
	}
	$("#again").html("Loading...");
	$.getJSON("ajax.php?teamnumber="+howmany,null,function(data,textStatus) {
		howmany = $("#teamnumber").val();
		$("#team-name").html(data.teamname);
		data = data.members;
		if (howmany==1) {
			$("#team-block").fadeOut("fast");
		} else {
			$("#team-block").fadeIn("fast");
		}
		for (i=0;i<howmany;i++) {
			if ($("#field"+i+"-0").length == 0) {
				newhero = $("#hero"+(i-1)).clone();
				str = newhero.html();
				newhero.html(str.replace(new RegExp("field"+(i-1),"g"),"field"+i)).attr("id","hero"+i);
				$("#hero"+(i-1)).after(newhero);
			}
			for (j=0;j<data[i].length;j++) {
				$("#field"+i+"-"+j).html(data[i][j]);
			}
		}
		while ($("#hero"+i).length > 0) {
			$("#hero"+i).remove();
			i++;
		}
		$("#again").html("<a href=\"#\">Again?</a>");
		$("#again a").click(getAnother);
	});
}

function showExisting() {
	if ($("#all-current").length==0) {
		$("#add-form").after("<div id=\"all-current\"></div>");
	}
	$("#all-current").load("show-all-ajax.php?canedit");
}

function addNew() {
	$.post('add-new-ajax.php?canedit',{type:$("#type").val(), doing:$("#doing").val(), using:$("#using").val(), fighting:$("#fighting").val(), because:$("#because").val(), first:$("#first").val(), second:$("#second").val(), prefix:$("#prefix").val(), team:$("#team").val(), suffix:$("#suffix").val(), submit:$("#submit").val()},function(data,textStatus) {
		console.log(data.result);
		$("#show-post-result").show().html("Saved!").hide(4000);
		$("#submit").show("fast");
		$("#add-form fieldset input").val("");
	},"json");
}

$().ready(function() {
	// AJAX loading new team+members
	$("#again").html("<a href=\"#\">Again?</a>");
	$("#again a").click(getAnother);
	// AJAX showing the existing options to be in-page
	$("#show-all").html("see all current options below the inputs");
	$("#show-all").attr('href','#');
	$("#show-all").click(showExisting);
	// AJAX hijacking the submit of new values
	$("#submit").click(function(event) {
		if ($("#show-post-result").length==0) {
			$("#submit").after("<div id=\"show-post-result\"></div>");
		}
		$("#submit").hide("fast");
		event.preventDefault();
		addNew()
	});
	
});