// Comic = Fur style, JS

var files = [];
var titles = [];
var widths = [];
var heights = [];
var scores = [];
var rude = [];
var numFiles=0;
var lastVoteID=0;
var timer=null;
var comCount=0;
var comCompare=0;
var commentScrutiny=0;
var curID=numFiles;
var bNewComment=false;
var bFailedToConnect=false;

// digg stuff
digg_suffix="&bodytext="+encodeURIComponent("Furballs is another web comic.  Created with a little more flair, you'll either love it or you won't.  There's only one way to find out...")+"&media=image&topic=comics_animation&thumbnails=0";

window.onbeforeunload = function(){
	// store a very temporary cookie so we know we're refreshing
	var d = new Date();
	d.setSeconds(d.getSeconds()+15);
	c = new cookieObject("lastComic", 1, "/", "ID");
	c.put("ID", curID);
	c.write();
}

$(document).ready(function(){

	if (bFailedToConnect)
		return;

	setup();
	
	curID = numFiles;
	
	// get/set cookies
	// we're refreshing, so check to see if we need to view a specific comic
	c = new cookieObject("lastComic", 1, "/", "ID");
	if (c.found)
	{
		curID = c.get("ID");
		c.remove();
	}
	
	//setup permalink link		
	vars = getURLVars();
	if (vars['comic'] != undefined && vars['comic'].length>3)
	{
		var fname="";
		var uname = vars['comic'].substr(0, vars['comic'].lastIndexOf("."));
		fname = fname.toLowerCase();
		uname = uname.toLowerCase();
		for (var i=0; i<=numFiles; i++)
		{
			if (files[i].lastIndexOf(".")!=-1)
				fname = files[i].substr(0, files[i].lastIndexOf("."));
			else
				fname = files[i];
			if (fname==uname)
			{
				curID = i;
				break;
			}
		}
	}
	
	// hide logo hover div
	$("div#logoHover").hide();
	
	// set the comic and buttons appropriately
	newComic();
	if (curID == numFiles)
	{
		// tbd: remove these with bg offset vars that hide the text
		$("div#next").css("background-position", "0px -74px").data("off", "disabled");
		$("div#last").css("background-position", "0px -74px").data("off", "disabled");
	}
	else if (curID==0)
	{
		// tbd: remove these with bg offset vars that hide the text
		$("div#prev").css("background-position", "0px -74px").data("off", "disabled");
		$("div#first").css("background-position", "0px -74px").data("off", "disabled");
	}
	
	// setup button hovers
	$("div#about").mouseover(function(){
		$(this).css("background-position", "0px -48px");
	}).mouseout(function(){
		$(this).css("background-position", "0px 0px");
	});
	$("div#archives").mouseover(function(){
		$(this).css("background-position", "0px -48px");
	}).mouseout(function(){
		$(this).css("background-position", "0px 0px");
	});
	
	$("div#next").mouseover(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px -37px");
	}).mouseout(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px 0px");
	});
	$("div#last").mouseover(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px -37px");
	}).mouseout(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px 0px");
	});
	$("div#prev").mouseover(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px -37px");
	}).mouseout(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px 0px");
	});
	$("div#first").mouseover(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px -37px");
	}).mouseout(function(){
		if ($(this).data("off")!="disabled")
			$(this).css("background-position", "0px 0px");
	});
	
	// logo hover special
	$("div#logo").mouseover(function(){
		$("div#logoHover").show();
	}).mouseout(function(){
		$("div#logoHover").hide();
	});
	$("div#logoHover").mouseover(function(){
		$("div#logoHover").show();
	}).mouseout(function(){
		$("div#logoHover").hide();
	});
});

function newComic()
{
	if (bFailedToConnect)
	{
		bNewComment=false;
		return;
	}
	$("span#numComments").text("");
	$("img#comic").css("background-image", "url(images/layout/loadingComic.gif)").attr("width", "300").attr("height", "300");
	var img = new Image;
	img.src="images/comics/"+files[curID]; // load in the new comic
	$(img).load(function(){
		$(this).unbind("load");
		newComic2();	
			// offset lower section to suit new height of comics
		$("div#comicDiv").css("height", heights[curID]+"px");
		$("div#lowerSection").css("top", (heights[curID]-287)+"px");
		$("div#midleftpng").css("height", heights[curID]+"px");
		$("div#midrightpng").css("height", (heights[curID]-0)+"px");
		$("div#midLeftjpg").css("height", (heights[curID]-0)+"px");
		$("div#midRightjpg").css("height", (heights[curID]-0)+"px");
		// tbd: offset comments div here too
	});
}

