// JavaScript Document

// methods for the wordnerd pages

var wordnerd="", wordnerdID=0;
var voteID=0;
var comID=0;
var bSwearFilter=true;
var pageString="";

$(document).ready(function(){
						   
	// hide the bodies / unwanted sections
	$("div[id^='commentsDiv']").each(function(){ $(this).hide() });
	$("div[id^='editBody']").each(function(){ $(this).hide() });
	$("div[id^='phraseBody']").each(function(){ $(this).hide() });
	$("div#newBodyWarning").each(function(){ $(this).hide() });
	// hide the add new divs
	$("div#newPhraseWarning").hide();
	$("div#newPhrase").hide();
	$("div[id^='newBody']").hide(); // hide all the new body submission divs
	
	// hide submissions divs if not lgoge din
	if (wordnerd=="" && wordnerdID==0)
	{
		$("div#newPhrase").html("<b>You must be logged in to create new submmissions<br><br>"+
					"Would you like to <a href='login.php'>Log In</a>?</b><br><br><br>");
		$("div[id^='newBody']").each(function(){
			$(this).html("<b>You must be logged in to create new submmissions<br><br>"+
					"Would you like to <a href='login.php'>Log In</a>?</b><br><br><br>");							  
		});
	}
	
	// prepare the buttons
	var h;
	//$("div.phraseButton").each(function(){
	$("div[id^='phraseTitle']").each(function(){
		$(this).click(function(){
			var obj = $("div.phraseButton", $(this));
			PhraseButtonClick(obj.attr("name"), obj);
			//PhraseButtonClick($(this).attr("name"), $(this));
		});
		// fix stupid IE bug by setting css bgpos
		$(this).css("background-position", "0% 100%");
		
		// store the vertical size of the body div for later use
		h = $("div#"+$(this).attr("name")).height();
		$(this).data("size", h);
	});
	
//	setTimeout("SetData();", 100);
	//SetData();
});


function SetData()
{
	var maxPos=0, h=0;
	$("div.phraseButton").each(function(){
		h = $(this).offset().top + 150;
		if (h>maxPos)
			maxPos=h;
	});
	
	// offset footer appropriately
	$("div#mainContainer").css("height", (maxPos)+"px"). data("pos", maxPos);
}


function PhraseButtonClick(n, obj)
{
	if (n.length<5)
		alert("bad name specified -- "+n);
	else
	{
		var bdy = $("div[id^='phraseBody']", obj.parent().parent());
		
		if (obj.css("background-position")=="0% 100%")
		{
			//alert("set 0 0");
			obj.css("background-position", "0% 0%");			

			//$("div#"+n).slideDown(500);
			bdy.slideDown(500);
		}
		else
		{
			//alert("set 0 100");
			obj.css("background-position", "0% 100%");			
			
			//$("div#"+n).slideUp(500);
			bdy.slideUp(500);
		}
	}
	
	return false; // stop click propogation
}

function Vote(section, id, subber)
{
	// call the ajax to vote for a wossname
	voteID = id;
	// possible returns will be success, Sorry - xxx, already voted
	$.post("bin/"+section+"DB.php?action=vote", { voteID: id, submitID: subber }, function(data){
		if (data=="success")
		{
			$("span#thumbsUp"+voteID).html("Thank you!");
		}
		else if (data.indexOf("Sorry")!=-1)
		{
			alert(data); // show error message direct from the php
		}
		else if (data=="already voted")
		{
			$("span#thumbsUp"+voteID).html("Already Voted");
		}
		else
		{
			alert(data);
		}
	});
}

function EditBody(section, id)
{
	// tbd: send ajax along with some hashed identifier stuff to ensure no funny business
	$.post("bin/"+section+"DB.php?action=edit", { username: wordnerd, userID: wordnerdID, bodyID: id,
		   					newBody: $("textarea#bodyText"+id).val() }, function(data){
		if (data.substr(0,10).indexOf("failure")==-1)
		{
			var id2 = parseInt(data.substr(0, data.indexOf("^")));
			data2 = data.substr(data.indexOf("^")+1);

			// successful edit, change content
			var div = $("div#editBody"+id2);
			div.slideUp(500);
			$("div#bodyText"+id2).html(data2).slideDown(500);
			$("a#editBody"+id2).html("Edit Origin");
		}
		else
		{
			// tbd: failed for some reason, alert user
			alert("Sorry,dute to  server problems we are unable to complete your edit request right now.  Please try again soon");
		}
	});
}

