$(function() {
	miner.dpInit();
	miner.handyForm();
	
	$("#inst h2 a").click(function() {
		if (this.innerHTML == "Show instructions") {
			this.innerHTML = "Hide instructions";
			$("#inst p").slideDown();
		}
		else {
			this.innerHTML = "Show instructions";
			$("#inst p").slideUp();
		}
		return false;
	});
	
	$("#main-form").submit(function() {
		var formData = miner.getFormData(this);
		
		authTable.make(formData.posts);
		formData.posts = authTable.namesToIds(formData.posts);
		
		miner.insertBbData(formData);
		return false;
		});
});

authTable = {
	table: [],
	authRegEx: /^(Author: )(.+)( Date)/gm,
	
	// @param	(str)posts	a bunch of posts
	// @return	(arr)		true; sets the authTable.table property
	make: function(content) {
	
		var auths = [];
		var author = "";
		while (name = this.authRegEx.exec(content)) {
			// IE gives us a string insteac of an array...
			author = (typeof(name) == "string") ? name.split(",")[2] : name[2];
			auths.push(author);
		}
		this.table = auths.unique();
		return true;
	},
	idToName:function(id) {
		return this.table[id];
	},
	namesToIds: function(posts) {
		 posts = posts.replace(this.authRegEx, function(m, p1, p2, p3) {
			return p1 + authTable.table.indexOf(p2) + p3;
		});	
		return posts;
	}
}



miner = {}
miner.nameKey = 0;
miner.authors = "";
miner.ajaxUrl = "./main.php";

miner.dpInit = function() {
	$('.date-pick').datePicker({
		startDate: '01/01/1970',
		endDate: (new Date()).asString()
	});
	} 

// @param		(DOM object)thisForm		the form with the stuff we want
// @return		(arr)						an array of criteria and posts to process
miner.getFormData = function(thisForm) {
		formData = {};
		// original post criteria
		formData.opMinWds = $('#op-min-wds').val();
		var dlDay = $('#op-deadline').val();
		var dlTime = $('#op-deadline-time').val()
		formData.opDeadline = dlDay + " " + dlTime;
		
		// reply posts criteria
		formData.replyMinWds = $('#reply-min-wds').val();
		formData.replyNum = $('#reply-num').val();
		var dlDay2 = $('#reply-deadline').val();
		var dlTime2 = $('#reply-deadline-time').val()
		formData.replyDeadline = dlDay2 + " " + dlTime2;		
		
		//the text of all the posts
		formData.posts = $('#bb-raw-text').val();
		return formData;
}
	
miner.insertBbData = function(formData) {
	window.scrollTo(0, 0);
	//get rid of the form
	$("#main-form").replaceWith("<div class='loading'><img src='./images/spinner.gif'><p>processing...</p></div>");
	//make the ajax call and get the author data
	$.post(miner.ajaxUrl, formData, function(bbInfo) {
			// get the jquery-wrapped DOM of the returned data
			data$ = $("<div></div>");
			data$.append(bbInfo);
			
			// replace the author IDs with author names
			data$.find("span.auth").each(function() {
				var thisName = authTable.idToName($(this).text());
				$(this).text(thisName);
			});			
			
			// sort by author
			var authDivs = data$.find("div.author");
			authDivs.sort(function(a,b) {
				var aName = $(a).find("span.auth").lastWord();
				var bName = $(b).find("span.auth").lastWord();
				return (aName > bName) ? 1 : -1;
			});
			

			
			// append the data from the server
			if (data$.find("#copies").html()) {
				$("<div id='copies'><h2><span class='text'>Possible copies!</span><a class='show-hide'>show</a></h2></div>")
					.append(data$.find("#copies").html())
					.appendTo("#content");
			}
			$("<div id='authors'><h2><span class='text'>Post authors (click to show posts)</span><a class='show-hide'>show all posts</a></h2></div>")
				.append(authDivs)
				.appendTo("#content");
			$("div.loading").remove();
			
			// add the global statistics:
			var wordStats$ = $("<p class='wordcount'>Average word count: </p>")
				.append("<span class='op'>original posts: <span class='val'>" + $("div.op span.wordcount").avg() + "</span></span>, ")
				.append("<span class='reply'>replies: <span class='val'>" + $("div.reply span.wordcount").avg() + "</span></span>");
				
			var timeStats$ = $("<p class='ds'>Average time before deadline: </p>")
				.append("<span class='val'>" + miner.humanTime( $("div.header span.ds-stamp").avg() ) + " </span></p>");
				
				
			
			$("<div id='stats'></div>")
				.append("<p class='gl'>Average grade level: <span class='val'>" + $("div.stats span.gl").avg() + "</span></p>")
				.append(timeStats$)
				.append(wordStats$)		
				.prependTo("#content");

			miner.tidyGl();
			miner.showHideCopies();
			miner.showHideAllPosts();
			miner.showOneAuth();		
		});
		
		
	
}
// this is a hack to make the grade-level string not show up if there's no value
miner.tidyGl= function() {
	$("span.gl:empty").parent().hide();
}

		



miner.showHideCopies = function() {
	$("#copies h2 a.show-hide").toggle(
		function(e) {
			$("#copies div.copy-and-orig").slideDown();
			e.target.innerHTML = "hide";
		},
		function(e) {
			$("#copies div.copy-and-orig").slideUp();
			e.target.innerHTML = "show";
		}
	);
};

miner.showHideAllPosts = function() {
	$("#authors h2 a.show-hide").toggle(
		function(e) {
			$("#authors div.author").addClass("show-posts").find("div.post").show();
			e.target.innerHTML = "hide all posts";
		},
		function(e) {
			$("#authors div.author").removeClass("show-posts").find("div.post").hide();
			e.target.innerHTML = "show all posts";
		}
	);
};		
miner.showOneAuth = function() {
	// hover inst should go here
	$("#authors h3").toggle(
		function() {
			$(this).siblings().slideDown(function() {
				$(this).parent().addClass("show-posts");
			})
			.end()
			.find("span.auth")
			.css( {fontWeight:"bold"} );
		},
		function() {
			$(this).siblings().slideUp(function() {
				$(this).parent().removeClass("show-posts");
			})
			.end()
			.find("span.auth")
			.css( {fontWeight:"normal"} );
		}
	);
}



	
	




		

miner.handyForm = function() {
	$("#main-form input").not(".date-pick").focus(function() {
		this.select();
		}
	);
}



miner.humanTime = function(secs) {
	var hours = Math.floor(secs / 3600);
	var days = Math.floor(hours / 24);
	
	if (days) return (days > 1) ? days + " days" : days + " day";
	if (hours) return (hours > 1) ? hours + " hours" : hours + " hour";
	return "less than one hour";
}


