var THUMBNAIL_PIC_SIZE = "150";
var MEDIUM_PIC_SIZE = "700";
var map = null;
var oldValue = null;
var registry = Array();

function removeNL(s){ 
  return s.replace(/[\n\r\t]/g,""); 
}

function getHTTPObject() {
	var xmlhttp;
  
	if (window.XMLHttpRequest)
		xmlhttp = new XMLHttpRequest();
	else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		if (xmlhttp == null)
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}

	return xmlhttp;
}

function getParameterValue(ParameterName) {
	var url = window.document.URL.toString();

	if (url.indexOf("?") > 0) {
		var Parameters = url.split("?")[1].split("&");
		for (i=0;i<Parameters.length;i++) {
			if (Parameters[i].indexOf("=") > 0) {
				var ParameterValue = [];
				ParameterValue[0] = Parameters[i].substring(0, Parameters[i].indexOf("="));
				ParameterValue[1] = Parameters[i].substring(Parameters[i].indexOf("=")+1,Parameters[i].length);
				if ( ParameterValue[0] == ParameterName)
					return decodeURIComponent(ParameterValue[1]);
			}
		}
	}
	return "";
}

function aybrequest(path, parameters) {
	if (typeof parameters.method == "undefined")
		parameters.method = "post";
	if (typeof parameters.async == "undefined")
		parameters.async = true;

	var varsString = "";
	for (key in parameters.vars) {
		varsString += "&" + key + "=" + encodeURIComponent(parameters.vars[key]);
	}

	http = getHTTPObject();
	if (parameters.method == "post")
		http.open("POST", url+path, parameters.async);
	else
		http.open("GET", url+path+varsString, parameters.async);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", varsString.length);
	http.setRequestHeader("Connection", "close");
	if (parameters.async) {
		http.onreadystatechange = function handleHttpResponse() {
										if ((http.readyState == 4) && (http.status == 200)) {
											if (typeof parameters.onComplete == "function")
												parameters.onComplete();
											var response = JSON.parse(http.responseText);
											if ((typeof parameters.onSuccess == "function") && (typeof response.success != "undefined") && (response.success == true))
													parameters.onSuccess(response);
											else if (typeof parameters.onFailure == "function")
													parameters.onFailure(response);
										}
									};
	}
	if (parameters.method == "post")
		http.send(varsString);
	else
		http.send(null);
	if (!parameters.async) {
		if (http.readyState == 4) {
			if (typeof parameters.onComplete == "function")
				parameters.onComplete();
			if (http.status == 200) {
				var response = JSON.parse(http.responseText);
				if ((typeof parameters.onSuccess == "function") && (typeof response.success != "undefined") && (response.success == true))
						parameters.onSuccess(response);
				else if (typeof parameters.onFailure == "function")
						parameters.onFailure(response);
			}
		}
	}
}

function swapDisplay(id1, id2) {
	if (document.getElementById(id1) && document.getElementById(id2)) {
		var display1 = document.getElementById(id1).style.display;
		var display2 = document.getElementById(id2).style.display;
		document.getElementById(id1).style.display = display2;
		document.getElementById(id2).style.display = display1;

	}
}

function restoreValue(id, value) {
	if (document.getElementById(id)) {
		document.getElementById(id).value = value;
	}
}

function captureKey(event, functionToCall) {
	var e = event || window.event;
	var code = e.charCode || e.keyCode;
	switch (code) {
		case 13:
			eval(functionToCall);
		break;
	}
}