function ShowEdit(id, section)
{
	var div = $("div#editBody"+id);
	if (div.is(":visible"))
	{
		div.slideUp(250);
		var y = $("div#mainContainer").data("pos") - 210;
		$("div#bodyText"+id).slideDown(250);
		$("div#mainContainer").data("pos", y).animate( { height: y+"px" }, 500);
		$("a#editBody"+id).html("Edit Origin");
		
		$.post("bin/"+section+"DB.php?action=getBody&id="+id, { smeg: "head" }, function(data){
			$("textarea#bodyText"+id).val(data);
		});
	}
	else
	{
		div.slideDown(500);
		var y = $("div#mainContainer").data("pos") + 210;
		$("div#mainContainer").data("pos", y).animate( { height: y+"px" }, 500);
		$("div#bodyText"+id).slideUp(500);
		$("a#editBody"+id).html("Cancel Edit");
		$("textarea#bodyText"+id).val("Loading Data...");
		
		$.post("bin/"+section+"DB.php?action=getBody&id="+id, { smeg: "head" }, function(data){
			$("textarea#bodyText"+id).val(data);
		});
	}
}

function ToggleSwearing()
{
	var str="";
	if (bSwearFilter)
		str = "off";
	else
		str = "on";
	
	//alert("sending out: bin/"+pageString+"DB.php?action=swear&filter="+str);
	$.post("bin/"+pageString+"DB.php?action=swear&filter="+str, { user:"wibble" }, function(data) {
		if (data=="success")
		{
			$("div#sweary>a").html("Refreshing - please wait");
			window.location.reload(true);
		}
		else
		{
			alert(data);
		}
	});
}

function ShowAddNew()
{
	if ($("div#newPhrase").is(":visible"))
		HideAddNew();
	else
	{
		if ($("div#userDiv").html().indexOf("login.php")!=-1)
		{
			$("div#newPhrase").html("<b>You must be logged in to create new submmissions<br><br>"+
					"Would you like to <a href='login.php'>Log In</a>?</b><br><br><br>");
			$("div[id^='newBody']").each(function(){
				$(this).html("<b>You must be logged in to create new submmissions<br><br>"+
						"Would you like to <a href='login.php'>Log In</a>?</b><br><br><br>");							  
			});
		}
		$("div#newPhrase").slideDown(900);
	}
}

function HideAddNew()
{
	$("div#newPhrase").slideUp(500);
}

function SubmitNewPhrase()
{
	// send the new submission via ajax
	
	// first validate input
	if ($("div#newPhraseWarning").is(":visible"))
		$("div#newPhraseWarning").slideUp(50);
	var bdy = $("textarea#newBody").val();
	var title = $("input#newTitle").val();
	if (title.length<3)
	{
		var str = "";
		if (pageString=="origins")
			str = "Figure of Speech";
		else if (pageString=="analogies")
			str = "Analogy/Metaphor/Similie";
		else if (pageString=="celebs")
			str = "Celebrity";
		$("div#newPhraseWarning").html("The "+str+" is too short (min. 3 characters).  Please correct this").slideDown(500);
		return false;
	}
	var filter = /(\w{1,}\s{1,}\w{1,}){3,}/;
	if (!filter.test(bdy))
	{
		var str = "";
		if (pageString=="origins")
			str = "Origin of the phrase";
		else if (pageString=="analogies")
			str = "Origin of the Analogy/Metaphor/Similie";
		else if (pageString=="celebs")
			str = "Obituary";
		$("div#newPhraseWarning").html("The "+str+" you have entered is too short (min. 4 words).  Please correct this").slideDown(500);
		return false;
	}
	if (IsSpam(bdy) || IsSpam(title))
	{
		$("div#newPhraseWarning").html("Please remove all links, email addresses, and other web-related stuff from your submission.  This is not the place for your spam").slideDown(500);
		return false;
	}
		
	// then send along
	
	$.post("bin/"+pageString+"DB.php?action=submit", { newBody: bdy, newTitle: title }, function(data){
		if (data=="success")
		{
			HideAddNew();
			window.location.href=pageString+".php?sort=latest";
		}
		else
		{
			$("div#newPhraseWarning").html(data).slideDown(500);
			return false;
		}
	});
}

