$(document).ready(function(){

// VOTE STUDY RESOURCE

	// Creater rater
	function rating(response, up, down) {

		// Initialize output
		var output;

		// Switch case on response (1-6)
		switch (response) {

			case '1':
				up++;
				break;
			case '2':
				down++;
				break;
			case '3':
				up--;
				break;
			case '4':
				down--;
				break;
			case '5':
				up++;
				down--;
				break;
			case '6':
				up--;
				down++;
				break;
		}

		// If both have positive votes
		if ((up > 0) && (down > 0)) {

			// Determine class of rater by analyzing the ratio

				var ratio = up / down;

				if (ratio >= 5) {

					var rater_class = 'a7';
				}
				else if (ratio >= 7/3) {

					var rater_class = 'a6';
				}
				else if (ratio >= 4/3) {

					var rater_class = 'a5';
				}
				else if (ratio > 4/5) {

					 var rater_class = 'a4';
				}
				else if (ratio > 7/15) {

					var rater_class = 'a3';
				}
				else {

					var rater_class = 'a2';
				}

			// Output
			output = '<a class="rating ' + rater_class + '" href="#"><span>' + up + '</span><span></span><span>' + down + '</span></a>';

		}
		else if ((up > 0) && (down == 0)) {

			output = '<a class="rating a8" href="#"><span>' + up + '</span><span></span><span>0</span></a>';

		}
		else if ((up ==0) && (down > 0)) {

			output = '<a class="rating a0" href="#"><span>0</span><span></span><span>' + down + '</span></a>';

		}
		// Else both are 0
		else {

			// No output
			output = '';
		}

		// Return output
		return output;
	}

	// On click
	$('#study ul.actions li a.thumbs-up, #study ul.actions li a.thumbs-down').click(function(e) {

		e.preventDefault(); // don't follow the link
		var a = $(this);

		// Grab link
		var link = $(this).attr('href');
		
		// Ajax request
		$.get(link, function(data) {
		
			// Switch case on response data (0-6)
			switch (data) {

				case '0':
					alert('An error occurred while processing the request.');
					break;
				case '1':
					a.addClass('active');
					a.find('span').text('Undo Thumbs Up');
					break;
				case '2':
					a.addClass('active');
					a.find('span').text('Undo Thumbs Down');
					break;
				case '3':
					a.removeClass('active');
					a.find('span').text('Thumbs Up');
					break;
				case '4':
					a.removeClass('active');
					a.find('span').text('Thumbs Down');
					break;
				case '5':
					a.addClass('active');
					a.parents('ul.actions').find('a.thumbs-down').removeClass('active').find('span').text('Thumbs Down');
					a.find('span').text('Undo Thumbs Up');
					break;
				case '6':
					a.addClass('active');
					a.parents('ul.actions').find('a.thumbs-up').removeClass('active').find('span').text('Thumbs Up');
					a.find('span').text('Undo Thumbs Down');
					break;
			}

			// Extract current vote count 
			if (a.parents('div.active').find('a.rating').length) {

				var up = parseInt(a.parents('div.active').find('a.rating span:first').text());
				var down = parseInt(a.parents('div.active').find('a.rating span:last').text());

				// Remove element
				a.parents('div.active').find('a.rating').remove();

			}
			// No current vote exists
			else {

				var up = 0;
				var down = 0;
			}

			// Update current rating
			var output = rating(data, up, down);
			a.parents('div.active').find('h2').after(output);

		});
	});

// VIEW ALL COMMENTS

	// On click
	$('#study .comments p.view-all a').click(function(e) {

		e.preventDefault(); // don't follow the link
		var a = $(this);

		// Create loading state
		$(this).addClass('loading');

		// Grab link
		var link = $(this).attr('href');
		
		// Ajax request
		$.get(link, function(data) {

			// If response is not 0, comments pulled successfully
			if (data != '0') {

				// Cache comments parents
				var parent = a.parents('.comments');

				// Add class to comments
				parent.addClass('all');

				// Delete view-all link
				parent.find('p.view-all').remove();

				// Post comments
				parent.prepend(data);

				// Add vote event handler
				parent.find('a.thumbs-up, a.thumbs-down').click(function(e) {

					voteComment(e, $(this));
				});

				// Add action popup event handler
				parent.find('a.thumbs-up, a.thumbs-down').mouseover(function(e) {

					// Grab text description
						// If picture
						if ($(this).hasClass('pic')) {

							var text = $(this).find('img').attr('alt');
						}
						else {
							var text = $(this).find('span').text();
						}

					// If a popup already exists, remove it
					$('#popup').remove();

					// Create popup (hidden)
					$('#footer').after('<div id="popup" class="action"><div class="main"><p>' + text + '</p></div><div class="arrow"></div></div>');

					// Calculate position
					var offset = $(this).offset();
					var width = $(this).outerWidth();
					var popup_width = $('#popup').width();
					var left = offset.left - popup_width / 2 + width / 2;
					var top = offset.top - $('#popup').height() - 10;
					var arrow = popup_width / 2 - 7;

					// Update position and set to visible
					$('#popup').css({
						'left' : left,
						'top' : top,
						'visibility' : 'visible'
					});

					// Update arrow position
					$('#popup .arrow').css({
						'left' : arrow + 'px'
					});

				});
				parent.find('a.thumbs-up, a.thumbs-down').mouseout(function(e) {
			 
					$('#popup').remove();
				});

				// Add delete event handler
				parent.find('.close a.close').click(function(e) {

					e.stopImmediatePropagation(); // stop event bubbling
					deleteComment(e, $(this));
				});

			}
			// Else error
			else {

				alert('An unexpected error occurred');
			}
		});
	});

// POST COMMENT

	// On click
	$('#study .comments p.respond a').click(function(e) {

		e.preventDefault(); // don't follow link

		// Cache comments
		comments = $(this).parents('.comments');

		// If form tag already exists,
		if (comments.find('form').length) {

			// Hide post comment link and show respond div
			comments.find('div.respond').removeClass('hidden');
			comments.find('p.respond').addClass('hidden');

			// Gain focus to form
			comments.find('textarea').focus();
		}
		// Else form tag does not exist already, create it
		else {

			// Add form contents
			comments.find('p.respond').after('<div class="respond"><form method="" action=""><fieldset><a class="pic" href="#"><img src="images/template/filler.png" width="60" height="45" alt="" /></a><textarea></textarea><input type="submit" name="submit" value="Post" /></fieldset><form><div class="close"><a class="close" href="#"><span>Hide</span></a></div></div>');

			// Hide post comment link
			comments.find('p.respond').addClass('hidden');

			// Cache form tag
			var form = comments.find('form');

			// Create hide button event
			form.find('a.close').click(function(e) {

				e.preventDefault(); // don't follow link

				// Hide respond div and show post comment link
				comments.find('div.respond').addClass('hidden');
				comments.find('p.respond').removeClass('hidden');
			});

			// Focus on textarea
			form.find('textarea').focus();

			// Form submission
			form.submit(function(e) {

				e.preventDefault(); // prevent normal form submission

				// Disable submit button
				form.find('.respond input[type=submit]').attr('disabled', 'disabled');

				// Process comment
				process_comment(form);

				// Return false
				return false;
			});
		}


	});

	// Process comment
	function process_comment(e) {

		// Cache comment and song_id
		var text = e.find('textarea').val();
		var resource_id = e.parents('.comments').find('p.respond a').attr('rel');

		// Ajax request
		$.ajax({
			type: 'POST',
			url: '/lib/ajax/study/process_comment.php',
			data: { resource_id: resource_id, comment: text},
			success: function(data) {

				// If no error occurred
				if (data != '0') {

					// Normal response = comment_id.user_name
					var comment_id = data.slice(0, data.indexOf('.'));
					var user_name = data.slice(data.indexOf('.') + 1);

					// Cache comments
					var comments = e.parents('.comments');

					// Output
					var output = '<div class="comment"><a class="pic" href="/user/profile.php"><img src="images/template/filler.png" width="60" height="45" alt="" /></a><p><strong><a rel="popup" href="/user/profile.php">' + user_name + '</a></strong><span>a moment ago</span></p><p>' + text + '</p><ul><li><a class="action thumbs-up" href="/lib/ajax/study/comment_vote.php?comment_id=' + comment_id + '&type=1"><span>Thumbs Up</span></a></li><li><a class="action thumbs-down" href="/lib/ajax/study/comment_vote.php?comment_id=' + comment_id + '&type=0"><span>Thumbs Down</span></a></li></ul><div class="close"><a class="close" data-comment_id="' + comment_id + '" href="#"><span>Delete</span></a></div></div>';

					// Add comment
					comments.find('p.respond').before(output);

					// Add voting event handler
					comments.find('ul li a.thumbs-up, ul li a.thumbs-down').click(function(e) {

						voteComment(e, $(this));
					});

					// Add action popup event handler
					comments.find('ul li a.thumbs-up, ul li a.thumbs-down').mouseover(function(e) {

						// Grab text description
							// If picture
							if ($(this).hasClass('pic')) {

								var text = $(this).find('img').attr('alt');
							}
							else {
								var text = $(this).find('span').text();
							}

						// If a popup already exists, remove it
						$('#popup').remove();

						// Create popup (hidden)
						$('#footer').after('<div id="popup" class="action"><div class="main"><p>' + text + '</p></div><div class="arrow"></div></div>');

						// Calculate position
						var offset = $(this).offset();
						var width = $(this).outerWidth();
						var popup_width = $('#popup').width();
						var left = offset.left - popup_width / 2 + width / 2;
						var top = offset.top - $('#popup').height() - 10;
						var arrow = popup_width / 2 - 7;

						// Update position and set to visible
						$('#popup').css({
							'left' : left,
							'top' : top,
							'visibility' : 'visible'
						});

						// Update arrow position
						$('#popup .arrow').css({
							'left' : arrow + 'px'
						});

					});
					comments.find('ul li a.thumbs-up, ul li a.thumbs-down').mouseout(function(e) {

						$('#popup').remove();
					});

					// Add delete event handler
					comments.find('.close a.close').click(function(e) {

						e.stopImmediatePropagation(); // stop event bubbling
						deleteComment(e, $(this));
					});

					// Hide respond div and show post comment link
					comments.find('div.respond').addClass('hidden');
					comments.find('p.respond').removeClass('hidden');
					
				}
				// Else an error occurred
				else {

					alert('An unexpected error occurred.');
				}
			}
		});

		// Clear text in textarea
		 e.find('textarea').val('');
	}

// DELETE COMMENTS

	// On click
	$('#study .comments .close a.close').click(function(e) {

		deleteComment(e, $(this));
	});

	// Delete comment function
	function deleteComment(e, a) {

		e.preventDefault(); // don't follow link

		var resource_id = a.parents('.comments').find('p.respond a').attr('rel');
		var comment_id = a.attr('data-comment_id');

		// Ajax request
		$.ajax({
			type: 'POST',
			url: '/lib/ajax/study/delete_comment.php',
			data: { resource_id: resource_id, comment_id: comment_id},
			success: function(data) {

				// If no error occurred
				if (data != '0') {

					// Delete popup
					$('#popup').remove();

					// Delete comment from the dom
					a.parents('div.comment').remove();
				}
				// Else an error occurred
				else {

					alert('An unexpected error occurred.');
				}
			}
		});
	}

// VOTE COMMENT (up/down)

	// On click
	$('#study .comment ul li a.thumbs-up, #study .comment ul li a.thumbs-down').click(function(e) {

		voteComment(e, $(this));
	});

	// Vote Comment function
	function voteComment(e, a) {

		e.preventDefault(); // don't follow the link
		e.stopImmediatePropagation(); // stop event bubbling

		// Grab link
		var link = a.attr('href');
		
		// Ajax request
		$.get(link, function(data) {
		
			// Switch case on response data (0-6)
			switch (data) {

				case '0':
					alert('An error occurred while processing the request.');
					break;
				case '1':
					a.addClass('active');
					a.find('span').text('Undo Thumbs Up');
					break;
				case '2':
					a.addClass('active');
					a.find('span').text('Undo Thumbs Down');
					break;
				case '3':
					a.removeClass('active');
					a.find('span').text('Thumbs Up');
					break;
				case '4':
					a.removeClass('active');
					a.find('span').text('Thumbs Down');
					break;
				case '5':
					a.addClass('active');
					a.parents('ul').find('a.thumbs-down').removeClass('active').find('span').text('Thumbs Down');
					a.find('span').text('Undo Thumbs Up');
					break;
				case '6':
					a.addClass('active');
					a.parents('ul').find('a.thumbs-up').removeClass('active').find('span').text('Thumbs Up');
					a.find('span').text('Undo Thumbs Down');
					break;
			}

			// Extract current vote count 
			if (a.parents('.comment:first').find('a.rating').length) {

				var up = parseInt(a.parents('.comment:first').find('a.rating span:first').text());
				var down = parseInt(a.parents('.comment:first').find('a.rating span:last').text());

				// Remove element
				a.parents('.comment:first').find('a.rating').remove();

			}
			// No current vote exists
			else {

				var up = 0;
				var down = 0;
			}

			// Update rating
			var output = rating(data, up, down);
			a.parents('.comment:first').find('a.pic').before(output);

		});
	}

// HIDE/SHOW ALL COMMENTS

	// On click
	$('#study ul.actions li a.comment').click(function(e) {
		
		// If user logged in
		if ($(this).parents('.contents').find('.comments').length) {

			e.preventDefault(); // don't follow link

			// Cache comments
			var comments = $(this).parents('.contents').find('.comments');

			// If 0 comments
			if (comments.hasClass('none')) {

				// If form was already created
				if (comments.find('form').length) {


					// If form hidden, show it
					if (comments.hasClass('hidden')) {

						$(this).find('span').text('Hide Comments');
						$('#popup p').text('Hide Comments');
						comments.removeClass('hidden');
						comments.find('div.respond').removeClass('hidden');
						comments.find('p.respond').addClass('hidden');
						comments.find('textarea').focus();
						
					}
					// Else form visible, hide it
					else {

						$(this).find('span').text('Add Comment');
						$('#popup p').text('Add Comment');
						comments.addClass('hidden');
						comments.find('div.respond').removeClass('hidden');
						comments.find('p.respond').addClass('hidden');
					}
				}
				// Else form not created yet
				else {

					// Add form contents
					comments.find('p.respond').after('<div class="respond"><form method="" action=""><fieldset><a class="pic" href="#"><img src="images/template/filler.png" width="60" height="45" alt="" /></a><textarea></textarea><input type="submit" name="submit" value="Post" /></fieldset><form><div class="close"><a class="close" href="#"><span>Hide</span></a></div></div>');

					// Hide post comment link
					comments.find('p.respond').addClass('hidden');

					// Cache form tag
					var form = comments.find('form');

					// Create hide button event
					form.find('a.close').click(function(e) {

						e.preventDefault(); // don't follow link

						// Hide respond div and show post comment link
						comments.find('div.respond').addClass('hidden');
						comments.find('p.respond').removeClass('hidden');
					});

					// Form submission
					form.submit(function(e) {

						e.preventDefault(); // prevent normal form submission

						// Disable submit button
						form.find('.respond input[type=submit]').attr('disabled', 'disabled');

						// Process comment
						process_comment(form);

						// Return false
						return false;
					});

					// Remove hidden class
					comments.removeClass('hidden');

					// Change popup text
					$(this).find('span').text('Hide Comments');
					$('#popup p').text('Hide Comments');

					// Focus on textarea
					comments.find('textarea').focus();
				}
			}
			// Else 1 or more comments exist
			else {

				// If comments hidden, show comments
				if (comments.hasClass('hidden')) {

					comments.removeClass('hidden');
					$(this).find('span').text('Hide Comments');
					$('#popup p').text('Hide Comments');
				}
				// Else comments visible, hide comments
				else {

					comments.addClass('hidden');
					$(this).find('span').text('Show Comments');
					$('#popup p').text('Show Comments');
				}
			}
		}
		// Else the user will follow the link to login
	});

});