function newComic2()
{	
	if (rude[curID])
	{
		// marked NSFW
		$("img#comic").css("background-image", "url(layout/NSFW.gif)").attr("width", widths[curID]).attr("height", heights[curID])
			.addClass("ptr").click(function(){
				$("img#comic").css("background-image", "url(images/comics/"+files[curID]+")").unbind("click").removeClass("ptr");
			});
	}
	else
		$("img#comic").css("background-image", "url(images/comics/"+files[curID]+")").attr("width", widths[curID]).attr("height", heights[curID]);	
	getTitle();
	
	//$("div#comments").css("top", (130 + heights[curID])+"px");
	$("div#rateFull").css("width","100px");	
	$("div#rateEmpty").css("width","100px");
	$("span#rating").text("2.5");
	
	c = new cookieObject("comicRating", 31, "/", "file");
	if (c.found)
	{
		if (c.get("file")=="undefined" || c.get("file").indexOf(files[curID])==-1)
		{
			$("div#ratings").show();
			$("div#thanks").hide();
		}
		else
		{
			$("div#ratings").hide();
			$("div#thanks").show();
			$("img#thanksImg").attr("src","bin/makeText.php?bgcol=FFEEDD&fgcol=000000&text="+scores[curID]+" Furballs Out Of 5&width=495&height=45");
			$("img#thanksTop").attr("src", "images/layout/thanks3.png");
		}
	}
	else
	{
		$("div#ratings").show();
		$("div#thanks").hide();	
	}
	
	// set size of comic table and div positions
	$("div.stuff").css("top", (heights[curID]+5)+"px");

	if ($.browser.safari)
		$("table#comments").css("top", "130px");
	else
		$("table#comments").css("top", "110px");
		
	// ********************** load in the new comments
	$("table#comStart").hide();
	$("table#loadingComments").show();
		
	var pth = top.location.href;
	var p = pth.lastIndexOf("index.php");
	pth = pth.substr(0,p);
	$("a#perma").attr("href", pth + "index.php?comic="+files[curID]);
	
	// change stumbleupon / digg links
	var str = encodeURIComponent("http://www.sayagain.co.uk/furballs/index.php?comic="+files[curID]);
	var tit = encodeURIComponent("Furballs: "+titles[curID]);
	$("a#su").attr("href", "http://www.stumbleupon.com/submit?title="+tit+"&url="+str);
	$("a#diggURL").attr("href","http://digg.com/submit?url="+str+"&title="+tit+digg_suffix);
	
	// NOTE ---- get comments ajax function call MUST go at the end of this newComic2 function
	comCount++;
	$.post("bin/getComments.php", {comicID: (curID+1)}, function(data){
		comCompare++;
		if (comCompare<comCount)
			return;
		$("table#comStart").after(data).remove();
		$("table#loadingComments").hide();
		var n = $("img[id^='reportComment']").size();
		if (n!=0)
		{
			if (n==1)
				$("span#numComments").text("1 comment");
			else
				$("span#numComments").text(n+" comments");
			if ($.browser.safari)
				$("span#numComments").css("top", "45px").css("left", "45px");
		}
		// IE fixes
		if ($.browser.msie)
		{
			$("table#comments").css("left", "15px");
			$("td.comment1").css("padding-left", "30px").css("padding-right", "30px");
		}
		$("img[id^='reportComment']").css("cursor", "pointer").click(function(){
				// clicked on report comment button
				if ($(this).attr("id")=="reportCommentX")
				{
					$("div#reported").show();
					$("img#reportedText").attr("src", "");
					$("img#reportedText").attr("src", "bin/makeText.php?width=450&height=200&bgcol=100001&fgcol=FEFEFE&text=This Comment Has Already^Been Moderated And Found^To Be Acceptable^ ^Thanks For Your Support");
				}
				else
				{
					var str = $(this).attr("id");
					str = str.substr(str.lastIndexOf("t")+1);
					$("div#reportMid").html($("span#comContent"+parseInt(str)).html());
					$("div#reportComment").show();
					commentScrutiny = parseInt(str);
				}
			});
		resizeTables();
		if (bNewComment)
		{
			bNewComment=false;
			targ = Math.min($("td.comment1:last").offset().top, Math.abs($(document).height()-$(window).height()));
			$("body,html").animate({scrollTop: targ}, 1000);
		}
	}, "text");
}