function ShowNewBodyDiv(id)
{	
	if ($("div#newBody"+id).is(":visible"))
	{
		var str = "";
		if (pageString=="origins")
			str = "Origin";
		else if (pageString=="analogies")
			str = "Entry";
		else if (pageString=="celebs")
			str = "Obituary";
		$("a#newBodyLink"+id).html("Add New "+str);
		$("div#newBody"+id).slideUp(500);
	}
	else
	{
		if ($("div#userDiv").html().indexOf("login.php")!=-1)
		{
			$("div#newPhrase").html("<b>You must be logged in to create new submmissions<br><br>"+
					"Would you like to <a href='login.php'>Log In</a>?</b><br><br><br>");
			$("div[id^='newBody']").each(function(){
				$(this).html("<b>You must be logged in to create new submmissions<br><br>"+
						"Would you like to <a href='login.php'>Log In</a>?</b><br><br><br>");							  
			});
		}
		
		var str = "";
		if (pageString=="origins")
			str = "Origin";
		else if (pageString=="analogies")
			str = "Entry";
		else if (pageString=="celebs")
			str = "Obituary";
		$("a#newBodyLink"+id).html("Cancel New "+str);
		$("div#newBody"+id).slideDown(500);
		setTimeout(function(){
			window.location.hash="newBodyBookmark"+id;
		}, 550);
	}
	return false;
}

function SubmitNewBody(id)
{
	var bdy = $("textarea#newBody"+id).val();
	if ($("div#newBodyWarning").is(":visible"))
		$("div#newBodyWarning").html("").slideUp(250);
	// check for valid input first
	var filter = /(\w{1,}\s{1,}\w{1,}){3,}/;
	if (!filter.test(bdy))
	{
		var str = "";
		if (pageString=="origins")
			str = "Origin of the phrase";
		else if (pageString=="analogies")
			str = "Origin of the Analogy/Metaphor/Similie";
		else if (pageString=="celebs")
			str = "Obituary";
		$("div#newBodyWarning").html("The "+str+" you have entered is too short (min. 3 words).  Please correct this").slideDown(500);
		return false;
	}
	if (IsSpam(bdy))
	{
		$("div#newBodyWarning").html("Please remove all links, email addresses, and other web-related stuff from your submission.  This is not the place for your spam").slideDown(500);
		return false;
	}
	
	// all clear, so send the submission
	voteID = id; // remember the id for when submission returns
	$.post("bin/"+pageString+"DB.php?action=newBody", { username: wordnerd, userID: wordnerdID,
			   									phraseID: id, newBody:bdy }, function(data){
		if (data=="success")
		{
			$("div#newBody"+voteID).slideUp(500);
			window.location.href=pageString+".php?sort=latest";
		}
		else
		{
			$("div#newBodyWarning").html(data).slideDown(500);
		}
	});
}

function SendKillRequest(id, section, pID)
{
	if (confirm("Are you sure you want to delete this body?"))
	{
		$.post("bin/"+section+"DB.php?action=kill", { username: wordnerd, userID: wordnerdID,
			   									bodyID: id, phraseID: pID }, function(data){
			// body removed hopefully
			if (data=="success")
			{
				alert("Body removed");
			}
			else if (data=="superkill")
			{
				alert("Body removed and Phrase also removed due to no more bodies");
			}
			else
			{
				alert(data);
			}
		});
	}
	return false;
}

