window.addEvent('domready', function() {

	// Update top-right links if logged in
	// Not security-critical: Assume cookie is valid
	if(Cookie.read('gbsid')) {
		document.id('header_login_link').set({
			text : 'Logout',
			href : 'http://www.goodblogs.com/logout'
		});

		document.id('header_signup_link').set({
			text : 'Your Account',
			href : 'http://www.goodblogs.com/edit-profile'
		});
	}


	// Default value in search box

	var searchBox = document.id('search').getElement('input[type=text]');
	var searchDefault = searchBox.value;
	searchBox.addEvent('focus',function() {
		if(searchBox.value == searchDefault) {
			searchBox.value = '';
		}
	});
	searchBox.addEvent('blur',function() {
		if(searchBox.value == '') {
			searchBox.value = searchDefault;
		}
	});


	// Place body ad after a <p> after at least minPos characters of text

	var adDiv = document.id('body_ad');
	if(adDiv) {
		var postBody = document.getElement('.post_body');
		var minPos = 900;
		var pos = 0;
		var paragraphs = postBody.getElements('p');
		for(var p=0; p < paragraphs.length; p++) {
			var pgph = paragraphs[p];
			pos += pgph.get('text').length;

			if(pos > minPos) {
				adDiv.inject(pgph, 'after');
				adDiv.removeClass('short_page');
				break;
			}
		}
	}


	// Add comment ajax
	var commentForm = document.id('comment_form');
	if(commentForm) {

		document.getElements('.edit_comment').each(function(link) {
			link.addEvent('click', clickEditComment);
		});

		document.getElements('.reply_to_comment').each(function(link) {
			link.addEvent('click', clickReplyToComment);
		});

		document.getElements('.delete_comment').each(function(link) {
			link.addEvent('click', clickDeleteComment);
		});

		commentForm.addEvent('submit', function(event) {
			event.stop();

			var commentField = commentForm.getElement('textarea[name=comment]');
			var postUrlName = commentForm.getElement('input[name=post]').value;
			var button = commentForm.getElement('input[type=submit]');

			button.setStyle('cursor','wait');

			var data = {
				action		: 'add',
				ajax		: 1,
				comment		: commentField.value,
				post		: postUrlName
			};

			new Request.JSON({
				url		: '/comment',
				onSuccess : function(json) {
					button.setStyle('cursor','pointer');


					if(json.errstr) {
						alert(json.errstr);

					} else {
						createCommentElement(commentField.value, json).inject(document.getElement('.view_post > ol.comments'));
						commentField.value = '';
						location.href = '#comment' + json.comment_id;
					}
				},

				onFailure : function() {
					button.setStyle('cursor','pointer');
					alert('Error adding comment');
				}

			}).post(data);
		});
	}


	// Add ajax to vote links on posts

	var voteBoxes = document.getElements('.vote_box');
	var urlNames = [];
	voteBoxesByUrl = [];

	voteBoxes.each(function(voteBox) {
		var voteLink = voteBox.getElement('.vote_link');
		var voteUrl = voteLink.href;
		var voteLink = new Element('div', voteLink.getProperties('text', 'class')).replaces(voteLink);
		var voteCount = voteBox.getElement('.num_votes');

		voteBox.setStyle('cursor', 'pointer');

		var urlName = voteUrl.substr(voteUrl.indexOf('/vote/') + '/vote/'.length);
		urlNames.push(urlName);
		voteBoxesByUrl[urlName] = voteBox;

		voteBox.addEvent('click', function(event) {
			if(! voteBox.alreadyVoted) {
				voteBox.setStyle('cursor','wait');

				if(! Cookie.read('gbsid')) {
					location.href = voteUrl;
					return;
				}

				new Request.JSON({
					url		: '/vote',
					onSuccess : function(responseJson) {
						if(responseJson.errstr) {
							if(responseJson.errstr == 'Login required') {
								location.href = voteUrl;
							} else {
								alert(responseJson.errstr);
							}

						} else {
							voteCount.set('text', responseJson.num_votes);
						}

						// Assume already voted because that's the cause of most errors
						voteBox.alreadyVoted = true;
						voteBox.setStyle('cursor', 'default');
					},

					onFailure : function() { location.href = voteUrl; }

				}).post({
					ajax		: 1,
					url_name	: urlName
				});
			}

			event.stop();
		});
	});


	// Update vote counts periodically - relies on ajax vote link section above
	var updateVotes = function() {
		new Request.JSON({
			url	: '/ajax-get-votes',
			noCache : true,
			onSuccess : function(responseJson) {
				responseJson.each(function(post) {
					var voteBox = voteBoxesByUrl[post.url_name];
					voteBox.getElement('.num_votes').set('text', post.num_votes);
				});
			}
		}).get({
			url_names	: urlNames
		});
	};

	if(voteBoxesByUrl.length) {
		updateVotes.call();
		updateVotes.periodical(30000);
	}


	// Use AJAX for flagging
	document.getElements('a.flag').each(function(flagLink) {
		flagLink.addEvent('click', function(event) {

			flagLink.setStyle('cursor','wait');

			var flagUrl = flagLink.href;
			var urlName = flagUrl.substr(flagUrl.indexOf('/flag/') + '/flag/'.length);

			new Request.JSON({
				url		: '/flag',
				onSuccess : function(responseJson) {
					flagLink.setStyle('cursor','pointer');
					if(responseJson.errstr) {
						if(responseJson.errstr == 'Login required') {
							location.href = flagUrl;
						} else {
							alert(responseJson.errstr);
						}
					} else {
						new Element('span', { text: 'You have flagged this post'}).replaces(flagLink);
					}
				},

				onFailure : function() { location.href = flagUrl; }

			}).post({
				ajax		: 1,
				url_name	: urlName
			});

			event.stop();
		});
	});


	// Add/remove from my bloggers (ajax)
	document.getElements('a.my_bloggers').each(function(a) {
		a.addEvent('click', function(event) {

			a.setStyle('cursor','wait');

			// a href="/my-bloggers?action=add;user_id=123"
			var action = (a.href.indexOf('action=add') != -1) ? 'add' : 'remove';
			var user_id = a.href.substr(a.href.indexOf('user_id=') + 'user_id='.length);

			new Request.JSON({
				url		: '/my-bloggers',
				onSuccess : function(json) {
					a.setStyle('cursor','pointer');
					if(json.errstr) {
						location.href = a.href;
						return;
					}

					if(action == 'add') {
						a.set('href', 'http://www.goodblogs.com/my-bloggers?action=remove;user_id='+user_id);
						a.set('text', (a.hasClass('follow_terminology')) ? '(Stop Following)' : 'Remove from My Bloggers');
					} else {
						a.set('href', 'http://www.goodblogs.com/my-bloggers?action=add;user_id='+user_id);
						a.set('text', (a.hasClass('follow_terminology')) ? '(Follow)' : 'Add to My Bloggers');
					}
				},

				onFailure : function() {
					a.setStyle('cursor','pointer');
					location.href = a.href;
				}

			}).post({
				ajax		: 1,
				action		: action,
				user_id		: user_id
			});

			event.stop();
		});
	});


	// Style input[type=file]
	var fileInputs = document.getElements('input[type=file]');
	fileInputs.each(function(fileInput) {
		var container = new Element('div', {
			'class'	: 'file_container'
		}).wraps(fileInput);

		var fakeDiv = new Element('div').inject(container);

		var fakeInput = new Element('input', {
			type	: 'text',
			'class'	: 'rounded_input'
		}).inject(fakeDiv);

		var fakeButton = new Element('input', {
			type	: 'button',
			value	: 'Browse...'
		}).inject(fakeDiv);


		fileInput.onchange = fileInput.onmouseout = function() {
			fakeInput.value = fileInput.value;
		};
	});
});