function resizeTables()
{
	var h = 350 + heights[curID];
	$("td.comment1").each(function(){ h += $(this).height(); h+=4;});
	$("td#whitey").css("height", h);
}

function addComment()
{
	// add comment to current comic's comments
	var com = document.forms.addCom.comment.value;
	var author = document.forms.addCom.author.value;
	$("span#commentWarning").text("PLEASE WAIT - CONTACTING SERVER");
	$("img#submitComment").hide();
	$.post("bin/addComment.php", { comment: com, auth: author, comicID: parseInt(curID)+1 }, function(data){
		// receive word form HQ about the comment's validity
		if (data=="SUCCESS")
		{
			// all A-OK so far
			$("span#commentWarning").text("Your comment has been successfully added to the comments list. You may close this window when ready");
			bNewComment=true;
			newComic();
		}
		else
		{
			$("span#commentWarning").text(data);
			$("img#submitComment").show();
		}
		}, "text");
}

function reportComment()
{
	// send ajax report of comment reporting
	$("div#reportMid").html("Please Wait...<br/><br/>Contacting Server");
	$.post("bin/reportComment.php", {ID: commentScrutiny}, function(data){
			// result of reporting comment
			$("div#reportComment").hide();
			$("img#reportedText").attr("src", "");
			if (data.indexOf("ERROR")==-1)
			{
				$("img#reportedText").attr("src", "bin/makeText.php?width=450&height=200&bgcol=100001&fgcol=FEFEFE&text=The Comment Has Been^Reported And A Moderator^Will View It Shortly^ ^Thanks For Your Support");
			}
			else
			{
				$("img#reportedText").attr("src", "bin/makeText.php?width=450&height=200&bgcol=100001&fgcol=FEFEFE&text=SERVER ERROR - the server is^having a schizophrenic episode,^please try reporting the comment^again in a short while");
			}
			$("div#reported").show();
		}, "text");
}

function next()
{
	if (curID==numFiles) return;
	curID++;
	if (curID>=numFiles)
	{
		curID=numFiles;
		$("div#next").css("background-position", "0px -74px").data("off", "disabled");
		$("div#last").css("background-position", "0px -74px").data("off", "disabled");
	}
	$("div#first").css("background-position", "0px 0px").data("off", "");
	$("div#prev").css("background-position", "0px 0px").data("off", "");
	newComic();
}

function prev()
{
	if (curID==0) return;
	curID--;
	if (curID==0)
	{
		$("div#first").css("background-position", "0px -74px").data("off", "disabled");
		$("div#prev").css("background-position", "0px -74px").data("off", "disabled");
	}
	$("div#next").css("background-position", "0px 0px").data("off", "");
	$("div#last").css("background-position", "0px 0px").data("off", "");
	newComic();
}

function first()
{
	if (curID==0) return;
	curID=0;
	$("div#next").css("background-position", "0px 0px").data("off", "");
	$("div#last").css("background-position", "0px 0px").data("off", "");
	$("div#first").css("background-position", "0px -74px").data("off", "disabled");
	$("div#prev").css("background-position", "0px -74px").data("off", "disabled");
	newComic();
}

function last()
{
	if (curID==numFiles) return;
	curID=numFiles;
	$("div#next").css("background-position", "0px -74px").data("off", "disabled");
	$("div#last").css("background-position", "0px -74px").data("off", "disabled");
	$("div#first").css("background-position", "0px 0px").data("off", "");
	$("div#prev").css("background-position", "0px 0px").data("off", "");
	newComic();
}

function getTitle()
{	
	$("img#comicTitle").attr("src", "bin/makeTitle.php?text="+titles[curID]);
}

function rateFail()
{
	blockActivity(false);
	// show an error screen - failed to contact server
	alert("Sorry, the server is unresponsive.  Please try again soon");
	$("img#thanksImg").attr("src","bin/makeText.php?text=Error - server timed out^please try again later&width=495&height=45&fgcol=000000&bgcol=FFEEDD");
	$("img#thanksTop").attr("src", "");
	$("div#ratings").hide();
	$("div#thanks").show();
}