function ShowCommentsDiv(bodyID)
{
	voteID=bodyID; // store for later use
	var obj = $("div#commentsDiv"+bodyID);
	if (obj.is(":visible"))
	{
		obj.slideUp(500);
		setTimeout(function(){
			$("div#commentsDiv"+voteID).html("Loading Comments...");
		}, 500);
		var str = $("div#commentsHeader"+voteID+">a").html();
		str = str.replace("Hide Com", "Show Com");
		$("div#commentsHeader"+voteID+">a").html(str);
	}
	else
	{
		if (obj.html().indexOf("Loading Comments")!=-1)
		{
			obj.slideDown(200);
			// need to load the comments
			setTimeout(function(){
				$.post("bin/comments.php?comAction=fetch", { id:voteID, section:pageString }, function(data){
					$("div#commentsDiv"+voteID).html(data);
					// hide the reply divs
					$("div#commentsDiv"+voteID+">div[id^='replyDiv']").each(function(){ $(this).hide(); });
					$("div#commentsDiv"+voteID+">div[id^='addComment']").each(function(){ $(this).hide(); });
					$("div#[id^='addReply']").each(function(){ $(this).hide() });
					// re-color the comments divs
					$("div#commentSpan").each(function(i){
						if (i%2==1)
							$(this).css("background-color", "#FFF");
					});
				});
			}, 550);
		}
		else
			obj.slideDown(500);
		var str = $("div#commentsHeader"+voteID+">a").html();
		str = str.replace("Show Com", "Hide Com");
		$("div#commentsHeader"+voteID+">a").html(str);
	}
}

function ShowAddBaseComment(id)
{
	var obj = $("div#addComment"+id);
	if (obj.is(":visible"))
	{
		obj.slideUp(500);
	}
	else
	{
		obj.slideDown(500);
		comID = id;
		setTimeout(function(){
			window.location.hash = "addCommentBookmark"+comID;
		}, 500);
	}
}

function ShowReply(id)
{
	var obj = $("div#addReply"+id);
	if (obj.is(":visible"))
	{
		obj.slideUp(500);
	}
	else
	{
		obj.slideDown(500);
	}
}

function AddComment(section, bodyID, replyID)
{	
	// test for valid comment
	var comment="";
	if (replyID!=0)
		comment = $("textarea#newReply"+replyID).val();
	else
		comment = $("textarea#newComment"+bodyID).val();
	
	if ($("div#commentWarning"+bodyID).is(":visible"))
		$("div#commentWarning"+bodyID).slideUp(250);
	
	if (comment.length<3)
	{
		$("div#commentWarning"+bodyID).html("Call that a comment?  How about some substance?").slideDown(500);
		return false;
	}
	if (IsSpam(comment))
	{
		$("div#commentWarning"+bodyID).html("Please remove all links, email addresses, and other web-related stuff from your comment.  This is not the place for your spam").slideDown(500);
		return false;
	}
	
	comID=bodyID; // store for later use
	$.post("bin/comments.php?comAction=submit", { comBody: comment, username: wordnerd, userID: wordnerdID,
			   								body: bodyID, reply: replyID, section: pageString}, function(data){
		if (data=="success")
		{
			setTimeout(function(){
				ShowCommentsDiv(comID);
			}, 550);
			$("div#[id^='addReply']").each(function(){ $(this).hide() });
			ShowCommentsDiv(comID);
		}
		else
		{
			$("div#commentWarning"+comID).html(data).slideDown(500);
		}
	});
}

function KillComment(id, bodyID)
{
	if (confirm("Are you sure you want to remove this comment, and all comments replying to it?"))
	{
		comID=bodyID; 
		$.post("bin/comments.php?comAction=kill", { killID: id,  username: wordnerd,
			   									section: pageString, userID: wordnerdID}, function(data){
			if (data=="success")
			{
				alert("Comment removed");
				$("div#[id^='addReply']").each(function(){ $(this).hide() });
				setTimeout(function(){
					ShowCommentsDiv(comID);
				}, 550);
				ShowCommentsDiv(comID);
			}
			else
			{
				alert(data);
			}
		});
	}
}
