var iScrollStep = 0;
var oTimeout = false;
var iNumTopicChecked = 0;

function checkUsername(sUsername, oInput)
{
	if(!sUsername)
	{
		$(oInput).removeClass("success");
		$(oInput).addClass("error");
		return;
	}

	$.get("/forum/check-username/", { username: sUsername }, function(bInUse)
		{
			if(bInUse == "true")
			{
				throwError(oInput, "Deze naam is al in gebruik.");
			}
			else
			{
				clearError(oInput);
			}
		});
}

function checkPasswords(sFormID)
{
	sPass1 = $("#password1").attr("value");
	sPass2 = $("#password2").attr("value");

	if(sPass1 && sPass2)
	{
		if(sPass1.length < 4 || sPass2.length < 4 || sPass2 != sPass1)
		{
			throwError("#"+sFormID+" input[type=password]", "Beide wachtwoorden moeten hetzelfde zijn en minimaal 4 karakter lang zijn.");
		}
		else
		{
			clearError("#"+sFormID+" input[type=password]");
		}
	}
}

function checkEmailAddress(sEmail, oInput, bCheckInUse)
{
	var oPattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

	if(oPattern.test(sEmail))
	{
		if(!bCheckInUse)
		{
			clearError(oInput);
			return;
		}

		$.get("/forum/check-email/", { email: sEmail }, function(bStatus)
		{
			$(oInput).parent().find(".inuse").remove();

			if(bStatus == "inuse")
			{
				throwError(oInput, "Dit e-mailadres is al in gebruik.");
				$(oInput).parent().append('<div class="inuse">Er is al een account met dit e-mailadres. <a href="/forum/forgot-password/?email='+sEmail+'">Klik hier als je je wachtwoord bent vergeten.</a></div>');
			}
			else if(bStatus == "hater")
			{
				throwError(oInput, "Je kunt je niet registreren met dit e-mailadres.");
				$(oInput).parent().append('<div class="inuse">Dit e-mailadres kan niet worden gebruikt voor registratie op onweer-online.</div>');
			}
			else
			{
				clearError(oInput);
			}
		});
	}
	else
	{
		throwError(oInput, "Dit is een ongeldig e-mailadres.");
	}
}

function throwError(oInput, sMessage)
{
	$(oInput).addClass("error");
	$(oInput).removeClass("success");
	$(oInput).attr("title", sMessage);
}

function clearError(oInput)
{
	$(oInput).addClass("success");
	$(oInput).removeClass("error");
	$(oInput).attr("title", "");
}

function loadConditions()
{
	if($("#conditionste").length) return;
	$("#registerform .columnleft").append('<label><textarea id="conditionste" readonly="readonly" rows="8" cols="40"></textarea></label>');
	$("#conditionste").load("/forum/load-conditions/");
}

function initPhotoTopic()
{
	iTotalWidth = 0;

	$("#tpphotos .imgcontainer").each(function()
	{
		iTotalWidth += $(this).width() + 6;
	});

	if(iTotalWidth == 0) return false;

	oContainerPos = $("#content").position();
	iContainerLeft = Math.round(oContainerPos.left);

	$("#tpphotos").css("width", iTotalWidth + "px");

	$("#tpcontainer").mousemove(function(e)
	{
		iCursorLeft = (e.pageX - this.offsetLeft - iContainerLeft);
		iScrollStep = Math.round(0 - ((iCursorLeft - 480) / 24));

	}).mouseover(function(e)
	{
		oTimeout = setTimeout("scrollPhotos()", 25);

	}).mouseout(function(e)
	{
		clearTimeout(oTimeout);
	});

}

function scrollPhotos()
{
	iWidth = $("#tpphotos").width();

	oPos = $("#tpphotos").position();
	iPos = oPos.left;

	iPos += iScrollStep;

	if(iPos < (0 - (iWidth - 957))) iPos = (0 - (iWidth - 957));
	if(iPos > 3) iPos = 3;

	$("#tpphotos").css("left", iPos + "px");

	oTimeout = setTimeout("scrollPhotos()", 50);
}


function modTopicAction(iTopicID, sAction)
{
	// Ja natuurlijk kun je onderstaande urls uitproberen en zien hoever je komt.
	// Laat me je plezier alvast bederven en vertellen dat je gewoon op de 404 pagina zult uitkomen.
	// Bedankt.

	sConfirm = '';

	if(sAction == "delete")
	{
		sConfirm = 'Weet je zeker dat je dit topic wilt verwijderen?';
	}
	else if(sAction == "delete_ban")
	{
		sConfirm = 'Weet je zeker dat je dit topic wilt verwijderen en de poster permanent wilt bannen?';
	}
	else if(sAction == "close")
	{
		sConfirm = 'Weet je zeker dat je dit topic wilt sluiten?';
	}

	if(sConfirm && confirm(sConfirm) == false) return false;

	window.location = '/forum/mod-topic/'+iTopicID+'/'+sAction+'/';
}