var comment = {
	vote: function (commentId, direction) {
		var oldVoteCount = 0;
		
		if (document.getElementById(commentId+'_votes')) {
			oldVoteCount = document.getElementById(commentId+'_votes').innerHTML;
			document.getElementById(commentId+'_votes').innerHTML = loadingImage;
		}

		if (document.getElementById(commentId+'_followCommentVotes')) {
			oldVoteCount = document.getElementById(commentId+'_followCommentVotes').innerHTML;
			document.getElementById(commentId+'_followCommentVotes').innerHTML = loadingImage;
		}

		new aybrequest('comment/vote', {
			async: true,
			method: 'post',
			vars: {
				commentId: commentId,
				direction: direction
			},
			onSuccess: function (response) {
				if (document.getElementById(commentId+'_votes'))
					document.getElementById(commentId+'_votes').innerHTML = response.voteCount;
				if (document.getElementById(commentId+'_followCommentVotes'))
					document.getElementById(commentId+'_followCommentVotes').innerHTML = response.voteCount;
			},
			onFailure: function (response) {
				if (document.getElementById(commentId+'_votes'))
					document.getElementById(commentId+'_votes').innerHTML = oldVoteCount;
				if (document.getElementById(commentId+'_followCommentVotes'))
					document.getElementById(commentId+'_followCommentVotes').innerHTML = oldVoteCount;
			}
		});
	},
	confirmRemove: function (commentId) {
		document.getElementById('commentX_'+commentId).style.display = "none";
		document.getElementById('commentConfirmRemove_'+commentId).style.display = "inline";
	},
	remove: function (commentId) {
		if (confirm('Are you ABSOLUTELY SURE you want to delete this comment forever?')) {
			new aybrequest('comment/remove', {
				async: true,
				method: 'post',
				vars: {
					commentId: commentId
				},
				onSuccess: function (response) {
					document.getElementById('pictureCommentsBody').removeChild(document.getElementById('comment_'+commentId));
					document.getElementById('commentsForPic').innerHTML = parseInt(document.getElementById('commentsForPic').innerHTML) - 1;
					var commentContainers = document.getElementById('pictureCommentsBody').getElementsByTagName('div');
					for (var i=0;i<commentContainers.length;i++) {
						if (i%2 == 0)
							commentContainers[i].style.backgroundColor = '#F4F4F4';
						else
							commentContainers[i].style.backgroundColor = '#DFDFDF';
					}
				},
				onFailure: function (response) {
					alert('Unable to delete that comment.');
				}
			});
		}
	},
	reply: function (commentId, user1, user2) {
		registry[commentId] = document.getElementById('comment_'+commentId).innerHTML;
		new aybrequest('comment/conversation', {
			async: true,
			method: 'post',
			vars: {
				user1: user1,
				user2: user2
			},
			onSuccess: function (response) {
				var conversation = response.conversation;
				var html = '';
				html += '<span style="font-weight: bold; font-size: 1.3em; display: block"><a style="text-decoration: none" href="'+url+'/user/view/'+response.user2.id+'">'+response.user2.username+'</a></span>';
				html += '<div style="padding: 3px">';
				html += '<a style="text-decoration: none" href="'+url+'/user/view/'+response.user2.id+'">';
				html += '<img style="vertical-align: top" class="frame" src="'+url+'img/cache/'+response.user2.id+'/'+response.user2.filename+'_'+THUMBNAIL_PIC_SIZE+'.'+response.user2.ext+'"/></a>';
				html += '<a href="javascript:comment.restore('+commentId+')" style="padding-left: 15px">Close Coversation</a>';
				html += '</div>';
				html += '<textarea id="commentReplyInput_'+commentId+'" style="width: 97%; height: 100px" onkeyup="captureKey(event, \'comment.submitReply('+commentId+', '+user2+', '+response.user2.defaultPictureId+')\');countAndLimit(\'commentReplyInput_'+commentId+'\', \'commentLength_'+commentId+'\', '+MAX_COMMENT_LENGTH+', \'COMMENT_TOO_SHORT_'+commentId+'\')"></textarea>';
				html += '<br/><input id="sendButton_'+commentId+'" type="button" value="Send" onclick="comment.submitReply('+commentId+', '+user2+', '+response.user2.defaultPictureId+')"/>';
				html += ' (<span id="commentLength_'+commentId+'">'+MAX_COMMENT_LENGTH+'</span> letters remaining) <span id="COMMENT_TOO_SHORT_'+commentId+'" class="bold red" style="display: none">COMMENT TOO SHORT</span>';
				html += '<img src="'+url+'img/loading.gif" style="display: none" id="loadingImage_'+commentId+'"/>';
				var conversationText = conversation.conversation;
				for (i=0;i<conversationText.length;i++) {
					html += '<div class="conversation"><a href="'+url+'user/view/'+conversationText[i].authorId+'">'+conversationText[i].author+'</a>: '+conversationText[i].text+'</div>';
				}
				document.getElementById('comment_'+commentId).innerHTML = html;
				document.getElementById('commentReplyInput_'+commentId).focus();
			},
			onFailure: function (response) {
				document.getElementById('sendButon_'+commentId).style.display = 'inline';
				document.getElementById('commentReplyLoadingImage_'+commentId).style.display = 'none';
			}
		});
	},
	restore: function(commentId) {
		document.getElementById('comment_'+commentId).innerHTML = registry[commentId];
	},
	submitReply: function (commentId, userId, pictureId) {
		if (document.getElementById('loadingImage_'+commentId).style.display == "inline")
			return;
		if (document.getElementById('COMMENT_TOO_SHORT_'+commentId))
			document.getElementById('COMMENT_TOO_SHORT_'+commentId).style.display = "none";
		document.getElementById('sendButton_'+commentId).style.display = "none";
		document.getElementById('loadingImage_'+commentId).style.display = "inline";
		document.getElementById('commentReplyInput_'+commentId).disabled = true;
		new aybrequest('comment/add', {
			async: true,
			method: 'post',
			vars: {
				userId: userId,
				pictureId: pictureId,
				comment: document.getElementById('commentReplyInput_'+commentId).value				
			},
			onSuccess: function (response) {
				var newDiv = document.createElement('div');
				newDiv.innerHTML = '<a href="'+url+'user/view/'+response.requestId+'">'+response.requestUsername+'</a>: '+response.comment;
				newDiv.className = "conversation";
				var divs = document.getElementById('comment_'+commentId).getElementsByTagName('div');
				for (var i=0;i<divs.length;i++) {
					if (divs[i].className == 'conversation') {
						document.getElementById('comment_'+commentId).insertBefore(newDiv, divs[i]);
						document.getElementById('sendButton_'+commentId).style.display = 'inline';
						document.getElementById('loadingImage_'+commentId).style.display = 'none';
						document.getElementById('commentReplyInput_'+commentId).value = '';
						document.getElementById('commentLength_'+commentId).innerHTML = MAX_COMMENT_LENGTH;
						document.getElementById('commentReplyInput_'+commentId).disabled = false;
						document.getElementById('commentReplyInput_'+commentId).focus();
						break;
					}
				}
			},
			onFailure: function (response) {
				if (typeof response.error != "undefined") {
					if (document.getElementById(response.error+'_'+commentId))
						document.getElementById(response.error+'_'+commentId).style.display = "";
					else
						alert(response.error)
				} else
					alert('There was a problem processing your request.');
				document.getElementById('loadingImage_'+commentId).style.display = "none";
				document.getElementById('sendButton_'+commentId).style.display = "inline";
				document.getElementById('commentReplyInput_'+commentId).disabled = false;
			}
		});
	},
	add: function (userId, pictureId) {
		if (document.getElementById('loadingimage').style.display == "inline")
			return;
		document.getElementById('COMMENT_TOO_SHORT').style.display = "none";
		document.getElementById('sendbutton').style.display = "none";
		document.getElementById('loadingimage').style.display = "inline";
		document.getElementById('comment').disabled = true;
		new aybrequest('comment/add', {
			async: true,
			method: 'post',
			vars: {
				comment: document.getElementById('comment').value,
				userId: userId,
				pictureId: pictureId
			},
			onComplete: function (response) {
				document.getElementById('comment').disabled = false;
				document.getElementById('comment').blur();
				document.getElementById('comment').focus();
			},
			onSuccess: function (response) {
				document.getElementById('commentsForPic').innerHTML = parseInt(document.getElementById('commentsForPic').innerHTML) + 1;
				document.getElementById('sendbutton').style.display = "inline";
				document.getElementById('loadingimage').style.display = "none";
				document.getElementById('comment').value = "";
				document.getElementById('commentLength').innerHTML = MAX_COMMENT_LENGTH;

				var commentDiv = document.createElement('div');

				commentDiv.id = "comment_"+response.commentId;

				commentDiv.style.padding = "5px";
				commentDiv.style.borderTop = "1px solid #C1C1C1";
				
				var html = '<span id="commentConfirmRemove_'+response.commentId+'" style="display: none" class="strong">';
				html += 'Confirm comment delete? ';
				html += '<input type="button" value="DELETE COMMENT" onclick="comment.remove('+response.commentId+')"/> ';
				html += ' <input type="button" value="NO" onclick="swapDisplay(\'commentX_'+response.commentId+'\', \'commentConfirmRemove_'+response.commentId+'\')"/>';
				html += '</span>';
				html += '<span class="strong red pointer" title="Remove Comment" onclick="swapDisplay(\'commentX_'+response.commentId+'\', \'commentConfirmRemove_'+response.commentId+'\')" id="commentX_'+response.commentId+'">X</span>  ';
				if (response.requestId != userId)
					html += '<a href="'+url+'comments/conversation?user1='+response.requestId+'&user2='+userId+'" class="strong blue pointer" style="text-decoration: none" title="View Conversation">C</span> ';
				html += '<a href="'+url+'user/view/'+response.requestId+'">'+response.requestUsername+'</a>: '+response.comment;
				html += '<span id="'+response.commentId+'_votes" class="voter">0</span>';

				commentDiv.innerHTML = html;

				var existingCommentDivs = document.getElementById('pictureCommentsBody').getElementsByTagName('div');

				if (existingCommentDivs[0]) {
					if (existingCommentDivs[0].style.backgroundColor == "")
						commentDiv.style.backgroundColor = "#F4F4F4";

					document.getElementById('pictureCommentsBody').insertBefore(commentDiv, existingCommentDivs[0]);
				} else
					document.getElementById('pictureCommentsBody').appendChild(commentDiv);
			},
			onFailure: function (response) {
				if ((typeof response.error != "undefined") && (document.getElementById(response.error)))
					document.getElementById(response.error).style.display = "";
				else
					alert('Error leaving comment.');
				document.getElementById('sendbutton').style.display = "inline";
				document.getElementById('loadingimage').style.display = "none";
			}
		});
	},
	sort: function() {
		var redirectUrl = window.location.protocol+"//"+window.location.host+window.location.pathname.split('&')[0]+"&sortOrder="+document.getElementById('sortOrder').value;
		if (getParameterValue("direction") != "")
			redirectUrl += "&direction="+getParameterValue("direction");
		window.location = redirectUrl;
	},
	alterFavorite: function (action, commentId, isMini) {
		if ((action != "add") && (action != "remove"))
			return false;
		var prevHTML = document.getElementById('favoriteLink_'+commentId).innerHTML;

		if (!isMini)
			document.getElementById('favoriteLink_'+commentId).innerHTML = "<span style=\"text-decoration: none\">Thinking...</span>";

		new aybrequest("comment/"+action+"favorite", {
			vars: {
				commentId: commentId
			},
			onSuccess: function (response) {
				if (action == "add") {
					if (isMini)
						document.getElementById('favoriteLink_'+commentId).innerHTML = "<span class=\"strong green pointer\" style=\"vertical-align:middle\" title=\"Remove from Favorites\" onclick=\"comment.alterFavorite('remove', "+commentId+", true)\">*</span>";
					else
						document.getElementById('favoriteLink_'+commentId).innerHTML = "<span onclick=\"comment.alterFavorite('remove', "+commentId+")\">Remove Favorite</span>";
				} else {
					if (isMini)
						document.getElementById('favoriteLink_'+commentId).innerHTML = "<span class=\"strong pointer\" style=\"vertical-align:middle\" title=\"Add to Favorites\" onclick=\"comment.alterFavorite('add', "+commentId+", true)\">*</span>";
					else
						document.getElementById('favoriteLink_'+commentId).innerHTML = "<a onclick=\"comment.alterFavorite('add', "+commentId+")\">Add Favorite</span>";
				}
			},
			onFailure: function (response) {
				if (response.error)
					alert(response.error);
				else
					alert('There seems to be a problem');
				document.getElementById('favoriteLink_'+commentId).innerHTML = prevHTML;
			}
		});
	}
}

