const GSAPI = "/skins/bird/idea/gsProxy.php?gs_api=";
const GSAUTH = "http://wiki.songbirdnest.com/skins/bird/idea/gsLogin.php?";
const GSWEB = "http://getsatisfaction.com";

function drawTable(id, apiCall, preprocess) {
	// clear existing results
	$("#table-" + id + " tbody").empty();

	function processData(data) {
		if (preprocess)
			data.data = preprocess(data.data);
		$.each(data.data, function(i, item) {
			var link = "<a href='" + item.at_sfn + "'>" + item.subject + "</a>";
			var activityDate = item.last_active_at.substr(0,
				item.last_active_at.indexOf(" "));
			var voteUp = $("<img src='/skins/bird/idea/add.png' " +
				"id='img-voteup-" + item.id + "' />");
			voteUp.click(function() {
				var voteUrl = GSAUTH + "gs_url=" +
					encodeURIComponent("http://api.getsatisfaction.com/topics/"
						+ item.slug + "/me_toos");
				$.get(voteUrl, {}, function(data, textStatus) {
					switch(data) {
						case "201":
							// Submitted successfully
							$("#tabpanel-" + id).fadeOut("normal", function() {
								drawTable(id, apiCall, preprocess);
							});
							break;
						case "400":
							alert("You already +1'd this idea.");
							break;
						case "401":
							alert("Need to login first.");
							break;
						default:
							if (data.indexOf("URL:") == 0) {
								var url = data.substring(4);
								window.location = url;
							} else {
								//document.write(data);
								alert("Error, sorry:" + data);
							}
							break;
					}
				});
			});

			var tr = $("<tr>");
			var voteTd = $("<td class='vote'>");
			voteTd.append(voteUp);
			voteTd.append(item.me_too_count);
			voteTd.appendTo(tr);
			tr.append("<td>" + link + "</td>" +
				"<td class='bugnum bugnum-" + item.id + "'></td>" +
				"<td>" + activityDate + "</td>" +
				"<td class='author author-" + item.author.id + "'></td>" +
				"<td class='develop' id='dev-" + item.id + "'>" +
					"<a title='Develop this Idea' href='/index.php?title=Idea_Kitchen/" + item.slug + "&amp;template=Idea_Dev_Template'><img src='/skins/bird/idea/brick_edit.png' alt='Develop this idea'/></a>" +
				"</td>" +
				"</tr>");
			tr.appendTo($("#table-" + id));
			$.getJSON(GSAPI + "people/" + item.author.id + ".json",
				function(data) {
					var authorUrl = (GSWEB + data.topics).replace("/topics", "")
					var authorInfo = "<a href='" + authorUrl + "'>" +
						"<img src='" + GSWEB + data.photo + "'/>" +
						data.name + "</a>";
					$(".author-" + item.author.id).html(authorInfo);
				});
			$.get(GSAPI + "topics/" + item.slug,
				function(xmlData, textStatus) {
					var lastBugMentioned = null;
					$('content', xmlData).each(function(i) {
						var contents = $(this).text();
						var bugs = contents.match(/show_bug.cgi\?id=([\d]+)/);
						if (bugs) {
							lastBugMentioned = bugs[bugs.length-1];
						}
					});
					if (lastBugMentioned) {
						var bugHtml = "<a href='http://bugzilla.songbirdnest.com/show_bug.cgi?id=" + lastBugMentioned + "'>" + lastBugMentioned + "</a>";
						$(".bugnum-" + item.id).html(bugHtml);
					}
				}, "xml");
		});
		$("#tabpanel-" + id).fadeIn("normal");
	}

	// if our API call is actually an array of API calls, then fire a request
	// off for each API call, and combine the results before processing the
	// data
	if (typeof(apiCall) == "object") {
		var total = apiCall.length;
		var totalData = { data: new Array };
		$.each(apiCall, function(i, api) {
			$.getJSON(GSAPI + api, function(data) {
				total--;
				totalData.data = totalData.data.concat(data.data);
				if (total == 0) {
					// all our outstanding requests have completed
					processData(totalData);
				}
			});
		});
	} else {
		$.getJSON(GSAPI + apiCall, processData);
	}
}