function modPostsAction(iTopicID, sAction)
{
	sConfirm = '';

	if(sAction == "delete")
	{
		sConfirm = 'Weet je zeker dat je deze post(s) wilt verwijderen?';
	}
	else if(sAction == "delete_ban")
	{
		sConfirm = 'Weet je zeker dat je deze post(s) wilt verwijderen en de auteur(s) permanent wilt bannen?';
	}

	if(sConfirm && confirm(sConfirm) == false) return false;

	sValues = '';

	$(".topic.post input[type=checkbox]:checked").each(function()
	{
		sValues += (sValues?';':'') + $(this).attr('value');
	});

	window.location = '/forum/mod-posts/'+iTopicID+'/'+sAction+'/?posts='+sValues;
}

function loadSelectboxTopics(iBoardID, sSelectboxID)
{
	$.get('/forum/load-selectbox-topics/'+iBoardID, function(data)
	{
		$('#'+sSelectboxID).html(data);
	});

}

function showNumberTopicChecked(oInput, bChecked)
{
	if(bChecked == true)
		iNumTopicChecked++;
	else
		iNumTopicChecked--;

	$("#num_selected_posts").html(iNumTopicChecked);
}



function getMessage(iID, iBox)
{
	$("#messagetable .selected").removeClass("selected").removeClass("isnew");
	$("#message"+iID).addClass("selected").removeClass("isnew");

	$.get("/message/get-message/"+iID+"/?mailbox="+iBox, function(data)
	{
		$("#fullmessage").html(data).show();
	});
}

function loadMailBox(iBox)
{
	$("#fullmessage").empty().hide();
	$("#mailmessages").load("/message/get-box/"+iBox);
}

function showBlock(sBlockID)
{
	$("#"+sBlockID).show();
}

function checkRecipients(sValue)
{
	aRecipients = sValue.split(',');
	if(aRecipients.length > 10)
	{
		$("#recipients_feedback").html('<span style="color:#ff0000;">Je kunt niet meer dan 10 ontvangers tegelijk invoeren.</span>');
	}
	else
	{
		$.post("/message/check-recipients/", {'recipients': sValue}, function(data)
		{
			$("#recipients_feedback").html(data);
		});
	}
}

function modifyRecipient(sOld, sNew)
{
	sRecipients = $("#recipients").attr('value');
	sRecipients = sRecipients.replace(sOld, sNew);

	$("#recipients").attr('value', sRecipients);

	checkRecipients(sRecipients);
}

function confirmDeleteMessage(iMessageID, iBox)
{
	if(confirm("Weet je zeker dat je dit bericht wilt verwijderen?"))
	{
		$.get("/message/delete-message/"+iMessageID, function(data)
		{
			$("#fullmessage").empty().hide();
			$("#mailmessages").load("/message/get-box/"+iBox);
		});
	}
}

function loadAddNoteForm()
{
	$("#addusernote").html('<textarea name="usernote" rows="5" cols="60"></textarea><br /><input type="submit" value="Toevoegen" /><br />&nbsp;');
}

function confirmEmptyUser(iUserID)
{
	if(confirm("Weet je zeker dat je alle topics en berichten van deze gebruiker wilt verwijderen?"))
	{
		if(confirm("Echt?"))
		{
			// probeer deze url en jij hebt meteen een ban
			window.location = '/forum/empty-user/'+iUserID+'/';
		}
	}
}

function confirmBanUser(iUserID)
{
	if(confirm("Weet je zeker dat je deze user wilt bannen?"))
	{
		// geldt ook voor deze
		window.location = '/forum/ban-user/'+iUserID+'/';
	}
}
function confirmUnBanUser(iUserID)
{
	if(confirm("Weet je zeker dat je de ban van deze user wilt opheffen?"))
	{
		// en ook voor deze. Probeer maar.
		window.location = '/forum/unban-user/'+iUserID+'/';
	}
}