function countAndLimit(elementId, feedbackId, maxLength, tooShortErrorElement) {
	var textElement = document.getElementById(elementId);
	textElement.value = removeNL(textElement.value);
	var feedbackElement = document.getElementById(feedbackId);
	var inputLength = textElement.value.length;
	if ((inputLength > 4) && document.getElementById(tooShortErrorElement))
		document.getElementById(tooShortErrorElement).style.display = "none";
	if (inputLength > maxLength) {
		textElement.value = textElement.value.substr(0,maxLength);
	}
	else {
		if (maxLength-inputLength <= 10) {
			feedbackElement.style.color = '#FF0000';
			feedbackElement.style.fontWeight = 'bold';
		} else {
			feedbackElement.style.color = '';
			feedbackElement.style.fontWeight = '';
		}
		feedbackElement.innerHTML =  maxLength-inputLength;
	}
}

function setFaction(factionId) {
	var pictures = document.getElementsByTagName('img');
	for (i=0;i<pictures.length;i++) {
		if (pictures[i].id.indexOf('faction') != -1) {
			pictures[i].style.backgroundColor = '#DFDFDF';
		}
	}
	document.getElementById('faction_'+factionId).style.backgroundColor = '#63AF24';
	document.getElementById('faction').value = factionId;
}

var user = {
	login: function () {
		var username = document.getElementById('username').value;
		var password = document.getElementById('password').value;
		var remember = document.getElementById('remember').checked;
		if ((username == '') || (password == '')) {
			alert('You must enter a username and password!');
		} else {
			document.getElementById('buttoncell').innerHTML = loadingImage;
			new aybrequest('user/login', {
				async: true,
				method: 'post',
				vars: {
					username : username,
					password : password,
					remember : remember
				},
				onSuccess: function (response) {
					document.location = url;
				},
				onFailure: function (response) {
					if (response.error == "USER_IS_BANNED") {
						var html = '<h1>YOU ARE BANNED!</h1>';
						html += '<div><span class="strong">Reason:</span> '+response.reason+'</div>';
						html += '<div><span class="strong">Banned On:</span> '+response.timestamp+'</div>';
						html += '<br/><br/><a href="'+url+'unbanrequest">Want to be unbanned?</a>';
						document.getElementById('content').innerHTML = html;
					} else if (response.error == "TOO_MANY_FAILED_LOGINS") {
						var html = '<h1>Account has been locked</h1>';
						html += '<div>Due to too many failed login attempts your account has been locked for 15 minutes.</div>';
						html += '<div>Please <a href="'+url+'user/resetpassword">reset your password</a> if you cannot remember it.</div>';
						document.getElementById('content').innerHTML = html;
					} else
						document.getElementById('buttoncell').innerHTML = '<input type="button" value="Login" onclick="user.login()" name="cmd"/> <span class="strong red"> Credentials invalid</span>';
				}
			});
		}
	},

	resetPassword: function () {
		document.getElementById('loadingImage').style.display = "inline";
		document.getElementById('submitButton').style.display = "none";
		new aybrequest('user/resetpassword', {
			async: true,
			method: 'post',
			vars : {
				userId: document.getElementById('userId').value,
				password: document.getElementById('password').value,
				confirmpassword: document.getElementById('confirmpassword').value
			},
			onSuccess: function (response) {
				document.getElementById('passwordResetTable').style.display = "none";
				document.getElementById('passwordResetComplete').style.display = "block";
			},
			onFailure: function (response) {
				document.getElementById('loadingImage').style.display = "none";
				document.getElementById('submitButton').style.display = "inline";
				if (window.parent.document.getElementById(response.error))
					window.parent.document.getElementById(response.error).style.display = "inline";
				else
					alert('There was a problem with your request.');
			}
		});
	},

	saveProfile: function () {
		document.getElementById('response').innerHTML = "";
		document.getElementById('saveButton').style.display = 'none';
		document.getElementById('loadingImage').style.display = 'inline';
		new aybrequest('user/profile', {
			async: true,
			method: 'post',
			vars: {
				perPage : document.getElementById('perPage').value,
				quote : document.getElementById('quote').value,
				biography : document.getElementById('biography').value,
				faction : document.getElementById('faction').value,
				gamertag : document.getElementById('gamertag').value,
				showGamertag : document.getElementById('showGamertag').checked,
				wiicode : document.getElementById('wiicode').value,
				showWiicode : document.getElementById('showWiicode').checked,
				ps3Name : document.getElementById('ps3Name').value,
				showPs3Name : document.getElementById('showPs3Name').checked,
				latitude : document.getElementById('latitude').value,
				longitude : document.getElementById('longitude').value,
				nsfwFilterEnabled : document.getElementById('nsfwFilterEnabled').value
			},
			onSuccess: function (response) {
				document.getElementById('saveButton').style.display = 'inline';
				document.getElementById('loadingImage').style.display = 'none';
				document.getElementById('response').className = "strong green";
				document.getElementById('response').innerHTML = "Save successful.";
			},
			onFailure: function (response) {
				document.getElementById('response').className = "strong red";
				document.getElementById('response').innerHTML = "Error saving profile.";
			}
		});
	},

	setDefaultPicture: function(pictureId) {
		document.getElementById('defaultbutton_'+pictureId).style.display = "none";
		document.getElementById('removebutton_'+pictureId).style.display = "none";
		var inputs = document.getElementsByTagName('input');
		for (var i=0;i<inputs.length;i++) {
			if ((inputs[i].id.indexOf('defaultbutton') != -1) && (inputs[i].id != "defaultbutton_"+pictureId))
				inputs[i].style.display = "block";
			else if ((inputs[i].id.indexOf('removebutton') != -1) && (inputs[i].id != "removebutton_"+pictureId))
				inputs[i].style.display = "block";
		}

		new aybrequest('user/setDefaultPictureId', {
			async: true,
			method: 'post',
			vars: {
				pictureId: pictureId
			},
			onSuccess: function (response) {},
			onFailure: function (response) {
				alert('There was a problem processing your request.');
			}
		});
	},
	
	report: function (userId) {
		document.getElementById('reportbutton').innerHTML = 'Reason <input type="text" id="reason" size="30"/> <input type="button" value="Send" onclick="user.submitReport('+userId+')"/>';
	},
	
	submitReport: function (userId) {
		if (document.getElementById('reason').value.length < 5) {
			alert('Reason is too short.');
			return;
		}
		new aybrequest('user/report', {
			async: true,
			method: 'post',
			vars: {
				offenderId: userId,
				reason: document.getElementById('reason').value
			},
			onSuccess: function (response) {
				document.getElementById('reportbutton').innerHTML = 'Reported';
			},
			onFailure: function (response) {
				alert('There was a problem processing your request.');
			}
		});
	},
	
	block: function (userId) {
		new aybrequest('user/block', {
			async: true,
			method: 'post',
			vars: {
				userId: userId
			},
			onSuccess: function (response) {
				document.getElementById('blockbutton').className = "red";
				document.getElementById('blockbutton').setAttribute('onclick', 'user.unblock('+userId+')');
				document.getElementById('blockbutton').innerHTML = 'Unblock User';
			},
			onFailure: function (response) {
				alert(response.error);
			}
		});
	},
	
	unblock: function (userId) {
		new aybrequest('user/unblock', {
			async: true,
			method: 'post',
			vars: {
				userId: userId
			},
			onSuccess: function (response) {
				document.getElementById('blockbutton').className = "";
				document.getElementById('blockbutton').setAttribute('onclick', 'user.block('+userId+')');
				document.getElementById('blockbutton').innerHTML = 'Block User';
			},
			onFailure: function (response) {
				alert(response.error);
			}
		});
	},
	viewCliqueDetails: function () {
		if (document.getElementById('cliqueBreakdown').style.display != "block")
			document.getElementById('cliqueBreakdown').style.display = "block";
		else
			document.getElementById('cliqueBreakdown').style.display = "none";
	},
	selfban: function () {
		var confirm1 = document.getElementById('confirm1').checked;
		var confirm2 = document.getElementById('confirm1').checked;
		var confirm3 = document.getElementById('confirm1').checked;
		var banMePassword = document.getElementById('banMePassword').value;
		if ((confirm1) && (confirm2) && (confirm3) && (banMePassword != "")) {
			document.getElementById('banButton').style.display = 'none';
			document.getElementById('INVALID_PASSWORD').style.display = 'none';
			document.getElementById('loadingImage').style.visibility = 'visible';
			new aybrequest('user/selfban', {
				async: true,
				method: 'post',
				vars: {
					confirm1: confirm1,
					confirm2: confirm2,
					confirm3: confirm3,
					banMePassword: banMePassword
				},
				onSuccess: function (response) {
					window.location = url;
				},
				onFailure: function (response) {
					document.getElementById('banButton').style.display = 'inline';
					document.getElementById('loadingImage').style.visibility = 'hidden';
					if (document.getElementById(response.error))
						document.getElementById(response.error).style.display = "inline";
					else
						alert('Unable to self ban.');
				}
			});
		} else
			alert('You must indicate you understand the terms and put in your password before you ban yourself.');
	},
	unblockFromProfile: function (userId) {
		new aybrequest('user/unblock', {
			async: true,
			method: 'post',
			vars: {
				userId: userId
			},
			onSuccess: function (response) {
				document.getElementById('ignored_'+userId).style.display = 'none';
			},
			onFailure: function (response) {
				alert(response.error);
			}
		});
	},
	sortComments: function (pictureId) {
		window.location = window.location.protocol+"//"+window.location.host+window.location.pathname.split('&')[0]+"&sortOrder="+document.getElementById('sortOrder').value+"&page="+document.getElementById('currentPage').value+"&pic="+pictureId;
	}
}