function clickEditComment(event) {
	event.stop();

	var commentContainer = event.target.getParent('.comment');

	if(commentContainer.isEditing) {
		return;
	} else {
		commentContainer.isEditing = true;
	}

	var comment_id = commentContainer.id.substr('commment'.length - 1);
	var commentBody = commentContainer.getElement('.comment_body');
	var origText = commentBody.get('text');

	commentBody.empty();
	var form = new Element('form').inject(commentBody);
	var textarea = new Element('textarea', { text : origText }).inject(form);
	var button = new Element('input', { type : 'submit', value : 'Save' }).inject(form);

	form.addEvent('submit', function(event) {
		event.stop();

		var newText = textarea.value;
		textarea.setStyle('cursor', 'wait');
		button.setStyle('cursor', 'wait');

		var data = {
			action		: 'edit_save',
			ajax		: 1,
			comment_id	: comment_id,
			comment		: newText
		};

		new Request.JSON({
			url		: '/comment',
			onFailure : function() {
				alert('Error saving comment.');
			},
			onSuccess : function(json) {

				if(json.errstr) {
					alert(json.errstr);

				} else {
					commentBody.empty();
					commentBody.set('text', newText);
					commentContainer.isEditing = false;
				}
			}
		}).post(data);
	});
}


function clickReplyToComment(event) {
	event.stop();

	var parentCommentContainer = event.target.getParent('.comment');
	if(parentCommentContainer.isReplying) {
		return;
	} else {
		parentCommentContainer.isReplying = true;
	}

	var replyLink = parentCommentContainer.getElement('.reply_to_comment');
	replyLink.setStyle('display', 'none');

	var parent_comment_id = parentCommentContainer.id.substr('commment'.length - 1);

	var form = new Element('form', { 'class' : 'reply_form' });
	var textarea = new Element('textarea').inject(form);
	var button = new Element('input', { type : 'submit', value : 'Reply' }).inject(form);

	var replyList = parentCommentContainer.getElement('ol.comments');
	if(replyList) {
		form.inject(replyList, 'before');
	} else {
		form.inject(parentCommentContainer, 'bottom');
	}

	form.addEvent('submit', function(event) {
		event.stop();

		var newText = textarea.value;
		textarea.setStyle('cursor', 'wait');
		button.setStyle('cursor', 'wait');

		var data = {
			action				: 'add',
			ajax				: 1,
			parent_comment_id	: parent_comment_id, // is a reply
			comment				: newText
		};

		new Request.JSON({
			url		: '/comment',
			onFailure : function() {
				alert('Error saving comment.');
			},
			onSuccess : function(json) {

				if(json.errstr) {
					alert(json.errstr);

				} else {
					form.destroy();
					parentCommentContainer.isReplying = false;
					replyLink.setStyle('display', 'inline');

					if(! replyList) {
						replyList = new Element('ol', { 'class' : 'comments' }).inject(parentCommentContainer);
					}

					createCommentElement(newText, json).inject(replyList);
				}
			}
		}).post(data);
	});
}