function loadMorePhotos(iAlbumID, iUserID)
{
	oDivs = $("#album"+iAlbumID+" .photo");
	iNumPhotosLoaded = oDivs.length;
	$.getJSON("/fotos/get-extra-photos/"+iAlbumID+"/", {"numloaded": iNumPhotosLoaded, "user": iUserID}, function(data)
	{
		$("#album"+iAlbumID+" div.lastphoto").removeClass("lastphoto");

		for(i = 0; i < data.photos.length; i++)
		{
			sHTML = '\
	<div class="photo" onclick="showLargePhoto(this, '+iAlbumID+', \''+data.photos[i].url+'\', '+iUserID+');">\
		<div style="background-image:url(\''+data.photos[i].url+'\');"></div>\
		<div class="subtitle">'+data.photos[i].title+'</div>\
	</div>';

			$("#album"+iAlbumID).append(sHTML);
		}

		if($("#album"+iAlbumID+" .addphoto").length)
		{
			$("#album"+iAlbumID).append($("#album"+iAlbumID+" .addphoto"));
			$("#album"+iAlbumID+" .addphoto:first-child").remove();
		}

		$("#album"+iAlbumID).append($("#album"+iAlbumID+" .morebutton"));
		$("#album"+iAlbumID).append($("#album"+iAlbumID+" .clear"));

		if(data.photos.length < 14) $("#album"+iAlbumID+" .morebutton").remove();

		$("#album"+iAlbumID+" div.photo:nth-child(7n)").addClass("lastphoto");

		$("#footergrowdiv").css("height", "10px");
		rePositionFooter();
	});
}

function showLargePhoto(oThumb, iAlbumID, sThumbUrl, iUserID)
{
	iDocumentHeight = $("body").height();
	iDocumentWidth  = $("body").width();

	$("body").append('<div id="darkener"></div>');
	$("#darkener").click(function()
	{
		closePhoto();
	}).css({"width": iDocumentWidth+'px', "height": iDocumentHeight+'px'});

	sLargeUrl = sThumbUrl.replace(/_thumb\./, '.');

	sCaption = $(oThumb).find("div.subtitle").html();

	$("body").append('<div id="photocontainer"><img src="'+sLargeUrl+'" /><br /><div class="largephoto_caption">'+sCaption+'</div><div class="clear"></div></div>');

	iThumbID = /\/(\d+)_thumb\./.exec(sThumbUrl);
	processLargePhoto(iAlbumID, iThumbID[1], iUserID);
}

function loadNewPhoto(iAlbumID, sWhichWay, iCurrentPhotoID, iUserID)
{
	$(document).unbind("keyup");
	$.getJSON("/fotos/get-"+sWhichWay+"-photo/"+iAlbumID+"/"+iCurrentPhotoID+"/", {"u": iUserID}, function(sJson)
	{
		$("#photocontainer").remove();
		$("body").append('<div id="photocontainer"><img src="'+sJson.url+'" /><br /><div class="largephoto_caption">'+sJson.title+'</div><div class="clear"></div></div>');

		processLargePhoto(iAlbumID, sJson.id, iUserID);
	});
}

function processLargePhoto(iAlbumID, iPhotoID, iUserID)
{
	// default image size = 732 x 549
	centerObject($("#photocontainer"), 732, 549);

	$("#photocontainer img").bind("load", function()
	{
		iImageWidth  = $(this).width();
		iImageHeight = $(this).height();

		centerObject($("#photocontainer"), iImageWidth, iImageHeight);
		$("#photocontainer .largephoto_caption").width(iImageWidth);
		addPhotoButtons(iImageWidth, iImageHeight, iAlbumID, iPhotoID, iUserID);

		setKeyboardHandlers(iAlbumID, iPhotoID, iUserID);
	});
}

function setKeyboardHandlers(iAlbumID, iThumbID, iUserID)
{
	$(document).bind("keyup", function(event)
	{
		switch(event.which)
		{
			case 27:
				closePhoto();
				break;
			case 37:
				loadNewPhoto(iAlbumID, 'previous', iThumbID, iUserID);
				break;
			case 39:
				loadNewPhoto(iAlbumID, 'next', iThumbID, iUserID);
				break;
		}
	});
}

function addPhotoButtons(iImageWidth, iImageHeight, iAlbumID, iPhotoID, iUserID)
{
	$("#photocontainer").append('<div class="button buttonback" style="top:'+(iImageHeight - 22)+'px;"></div>');
	$("#photocontainer").append('<div class="button buttonnext" style="left:'+(iImageWidth - 22)+'px; top:'+(iImageHeight - 22)+'px;"></div>');
	$("#photocontainer").append('<div class="button buttonoptions" style="top:'+(iImageHeight - 22)+'px;"></div>');
	$("#photocontainer").append('<div class="button buttonclose" style="left:'+(iImageWidth - 22)+'px;"></div>');

	$("#photocontainer .buttonback").click(function()
	{
		loadNewPhoto(iAlbumID, 'previous', iPhotoID, iUserID);
	});

	$("#photocontainer .buttonnext").click(function()
	{
		loadNewPhoto(iAlbumID, 'next', iPhotoID, iUserID);
	});

	$("#photocontainer .buttonclose").click(function()
	{
		closePhoto();
	});

	$("#photocontainer .buttonoptions").click(function()
	{
		showPhotoOptions(iPhotoID);
	});
}