var unbanRequest = {
	newRequest: function () {
		document.getElementById('loadingImage').style.display = 'inline';

		document.getElementById('requestButton').style.display = "none";

		document.getElementById('INVALID_USERID').style.display = "none";
		document.getElementById('INVALID_REASON').style.display = "none";
		document.getElementById('CODE_NOT_FOUND').style.display = "none";
		document.getElementById('ERRORS_WARNING').style.display = "none";

		new aybrequest('unbanrequest/newRequest', {
			async: true,
			method: 'post',
			vars: {
				userId: document.getElementById('userId').value,
				reason: document.getElementById('reason').value
			},
			onSuccess: function (response) {
				document.getElementById('unbanRequestForm').style.display = "none";
				document.getElementById('requestSuccess').style.display = "block";
				document.getElementById('loadingImage').style.display = "none";
			},
			onFailure: function (response) {
				document.getElementById('loadingImage').style.display = "none";
				document.getElementById('ERRORS_WARNING').style.display = "inline";
				document.getElementById('requestButton').style.display = "inline";

				if (response.error == "PENDING_REQUEST")
					document.getElementById('unbanRequestForm').style.display = "none";

				if (response.error == "NOT_BANNED")
					alert('You are not currently banned.');
				
				if (response.error != "" && document.getElementById(response.error))
					document.getElementById(response.error).style.display = "inline";
			}
		});
	},
	checkStatus: function () {
		document.getElementById('loadingImage_statusCheck').style.display = "inline";
		document.getElementById('statusCheckButton').style.display = "none";
		document.getElementById('INVALID_USERID_STATUSCHECK').style.display = "none";
		new aybrequest('unbanrequest/checkStatus', {
			async: true,
			method: 'post',
			vars: {
				userId: document.getElementById('userId_statusCheck').value
			},
			onSuccess: function (response) {
				document.getElementById('loadingImage_statusCheck').style.display = "none";
				document.getElementById('requestStatusRow').style.display = "table-row";
				document.getElementById('requestStatus').innerHTML = "On "+response.requestTimestamp+" you requested to be unbanned. Your application status is: "+response.status;

			},
			onFailure: function (response) {
				document.getElementById('loadingImage_statusCheck').style.display = "none";
				document.getElementById('statusCheckButton').style.display = "inline";

				if (response.error != "" && document.getElementById(response.error))
					document.getElementById(response.error).style.display = "inline";
				else if (response.error == "NO_REQUEST")
					alert("You do not currently have an unban request submitted.");
			}
		});
	}
}