function ideaSearch() {
	var text = $("form#form-search :input")[0].value;
	$("#div-ideasearch").fadeOut("normal", function() {
		$("#div-ideasubmit").fadeIn("normal");
	});
	var url = "topics.json%3fstyle=idea%26sort=most_me_toos%26q=" +escape(text);
	drawTable("submit", url, function(data) {
		data.sort(function(a,b) {
			return (a.me_too_count < b.me_too_count);
		});
		return (data);
	});
	$("form#form-submit :input")[0].value = text;
}

function ideaSubmit() {
	$("#div-search").fadeOut("normal");
	var submitUrl = GSAUTH + "gs_url=" +
		encodeURIComponent("http://api.getsatisfaction.com/topics");
	var subject = $("form#form-submit :input")[0].value;
	var description = $("form#form-submit :input")[1].value;
	var keywords = $("form#form-submit :input")[2].value;
	$.post(submitUrl, {
			"topic[company_domain]": "songbird",
			"topic[style]": "idea",
			"topic[subject]": subject,
			"topic[additional_detail]": description, 
			"topic[keywords]": keywords
		}, function(data, textStatus) {
			switch(data) {
				case "201":
					// Submitted successfully
					alert("Idea submitted successfully!");
					break;
				default:
					if (data.indexOf("URL:") == 0) {
						var url = data.substring(4);
						// append the query data so that when we go to post
						// and the user isn't signed in - we'll be
						// redirected back to this page post-token-grant, and
						// can re-POST the data
						var q = "&tsubject=" + encodeURIComponent(subject) +
							"&tdescription=" + encodeURIComponent(description) +
							"&tkeywords=" + encodeURIComponent(keywords);
						url += encodeURIComponent(q);
						window.location = url;
					} else {
						alert("Error, sorry.");
					}
					break;
			}
		}
	);
}

$("#tab-popular").click(function() {
	$("#tabnav li.selected").removeClass('selected');
	$(".tabpanel").fadeOut("normal");
	$("#tabnav li#tab-popular").addClass('selected');
	drawTable("popular", [
		"topics.json%3fstyle=idea%26sort=most_me_toos%26status=pending",
		"topics.json%3fstyle=idea%26sort=most_me_toos%26status=nil",
		"topics.json%3fstyle=idea%26sort=most_me_toos%26status=active"
		], function(data) {
			data.sort(function(a,b) {
				return (a.me_too_count < b.me_too_count);
			});
			data.splice(30);
			return data;
		});
});

$("#tab-recent").click(function() {
	$("#tabnav li.selected").removeClass('selected');
	$(".tabpanel").fadeOut("normal");
	$("#tabnav li#tab-recent").addClass('selected');
	drawTable("recent", [
		"topics.json%3fstyle=idea%26sort=recently_active%26status=pending",
		"topics.json%3fstyle=idea%26sort=recently_active%26status=nil",
		"topics.json%3fstyle=idea%26sort=recently_active%26status=active"
		], function(data) {
			data.sort(function(a,b) {
				return (a.last_active_at < b.last_active_at);
			});
			data.splice(30);
			return data;
		});
});

$("#tab-submit").click(function() {
	$("#tabnav li.selected").removeClass('selected');
	$(".tabpanel").fadeOut("normal");
	$("#tabnav li#tab-submit").addClass('selected');
	$("#tabpanel-submit > div").hide();
	$("#tabpanel-submit").fadeIn("normal");
	$("#tabpanel-submit #div-ideasearch").show();
});

// select the popular ideas table by default
//drawTable("popular", "topics.json%3fstyle=idea%26sort=most_me_toos");
drawTable("popular", [
		"topics.json%3fstyle=idea%26sort=most_me_toos%26status=pending",
		"topics.json%3fstyle=idea%26sort=most_me_toos%26status=nil",
		"topics.json%3fstyle=idea%26sort=most_me_toos%26status=active"
		], function(data) {
			data.sort(function(a,b) {
				return (a.me_too_count < b.me_too_count);
			});
			data.splice(30);
			return data;
		});