// rate this comic based on var passed in
function rate(n)
{
	blockActivity(true, "layout/pleasewait.png");
	lastVoteID=curID;
	clearTimeout(timer);
	timer = setTimeout("rateFail()", 10000);
	$.post("bin/rateComic.php", {rating: n, file: files[curID]}, function(data){
		clearTimeout(timer);
		if (data=="ERROR" || data.length > 4)
		{
			// show error message to user and ask them to try again later
			$("img#thanksImg").attr("src","bin/makeText.php?text=Error - unable to connect to^database - please try again later&width=495&height=45&fgcol=000000&bgcol=FFEEDD");
			$("img#thanksTop").attr("src", "");
			$("div#ratings").hide();
			$("div#thanks").show();
		}
		else
		{
			var x = parseFloat(data);
			var res = Math.floor(x*10.0)/10.0;
			scores[lastVoteID] = res;
			$("img#thanksImg").attr("src","bin/makeText.php?text="+res+" Furballs Out Of 5&width=495&height=40&fgcol=000000&bgcol=FFEEDD");
			//$("img#thanksTop").attr("src", "images/layout/thanks.png");
			$("div#ratings").hide();
			$("div#thanks").show();
			$("img#thanksTop").attr("src", "images/layout/thanks.png");
			blockActivity(false);
			c = new cookieObject("comicRating", 31, "/", "file");
			if (c.found)
			{
				var str = c.get("file");
				if (str.indexOf(files[curID]==-1))
					str = str + files[curID];
				c.put("file", str+"--");
			}
			else
				c.put("file", files[curID]+"--");
			c.write();
		}
	}, "text");
}

// setup the ratings system and other stuff
function setup()
{
	// set rating system hover functions
	$("div#rateFull").mousemove(function(m){
			var x = m.pageX - $(this).offset().left;
			//alert(x);
			$(this).css("width", x+"px");
			$("div#rateEmpty").css("width", (200-x)+"px");
			r = Math.floor((x/40)*10.0)/10.0;
			$("span#rating").text(r);
		}).click(function(){
			rate(parseFloat($("span#rating").text()));
		});
	$("div#rateEmpty").mousemove(function(m){
			var x = m.pageX - $("div#rateFull").offset().left;
			//alert(x);
			$("div#rateFull").css("width", x+"px");
			$(this).css("width", (200-x)+"px");
			r = Math.floor((x/40)*10.0)/10.0;
			$("span#rating").text(r);
		}).click(function(){
			rate(parseFloat($("span#rating").text()));
		});
	$("span#rating").mousemove(function(m){
		$("div#rateFull").css("width","200px");	
		$("div#rateEmpty").css("width","0px");
		$(this).text("5.0");
		}).click(function(){
			rate(5);
		});
	$("img#rate0").mouseover(function(m){
		$("div#rateFull").css("width","0px");	
		$("div#rateEmpty").css("width","200px");
		$("span#rating").text("0.0");
		}).click(function(){
			rate(0);
		});

	$("img#repYes").click(reportComment);
	$("img#repNo").click(function(){ $("div#reportComment").hide(); });
	$("img#reportedOK").click(function(){ $("div#reported").hide(); newComic(); });
	$("img.addComment").click(function(){
		$("input#author").attr("value","Type your name here (or leave blank)").focus(function(){ $(this).attr("value","").unbind("focus"); });
		$("textarea#comment").attr("value","Type your comment here").focus(function(){ $(this).attr("value","").unbind("focus"); });
		$("div#addComment").show(); $("img#submitComment").show();
		$("span#commentWarning").text("");
	});
	$("input#author").focus(function(){ $(this).attr("value","").unbind("focus"); });
	$("textarea#comment").focus(function(){ $(this).attr("value","").unbind("focus"); });
	$("img#submitComment").click(addComment);
}

// function to prevent user input (set bShow to true to block input, and urlToImage for an image to show such as loading or please wait)
function blockActivity(bShow, urlToImage)
{
	if ($("div#blockActivity").size()==0)
	{
		// make the blocking div
		var h= $(window).height()/2;
		$("body").append("<div align='center' id='blockActivity' style='width: 100%; height: 100%; display:none;"+
						 "padding-top: "+h+"px; text-align:center; position: fixed; top: 0px; margin: 0 auto; z-index:999;'>"+
						 "&nbsp;</div>");
	}
	
	if (bShow)
	{
		var a = $("div#blockActivity");
		a.show();
		if (urlToImage!=null)
		{
			a.html("<img src='"+urlToImage+"' />");
		}
	}
	else
	{
		$("div#blockActivity").hide();
	}
}