var clique = {
	vote: function (userId) {
		document.getElementById('cliqueVoteLoadingImage').style.display = "inline";
		document.getElementById('cliqueVote').style.display = "none";
		new aybrequest('clique/vote', {
			async: true,
			method: 'post',
			vars: {
				cliqueId: document.getElementById('cliqueVote').value,
				userId: userId
			},
			onSuccess: function (response) {
				document.getElementById('cliqueVotes').innerHTML = parseInt(document.getElementById('cliqueVotes').innerHTML) + 1;
				document.getElementById('cliqueVoteResult').innerHTML = response.clique;
				document.getElementById('cliqueBreakdown').src = response.newBreakdownImg;
				document.getElementById('cliqueVoting').style.display = "none";
				if (parseInt(document.getElementById('cliqueVotes').innerHTML) != 1)
					document.getElementById('cliqueVotePlural').style.display = 'inline';
				else
					document.getElementById('cliqueVotePlural').style.display = 'none';
			},
			onFailure: function (response) {
				alert('There was a problem processing your request.');
				document.getElementById('cliqueVoteLoadingImage').style.display = "none";
				document.getElementById('cliqueVote').style.display = "inline";
				document.getElementById('cliqueVote').value = "";
			}
		});
	}
}

var goonglobe = {
	initializeBrowse: function () {
		map = new google.maps.Map2(document.getElementById("map"));
		map.setCenter(new google.maps.LatLng(document.getElementById('myLatitude').value, document.getElementById('myLongitude').value), 10);
		map.enableScrollWheelZoom();
		var mt = map.getMapTypes();
		for (var i=0; i<mt.length; i++) {
			mt[i].getMinimumResolution = function() {return 0;}
			mt[i].getMaximumResolution = function() {return 12;}
		}
		map.addControl(new GOverviewMapControl());
		map.addControl(new GLargeMapControl());
		GEvent.addListener(map, "moveend", function() {
			if ((Math.abs(map.getCenter().lat()-document.getElementById('lastLatitude').value) > .7) || (Math.abs(map.getCenter().lng()-document.getElementById('lastLongitude').value) > .7)) {
				document.getElementById('lastLatitude').value = map.getCenter().lat();
				document.getElementById('lastLongitude').value = map.getCenter().lng();
				goonglobe.populatePoints();
			}
		});

		goonglobe.populatePoints();
	},
	initializeProfile: function () {
		map = new google.maps.Map2(document.getElementById("map"));
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());

		var latitude = document.getElementById('latitude').value;
		var longitude = document.getElementById('longitude').value;
		if (latitude != 0) {
			map.setCenter(new GLatLng(latitude, longitude), 10);
			map.addOverlay(new GMarker(map.getCenter()));
		} else {
			map.setCenter(new GLatLng(41.771311, -98.613281), 3);
		}

		GEvent.addListener(map, "click", function(marker, point) {
			map.clearOverlays();
			document.getElementById('latitude').value = point.lat();
			document.getElementById('longitude').value = point.lng();
			map.addOverlay(new GMarker(point));
		});
	},
	populatePoints: function () {
		document.getElementById('loadingImage').style.display = "inline";
		new aybrequest('globe/getcoordinates', {
			async: true,
			method: 'get',
			vars: {
				latitude: document.getElementById('lastLatitude').value,
				longitude: document.getElementById('lastLongitude').value,
				factionId: document.getElementById('faction').value
			},
			onSuccess: function (response) {
				map.clearOverlays();
				document.getElementById('numberOfPoints').innerHTML = response.users.length;
				for (i=0;i<response.users.length;i++) {
					map.addOverlay(goonglobe.createMarker(response.users[i]));
				}
				document.getElementById('loadingImage').style.display = "none";
			},
			onFailure: function (response) {
				alert('There was a problem processing your request.');
			}
		});
	},
	createMarker: function (user) {
		var point = new GLatLng(user.latitude, user.longitude);
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function () {
			marker.openInfoWindowHtml('<div style="height: 100px; line-height: 8em"><a href="'+url+'user/view/'+user.id+'"><img style="vertical-align: middle" src="'+url+'img/sigpics/'+user.id+'.png"/></a></div>');
		});
		return marker;
	},
	remove: function () {
		map.clearOverlays();
		document.getElementById('latitude').value = "";
		document.getElementById('longitude').value = "";
	},
	changeCity: function() {
		var coordinates = document.getElementById('city').value;
		if (coordinates != "") {
			var coords = coordinates.split(",");
			if (coords.length == 2) {
				map.setCenter(new GLatLng(coords[0], coords[1]), 8);
			}
		}
	}
}