function clickDeleteComment(event) {
	event.stop();

	if(confirm('Really delete this comment?')) {
		var link = event.target;

		link.setStyle('cursor','wait');

		var commentContainer = link.getParent('.comment'); // id: comment123
		var comment_id = commentContainer.id.substr('commment'.length - 1);

		var data = {
			action		: 'delete',
			ajax		: 1,
			comment_id	: comment_id
		};

		new Request.JSON({
			url		: '/comment',
			onFailure : function() {
				alert('Error deleting comment.');
			},

			onSuccess : function(json) {
				if(json.errstr) {
					alert(json.errstr);

				} else {
					commentContainer.destroy();
				}
			}
		}).post(data);
	}
}


function getBloggerUrl(author_url_name, user_id) {
	return ((author_url_name)
		? 'http://'+author_url_name+'/'
		: 'http://www.goodblogs.com/bloggers/' + user_id);
}


function createCommentElement(commentText, json) {
	var bloggerUrl = getBloggerUrl(json.author_url_name, json.user_id);
	var commentElement = $e('li', {
		'class' : 'comment',
		'id'	: 'comment' + json.comment_id,
		'children' : [

			$e('div', {
				'class' : 'post-img',
				'children' : [

					$e('a', {
						'href' : bloggerUrl,
						'children' : [
							$e('img', {
								src		: 'http://www.goodblogs.com/user_thumbs/' + ((json.author_has_photo) ? json.user_id : 'default-small') + '.jpg',
								width	: 40,
								height	: 40,
								alt		: ''
							})
						]
					})
				]
			}),

			$e('div', {
				'class' : 'date',
				'text'  : json.posted_date_fmt
			}),

			$e('cite', {
				'class' : 'author_name',
				'children' : [
					$e('a', {
						'href' : bloggerUrl,
						'text' : json.author
					}),

					$e('span', {
						'class' : 'says',
						'text'  : ' says:'
					})
				]
			}),

			$e('div', {
				'class' : 'comment_body',
				'text'  : commentText
			}),

			$e('div', {
				'class'	: 'comment_functions',
				'children' : [
					$e('a', {
						'href'	: '/comment?action=edit&comment_id=' + json.comment_id,
						'class' : 'edit_comment',
						'text'  : 'Edit',
						'events' : {
							'click' : clickEditComment
						}
					}),

					$e('span', { 'text' : ' or ' }),

					$e('a', {
						'href'  : '/comment?action=delete&comment_id=' + json.comment_id,
						'class' : 'delete_comment',
						'text'  : 'delete',
						'events' : {
							'click' : clickDeleteComment
						}
					}),

					$e('span', { 'text' : ' this comment' })
				]
			}),

			$e('div', {
				'class'	: 'comment_functions',
				'children' : [
					$e('a', {
						'href'	: '/comment?action=reply&comment_id=' + json.comment_id,
						'class' : 'reply_to_comment',
						'text'  : 'Reply',
						'events' : {
							'click' : clickReplyToComment
						}
					}),
				]
			})
		]
	});

	return commentElement;
}


// @depends mootools-1.2.4-core.js
//
// $e(): Use the mootools new element function to chain up element creation in a nice way
//
// $e('a', {
// 'href': './home',
// 'children': [
// $e('img', {'src': './logo.png', 'title': 'popacular'}),
// $e('span', 'popacular.com/home')
// ]
// });
//
// Created: 2010-05-21
// License: MIT-Style License
// Nathan Reed (c) 2010
//
function $e(tag, props) {
   tag = tag || 'div';

   if(!$defined(props)) {
      return new Element(tag);
   }

   // normalize the properties element for the
   // mootools element constructor
   if($type(props) == 'string') {
      props = {'text': props};
   } else if($type(props) == 'element') {
      props = {'children': props};
   }

   // remove the children property from the array, we don't want it in there.
   // because when we pass these properties to the mootools element function it
   // might get confused.
   var children = props.children;
   props.children = null;

   var new_element = new Element(tag, props);

   if($defined(children)) {

      if($type(children) == 'element') {
         // if they have just passed through one child, then
         // normalize it by turning it into an array with one element.
         children = [children];
      }

      // add the children to the new element one by one
      children.each(function(item) {
         new_element.grab(item);
      });

   }

   return new_element
}