function showPhotoOptions(iPhotoID)
{
	sOriginalCaption = $("#photocontainer .largephoto_caption").html();

	$("#photocontainer .largephoto_caption").load("/fotos/get-photo-options/"+iPhotoID+"/");
	$("#photocontainer .buttonoptions").removeClass("buttonoptions").addClass("buttonoptionsclose").unbind();
	$("#photocontainer .buttonoptionsclose").click(function()
	{
		$("#photocontainer .largephoto_caption").html(sOriginalCaption);
		$("#photocontainer .buttonoptionsclose").removeClass("buttonoptionsclose").addClass("buttonoptions").unbind();
		$("#photocontainer .buttonoptions").click(function()
		{
			showPhotoOptions(iPhotoID);
		});
	});
}

function centerObject(oObject, iWidth, iHeight)
{
	iDocumentWidth  = $("body").width();
	iScrollPos = $(document).scrollTop();
	iBrowserHeight = $(window).height();

	iLeft = Math.round((iDocumentWidth - (iWidth + 30)) / 2);
	iTop = Math.round((iBrowserHeight - (iHeight + 65)) / 2) + iScrollPos;

	$(oObject).css({"left": iLeft+"px", "top": iTop+"px"});
}

function closePhoto()
{
	$("#darkener").remove();
	$("#photocontainer").remove();
	$(document).unbind("keyup");
}

function showMovePhotoDialog(iPhotoID)
{
//	$("#photocontainer .largephoto_caption").fadeOut("fast");

	$("#photocontainer .largephoto_caption").html('Selecteer hieronder het album waar je deze foto naartoe wilt verplaatsen.<br /><br /><select name="move_to" id="move_to"></select><input type="button" value="Verplaatsen" onclick="movePhoto('+iPhotoID+');" />');

	t = 0;

	$("h1 span").each(function()
	{
		if(t > 1)
		{
			sAlbumName = $(this).html();
			$("#move_to").append('<option value="'+sAlbumName+'">'+sAlbumName+'</option>');
		}
		t++;
	});
}

function movePhoto(iPhotoID)
{
	window.location = '/fotos/move-photo/'+iPhotoID+'/?album='+urlencode($("#move_to").val());
}

function confirmDeletePhoto(iPhotoID)
{
	if(confirm("Weet je zeker dat je deze foto permanent wilt verwijderen?")) window.location = '/fotos/delete-photo/'+iPhotoID;
}

function addPhotoTag(iPhotoID)
{
	$("#photocontainer .largephoto_caption").html('Voer hieronder een nieuwe TAG in. Een TAG beschrijft in 1 woord wat er te zien is op de foto. Je kunt meerdere keren een TAG toevoegen.<br /><br /><input type="text" size="10" maxlength="30" name="newtag" id="newtag" /><input type="button" value="Toevoegen" onclick="savePhotoTag('+iPhotoID+');" />');
}

function savePhotoTag(iPhotoID)
{
	sNewTag = $("#newtag").val();
	$.get("/fotos/add-tag/"+iPhotoID, {"tag": sNewTag}, function()
	{
		$("#photocontainer .largephoto_caption").html('Tag <strong style="text-transform:lowercase;">'+sNewTag+'</strong> opgeslagen. Je kunt hieronder eventueel nog een tag toevoegen.<br /><br /><input type="text" size="10" maxlength="30" name="newtag" id="newtag" /><input type="button" value="Toevoegen" onclick="savePhotoTag('+iPhotoID+');" />');
	});
}

function initForumIndex()
{
	// zorgt ervoor dat de hele rij klikbaar is, ipv alleen de link
	if($("table tr.board").length)
	{
		$("table tr.board").click(function(e)
		{
			e.preventDefault();
			sHref = $(this).find("a").attr("href");
			window.location = sHref;
		});
	}
}

function initBoard()
{
	if($("table tr.topicrow").length)
	{
		// enkele en dubbele selector voor browsers die wel en geen tbody aanmaken
		if($("table tr.topicrow:first-child").parent().hasClass("no_row_hilite")) return;
		if($("table tr.topicrow:first").parent().parent().hasClass("no_row_hilite")) return;

		$("table tr.topicrow").click(function(e)
		{
			//e.preventDefault();
			sHref = $(this).find("a").attr("href");
			window.location = sHref;
		});
	}
}

function makeAbbrevsClickable()
{
	$("abbr").click(function()
	{
		sUrl = $(this).attr("data-source");
		window.location = sUrl;
	});
}


$(document).ready(function()
{
	initPhotoTopic();
	initForumIndex();
	initBoard();

	makeAbbrevsClickable();

	$("#buttonscrolltop").click(function(e)
	{
		e.preventDefault();
		$("html,body").animate({scrollTop: 0},
		{
			duration: 1000,
			specialEasing:
			{
				width: 'linear',
				height: 'easeOutBounce'
			}
		});
	});
});