var picture = {
	remove: function(pictureId) {
		var answer = confirm("Are you sure you want to remove this picture and all the comments associated with it?");
		if (answer) {
			document.getElementById('row_'+pictureId).style.display = "none";
			new aybrequest('picture/remove', {
				async: true,
				method: 'post',
				vars: {
					pictureId: pictureId
				},
				onSuccess: function (response) {
					var numPics = 0;
					var rows = document.getElementById('pictures').rows;
					for (var i=0;i<rows.length;i++) {
						if (rows[i].style.display != "none")
							numPics++;
					}
					if (numPics < 10) {
						document.getElementById('max_pics_message').style.display = "none";
						document.getElementById('upload_form').style.display = "block";
					} else {
						document.getElementById('max_pics_message').style.display = "block";
						document.getElementById('upload_form').style.display = "none";
					}
				},
				onFailure: function (response) {
					alert('There was a problem processing your request.');
					document.getElementById('row_'+pictureId).style.display = "table-row";
				}
			});
		}
	},
	captionKeyCapture: function(event, pictureId) {
			var e = event || window.event;
			var code = e.charCode || e.keyCode;

			if (code == 13)
				picture.saveCaption(pictureId);
			else {
				if (document.getElementById('old_comment_'+pictureId).value != document.getElementById('new_comment_'+pictureId).value)
					document.getElementById('savecaption_'+pictureId).style.display = "inline";
				else
					document.getElementById('savecaption_'+pictureId).style.display = "none";
			}
	},
	saveCaption: function(pictureId) {
		document.getElementById('savecaption_'+pictureId).style.display = "none";
		document.getElementById('savecaption_indicator_'+pictureId).style.display = "inline";
		new aybrequest('picture/saveCaption', {
			async: true,
			method: 'post',
			vars: {
				pictureId: pictureId,
				caption: document.getElementById('new_comment_'+pictureId).value
			},
			onSuccess: function (response) {
				document.getElementById('old_comment_'+pictureId).value = document.getElementById('new_comment_'+pictureId).value;
				document.getElementById('savecaption_indicator_'+pictureId).style.display = "none";
			},
			onFailure: function (response) {
				alert('There was a problem processing your request.');
				document.getElementById('savecaption_indicator_'+pictureId).style.display = "none";
				document.getElementById('savecaption_'+pictureId).style.display = "inline";
			}
		});
	},
	upload: function (fileField) {
		var allowed_exts = /\.jpg|\.png|\.gif|\.jpeg/i;
		if (fileField.value.search(allowed_exts) == -1) {
			alert('That is not a valid image type! Must be jpg, png, gif, or jpeg');
			fileField.form.reset();
		} else {
			document.getElementById('new_pic_loading').style.display = "inline";
			fileField.form.submit();
		}
	},
	finishUpload: function (response) {
		window.parent.document.getElementById("new_pic_loading").style.display = "none";
		window.parent.document.getElementById("upload_form").reset();
		
		if (response.success) {
			var pictures = window.parent.document.getElementById("pictures");
			var row = pictures.insertRow(pictures.rows.length);
			row.id = 'row_'+response.pictureId;
			var pictureCell = row.insertCell(0);
			pictureCell.style.textAlign = "center";
			var img = window.parent.document.createElement('img');
			img.className = "frame";
			img.src = url+'img/cache/'+response.id+'/'+response.filename+'_'+THUMBNAIL_PIC_SIZE+'.'+response.ext;
			var commentsNum = window.parent.document.createElement('span');
			commentsNum.className = "commentsNum";
			commentsNum.innerHTML = "0 comments";
			pictureCell.appendChild(img);
			pictureCell.appendChild(commentsNum);
			var infoCell = row.insertCell(1);
			infoCell.className = "pictureInfoCell";
			var old_comment_input = window.parent.document.createElement('input');
			old_comment_input.id = "old_comment_"+response.pictureId;
			old_comment_input.type = "hidden";
			old_comment_input.value = "";
			infoCell.appendChild(old_comment_input);
			var new_comment_input = window.parent.document.createElement('input');
			new_comment_input.id = "new_comment_"+response.pictureId;
			new_comment_input.type = "text";
			new_comment_input.value = "";
			new_comment_input.style.width = "600px";
			new_comment_input.maxlength = "100";
			new_comment_input.setAttribute('onkeyup', "picture.captionKeyCapture(event, "+response.pictureId+")");
			infoCell.appendChild(new_comment_input);
			var savecaption_indicator = window.parent.document.createElement('img');
			savecaption_indicator.id = "savecaption_indicator_"+response.pictureId;
			savecaption_indicator.style.display = "none";
			savecaption_indicator.src = url+"img/loading.gif";
			infoCell.appendChild(savecaption_indicator);
			var savecaption_button = window.parent.document.createElement('input');
			savecaption_button.id = "savecaption_"+response.pictureId;
			savecaption_button.type = "button";
			savecaption_button.value = "Save Caption";
			savecaption_button.setAttribute('onclick', "picture.saveCaption("+response.pictureId+")");
			savecaption_button.style.display = "none";
			infoCell.appendChild(savecaption_button);
			var defaultbutton = window.parent.document.createElement('input');
			defaultbutton.id = "defaultbutton_"+response.pictureId;
			defaultbutton.style.display = "block";
			defaultbutton.type = "button";
			defaultbutton.value = "Set as Default";
			defaultbutton.setAttribute('onclick', "user.setDefaultPicture("+response.pictureId+")");
			infoCell.appendChild(defaultbutton);
			var removebutton = window.parent.document.createElement('input');
			removebutton.id = "removebutton_"+response.pictureId;
			removebutton.style.display = "block";
			removebutton.type = "button";
			removebutton.value = "Remove";
			removebutton.setAttribute('onclick', "picture.remove("+response.pictureId+")");
			infoCell.appendChild(removebutton);

			var nsfwbutton = window.parent.document.createElement('input');
			nsfwbutton.id = "nsfwbutton_"+response.pictureId;
			nsfwbutton.style.display = "block";
			nsfwbutton.type = "button";
			nsfwbutton.value = "Mark as NSFW";
			nsfwbutton.setAttribute('onclick', "picture.toggleNSFW("+response.pictureId+")");
			infoCell.appendChild(nsfwbutton);

			var numPics = 0;
			var rows = window.parent.document.getElementById('pictures').rows;
			for (var i=0;i<rows.length;i++) {
				if (rows[i].style.display != "none")
					numPics++;
			}

			if (numPics < 10) {
				window.parent.document.getElementById('max_pics_message').style.display = "none";
				window.parent.document.getElementById('upload_form').style.display = "block";
			} else {
				window.parent.document.getElementById('max_pics_message').style.display = "block";
				window.parent.document.getElementById('upload_form').style.display = "none";
			}
		} else {
			alert(response.error);
		}
	},
	showVoters: function (pictureId, commentId) {
		var key = 'pictureVoters_'+pictureId;
		if (typeof commentId != "undefined")
			key += '_'+commentId;
		if (document.getElementById(key))
			document.getElementById(key).style.visibility = "visible";
	}, 
	hideVoters: function (pictureId, commentId) {
		var key = 'pictureVoters_'+pictureId;
		if (typeof commentId != "undefined")
			key += '_'+commentId;
		if (document.getElementById(key))
			document.getElementById(key).style.visibility = "hidden";
	},
	vote: function (pictureId, direction, commentId) {
		var key = pictureId;
		if (typeof commentId != "undefined")
			key += '_'+commentId;

		document.getElementById('img_'+key).onmouseout = null;
		var oldVoteCount = 0;
		var voteCount = document.getElementById(key+"_votes");
		if (!voteCount)
			return;

		oldVoteCount = voteCount.innerHTML;
		voteCount.innerHTML = loadingImage;

		new aybrequest("picture/vote", {
			vars: {
				pictureId: pictureId,
				direction: direction
			},
			onSuccess: function (response) {
				voteCount.innerHTML = response.voteCount;
			},
			onFailure: function (response) {
				voteCount.innerHTML = oldVoteCount;
			}
		});
	}, toggleNSFW: function(pictureId) {
		var button = document.getElementById('nsfwbutton_'+pictureId);
		button.value = "";
		new aybrequest("picture/toggleNSFW", {
			vars: {
				pictureId: pictureId
			},
			onSuccess: function (response) {
				if (response.isNSFW) {
					button.value = "Mark as SFW";
				} else {
					button.value = "Mark as NSFW";
				}
			},
			onFailure: function (response) {
				alert("Error changing NSFW status of picture.");
			}
		});
	}
}

var filter = {
	browse: function () {
		var newUrl = url+'user/browse?';
		var gender = encodeURIComponent(document.getElementById('gender').value);
		var sortOrder = encodeURIComponent(document.getElementById('sortOrder').value);
		var clique = encodeURIComponent(document.getElementById('clique').value);
		var faction = encodeURIComponent(document.getElementById('faction').value);
		var gamers = encodeURIComponent(document.getElementById('gamers').value);
		var avatars = encodeURIComponent(document.getElementById('avatars').checked);
		var onlinenow = encodeURIComponent(document.getElementById('onlinenow').checked);
		newUrl += 'gender='+gender+'&sortOrder='+sortOrder+'&clique='+clique+'&faction='+faction+'&gamers='+gamers+'&avatars='+avatars+'&onlinenow='+onlinenow;
		window.location = newUrl;
	},
	reset: function () {
		document.getElementById('gender').value = "all";
		document.getElementById('sortOrder').value = 1;
		document.getElementById('clique').value = "all";
		document.getElementById('faction').value = "all";
		document.getElementById('gamers').value = "all";
		document.getElementById('avatars').checked = false;
		document.getElementById('onlinenow').checked = false;
	},
	toggleControls: function() {
		var filterImage = document.getElementById('filterImage');
		var filters = document.getElementById('filters');
		if (filterImage.src.indexOf('minus') == -1) {
			filters.style.display = "block";
			filterImage.src = url+"img/minus.gif";
		} else {
			filters.style.display = "none";
			filterImage.src = url+"img/plus.gif";
		}
	}
}

var award = {
	updateCountdown: function() {
		if (document.getElementById('awardCountdownSeconds')) {
			var seconds = document.getElementById('awardCountdownSeconds').innerHTML;
			if (seconds > 1) {
				var newSeconds = seconds - 1;
				var remainder = 0;
				var html = "";
				var days = Math.floor(newSeconds/(60*60*24));
				remainder = newSeconds-(60*60*24*days);
				if (days > 0)
					html += days+"d ";
				var hours = Math.floor(remainder/(60*60));
				remainder = remainder - (60*60*hours);
				if (hours > 0)
					html += hours+"h ";
				var hours = Math.floor(remainder/60);
				remainder = remainder - (60*hours);
				if (hours > 0)
					html += hours+"m ";
				if (remainder > 0) {
					html += remainder+"s";
				}
				document.getElementById('humanFriendlyCountdown').innerHTML = "(round ends in "+html+")";
				document.getElementById('awardCountdownSeconds').innerHTML = newSeconds;
				setTimeout("award.updateCountdown()", 1000);
			} else
				document.getElementById('humanFriendlyCountdown').innerHTML = 'ROUND OVER! <img src="http://awfulyearbook.com/img/emoticons/emot-downsbravo.gif"/>';
		}
	},
	vote: function (awardId, userId, username, pictureId) {
		if (awardId != "") {
			document.getElementById('award_vote_td_'+awardId).className = "";
			document.getElementById('award_vote_button_'+awardId).style.display = "none";
			document.getElementById('award_button_loading_'+awardId).style.display = "inline";
			new aybrequest('award/vote', {
				async: true,
				method: 'post',
				vars: {
					awardId: awardId,
					userId: userId,
					pictureId: pictureId
				},
				onSuccess: function (response) {
					document.getElementById('award_vote_td_'+awardId).style.display = "none";
					document.getElementById('award_you_voted_'+awardId).innerHTML = '(you voted for <a href="'+url+'user/view/'+userId+'>'+username+'</a>)';
				},
				onFailure: function (response) {
					document.getElementById('award_vote_td_'+awardId).className = "view_actions";
					document.getElementById('award_button_loading_'+awardId).style.display = "none";
					document.getElementById('award_vote_button_'+awardId).style.display = "inline";
					if (response.error)
						alert('ERROR: '+response.error);
				}
			});
		}
	},
	suggest: function () {
		var suggestion = document.getElementById('suggestion').value;
		if (suggestion.length > 5) {
			document.getElementById('submit').style.display = 'none';
			document.getElementById('loadingImage').style.display = 'inline';
			new aybrequest('award/suggest', {
				async: true,
				method: 'post',
				vars: {
					suggestion: suggestion
				},
				onSuccess: function (response) {
					alert('Your suggestion has been added.');
					window.location.reload();
					document.getElementById('submit').style.display = 'inline';
					document.getElementById('loadingImage').style.display = 'none';
				},
				onFailure: function (response) {
					document.getElementById('submit').style.display = 'inline';
					document.getElementById('loadingImage').style.display = 'none';
					if (response.error)
						alert(response.error);
					else
						alert('FAILED!');
				}
			});
		} else
			alert('That can\'t be a very good suggestion...');
	},
	voteSuggestion: function (awardId, direction) {
		document.getElementById(awardId+'_votes').innerHTML = '<img src="'+url+'img/loading.gif"/>';
		new aybrequest('award/votesuggestion', {
			async: true,
			method: 'post',
			vars: {
				awardId: awardId,
				direction: direction
			},
			onSuccess: function (response) {
				document.getElementById(awardId+'_votes').innerHTML = response.votes;
			},
			onFailure: function (response) {
				document.getElementById(awardId+'_votes').innerHTML = response.votes;
			}
		});
	}
}

var thread = {
	add: function (userId) {
		var threadId = document.getElementById('threadId').value;
		if (threadId == "") {
			alert('You might want to try entering a thread id.');
			return;
		}
		document.getElementById('addThreadLoadingImage').style.display = "inline";
		new aybrequest('thread/add', {
			async: true,
			method: 'post',
			vars: {
				threadId: threadId,
				userId: userId
			},
			onSuccess: function (response) {
				document.getElementById('addThreadLoadingImage').style.display = "none";
				var threadsTable = document.getElementById('threadsTable');
				var newRow = threadsTable.insertRow(threadsTable.rows.length);
				var titleCell = newRow.insertCell(0);
				titleCell.innerHTML = '<a href="'+response.thread.url+'">'+response.thread.title+'</a>';
				var ratingCell = newRow.insertCell(1);
				var html = '<img class="rating" src="'+url+'img/threadratings/';
				if (response.thread.votes > 0)
					html += Math.round(response.thread.rating)+'stars';
				else
					html += 'norating';
				html += '"/>';
				ratingCell.innerHTML = html;

			},
			onFailure: function (response) {
				document.getElementById('addThreadLoadingImage').style.display = "none";
				document.getElementById('addThreadResult').className = "red";
				if (response.error)
					document.getElementById('addThreadResult').innerHTML = response.error;
				else
					document.getElementById('addThreadResult').innerHTML = "There was a problem processing your request.";
			}
		});
	},
	changeVisibility: function (threadId) {
		document.getElementById('threadVisibilityImg_'+threadId).style.visibility = "visible";
		var isVisible = document.getElementById('threadVisibility_'+threadId).value;
		new aybrequest('thread/changeVisibility', {
			method: 'post',
			async: true,
			vars: {
				threadId: threadId,
				isVisible: isVisible
			},
			onSuccess: function (response) {
				document.getElementById('threadVisibilityImg_'+threadId).style.visibility = "hidden";
			},
			onFailure: function (response) {
				document.getElementById('threadVisibilityImg_'+threadId).style.visibility = "hidden";
			}
		});
	}
}

function search() {
	var keyword = document.getElementById('keyword').value;
	var category = document.getElementById('category').value;
	if (keyword.length < 3) {
		alert('Search term must be atleast 3 characters.');
	} else {
		document.getElementById('loadingImage').style.display = "inline";
		document.getElementById('actionButton').style.display = "none";
		window.location = window.location.protocol+"//"+window.location.host+window.location.pathname.split('&')[0]+"&keyword="+encodeURIComponent(keyword)+"&category="+encodeURIComponent(category);
	}
}

var pagination = {
	select: function () {
		var page = document.getElementById('page');
		oldValue = page.value;
		page.value = "";
		page.select();
		page.style.color = "black";
	},
	captureKey: function(event, paginationUrl) {
		var e = event || window.event;
		var code = e.charCode || e.keyCode;

		if (code == 13) {
			window.location = paginationUrl+document.getElementById('page').value;
		}
	},
	blur: function() {
		var page = document.getElementById('page');
		page.style.color = "grey";
		page.value = "";
		page.value = oldValue;
	}
}

var register = {
	reveal: function () {
		document.getElementById('confirmRules').style.display = "none";
		document.getElementById('registrationForm').style.display = "block";
	},
	cya: function () {
		window.location = "http://signup.myspace.com/index.cfm?fuseaction=join";
	},
	submitRegistration: function () {
		var fileField = document.getElementById('incoming_file');
		var allowed_exts = /\.jpg|\.png|\.gif|\.jpeg/i;
		if (fileField.value.search(allowed_exts) == -1) {
			document.getElementById('INVALID_PICTURE').style.display = "inline";
		} else {
			document.getElementById('loadingImage').style.display = "inline";
			document.getElementById('registerButton').style.display = "none";

			document.getElementById('INVALID_USERID').style.display = "none";
			document.getElementById('PASSWORD_TOO_SHORT').style.display = "none";
			document.getElementById('MISMATCHED_PASSWORDS').style.display = "none";
			document.getElementById('INVALID_GENDER').style.display = "none";
			document.getElementById('INVALID_PICTURE').style.display = "none";
			document.getElementById('CODE_NOT_FOUND').style.display = "none";
			document.getElementById('ERRORS_WARNING').style.display = "none";
			
			fileField.form.submit();
		}
	},
	finishRegistration: function (response) {
		window.parent.document.getElementById("loadingImage").style.display = "none";
		if (response.success) {
			window.parent.document.getElementById('registrationForm').style.display = "none";
			window.parent.document.getElementById('registrationComplete').style.display = "block";
			//setTimeout('parent.window.location="'+url+'user/login"', 1000);
		} else {
			window.parent.document.getElementById('registerButton').style.display = "inline";
			if (window.parent.document.getElementById(response.error))
				window.parent.document.getElementById(response.error).style.display = "inline";
			else if (response.error == "ALREADY_REGISTERED") {
				alert('You are already registered for the yearbook, go login.');
				window.parent.location = url;
			} else
				alert(response.error);
			window.parent.document.getElementById('ERRORS_WARNING').style.display = "inline";
		}
	}
}

var buddyList = {
	add: function () {
		var username = document.getElementById('username').value;
		if (username == "") {
			document.getElementById('INVALID_USERNAME').style.display = "inline";
		} else {
			document.getElementById('loadingImage').style.visibility = "visible";
			document.getElementById('addButton').style.visibility = "hidden";
			document.getElementById('INVALID_USERNAME').style.display = "none";
			document.getElementById('DUPLICATE_BUDDY').style.display = "none";
			document.getElementById('CANNOT_ADD_SELF').style.display = "none";
			document.getElementById('BANNED_BUDDY').style.display = "none";
			new aybrequest('buddylist/add', {
				method: 'post',
				async: true,
				vars: {
					username: username
				},
				onSuccess: function (response) {
					document.getElementById('addButton').style.visibility = "visible";
					document.getElementById('SUCCESSFUL_ADD').style.display = "inline";
					setTimeout("document.getElementById('SUCCESSFUL_ADD').style.display = 'none'", 2000);
					setTimeout("document.getElementById('username').value = ''", 300);
					var table = document.getElementById('buddyList');
					table.innerHTML = "";
					for (var i=0;i<Math.ceil(response.buddyList.buddies.length/5);i++) {
						var row = document.createElement('tr');
						for (var j=0;j<5;j++) {
							if ((i*5)+j < response.buddyList.buddies.length) {
								var cell = document.createElement('td');
								var buddy = response.buddyList.buddies[(i*5)+j];
								var html = '<a href="'+url+'user/view/'+buddy.buddyId+'&pic='+buddy.pictureId+'">';
								html += '<img class="frame" src="'+url+'img/cache/'+buddy.filename+'_'+THUMBNAIL_PIC_SIZE+'.'+buddy.ext+'"/>';
								html += '</a><br />';
								html += '<a class="username" href="'+url+'user/view/'+buddy.buddyId+'?pic='+buddy.pictureId+'">'+buddy.username+'</a>';
								cell.innerHTML = html;
								row.appendChild(cell);
							}
						}
						table.appendChild(row);
					}
					document.getElementById('loadingImage').style.visibility = "hidden";
					//loop through & add buddies from response.buddyList using DOM
				},
				onFailure: function (response) {
					document.getElementById('loadingImage').style.visibility = "hidden";
					document.getElementById('addButton').style.visibility = "visible";
					if ((response.error != "") && document.getElementById(response.error))
						document.getElementById(response.error).style.display = "inline";
					else
						alert("There was a problem adding that user to your buddy list.");
				}
			});
		}
	},
	modifyBuddyList: function (userId, action) {
		document.getElementById('buddyButtonLoading').style.display = "inline";
		if (action == "add")
			document.getElementById('addBuddyButton').style.display = "none";
		else
			document.getElementById('removeBuddyButton').style.display = "none";
		new aybrequest('buddylist/'+action, {
			method: 'post',
			async: true,
			vars: {
				userId: userId
			},
			onSuccess: function (response) {
				document.getElementById('buddyButtonLoading').style.display = "none";
				if (action == "add")
					document.getElementById('removeBuddyButton').style.display = "inline";
				else
					document.getElementById('addBuddyButton').style.display = "inline";
			},
			onFailure: function (response) {
				if (response.error)
					alert(response.error);
				else
					alert('There seems to be a problem');
				document.getElementById('buddyButtonLoading').style.display = "none";
				if (action == "add")
					document.getElementById('addBuddyButton').style.display = "inline";
				else
					document.getElementById('removeBuddyButton').style.display = "inline";
			}
		});
		
	}
}