$(document).ready(function()
{
	var posting = false;
	
	$('#post_editor .tool_bold').click(function(){BBCodeClick('b');});
	$('#post_editor .tool_italic').click(function(){BBCodeClick('i');});
	$('#post_editor .tool_underline').click(function(){BBCodeClick('u');});
	$('#post_editor .tool_quote').click(function(){BBCodeClick('quote');});
	$('#post_editor .tool_link').click(function(){BBCodeClick('url');});
	$('#post_editor .tool_media').click(function(){BBCodeClick('media');});
	
	//Create post
	$('#create_post').click(function()
	{
		var newPost = $('#post_editor');
		
		if(!posting)
		{
			var placeholderSupported = "placeholder" in $('#post_editor .title')[0];
			posting = true;
			
			if(!placeholderSupported)
			{
				$('#post_editor .title').val($('#post_editor .title').attr('placeholder')).focus(function(){selectText(this);});
				$('#post_content').val($('#post_content').attr('placeholder')).focus(function(){selectText(this);});
				
				function selectText(elem)
				{
					if($(elem).val() == $(elem).attr('placeholder'))
						elem.select();
				}
			}
			else
			{
				$('#post_editor .title').val('');
				$('#post_content').val('');
			}
			
			setPostHotspotOrFeatured('none');
			$('#post_editor select[name=category]').val(1);
			$('#post_editor input[name=id]').val('');
			$('#post_editor input[name=hotspot_type]').val('0');
			newPost.prependTo('#news_posts').hide().slideDown();
			//$('#post_editor .title').focus();
		}
	});
	
	//Close editor
	$('#post_views .close').click(function()
	{
		if($('#post_editor input[name=id]').val() > 0)
		{
			$('#post_editor').slideUp(function()
			{
				$('.post[data-post-id="' + $('#post_editor input[name=id]').val()  + '"]').slideDown();
			});
		}
		else
			$('#post_editor').slideUp();
		
		posting = false;
	});
	
	//Submit post
	$('#post_editor .submit').click(function()
	{
		var formData = $('#post_editor').serialize();
		
		$.post('posting.php?mode=submit', formData, function(data)
		{
			var response;
			
			try
			{
				response = JSON.parse(data);
			}
			catch(ex)
			{
				showMessage('An unparsable message was returned', 'Error submitting post', data, ['OK']);
				return;
			}
			
			if(response.result == 'success')
			{
				if(!$('#featured_chk').attr('checked'))
					window.location = "index.php";
				else
					window.location.reload();
			}
			else if(response.result == 'denied')
				showMessage(response.data, 'Error submitting post', '', ['OK']);
			else
				showMessage('There was an error while attempting to edit the post.  Please make sure all information was entered.', 'Error submitting post', response.data, ['OK']);
		});
		
		return false; //Prevent form submission
	});
	
	//Edit post
	$('.admin_tools .edit').click(function()
	{
		if(posting)
			return;
		
		var post = $(this).parents('.post');
		
		posting = true;
		
		post.slideUp(function()
		{
			var editor = $('#post_editor');
			var hotspotType = $(this).attr('data-hotspot-type');
			var category = $(this).attr('data-category-id');
			var featured = $(this).attr('data-featured');
			
			if(parseInt(featured))
				setPostHotspotOrFeatured('featured', true);
			else
				setPostHotspotOrFeatured('hotspot', hotspotType);
				
			$('#post_editor select[name=category]').val(category);
			$('#post_editor .title').val($(this).find('.title').text());
			$('#post_content').val($(this).find('.content').attr('data-original'));
			$('#post_editor input[name=id]').val($(this).attr('data-post-id'));
			editor.insertBefore(post).hide().slideDown();
		});
	});
	
	//Delete post
	$('.post > div > .admin_tools .delete').click(function()
	{
		var post = $(this).parents('.post')
		var postId = post.attr('data-post-id');
		
		showMessage('Are you sure you want to delete this post?', 'Delete Post', '', ['Delete', 'Cancel'], function(result, messageBox)
		{
			if(result == 'Delete')
			{
				showMessageSpinner();
				
				$.post('posting.php?mode=delete', { 'p' : postId }, function(data, textStatus)
				{
					var response;
					
					try
					{
						response = JSON.parse(data);
					}
					catch(ex)
					{
						console.err('Error parsing result: ', ex);
						//showMessageBox(data, 'Error deleting post', '', ['OK']);
						return;
					}
					
					if(response.result == 'success')
					{
						closeMessageBox();
						post.css('min-height', '0').slideUp(function(){ $(this).remove(); });
						
						if(!$('#featured_chk').attr('checked'))
							window.location = "index.php";
					}
					else
						console.err('Error deleting post: ', response);
				});
			}
			else
				return true;
		});
	});
	
	//Toogles featured image dropdown visiblity
	$('#featured_chk').change(function()
	{
		setPostHotspotOrFeatured('featured', this.checked);
	});
	
	$('#post_views .featured').click(function()
	{
		$('#featured_chk').prop('checked', !$('#featured_chk').prop('checked')).trigger('change');
	});
	
	//Shows hotspot type selector
	$('#post_editor .btn_hotspot').click(function()
	{
		$('#hotspot_selector').css('visibility', 'visible').hide().fadeIn();
	});
	
	//Changes hotspot type
	$('#hotspot_selector .box > div').click(function()
	{
		var hotspotType = this.getAttribute('data-type');
		
		setPostHotspotOrFeatured('hotspot', hotspotType);
		$('#hotspot_selector').fadeOut();
	});
	
	function BBCodeClick(code)
	{
		var box = $('#post_content')
		var open = '[' + code + ']';
		var close = '[/' + code + ']';
		
		if(box.get(0).selectionStart - box.get(0).selectionEnd == 0)
			box.val(box.val() + open + close);
		else
		{
			var text = box.val();
			var preSelection = text.substring(0, box.get(0).selectionStart);
			var selection = text.substring(box.get(0).selectionStart, box.get(0).selectionEnd);
			var postSelection = text.substring(box.get(0).selectionEnd);
			
			box.val(preSelection + open + selection + close + postSelection);
		}
	}
	
	function setPostHotspotOrFeatured(type, value)
	{
		if(type == 'featured' && value == true)
		{
			changeHotspotType(0);
			$('#featured_image_selection').show();
			$('#featured_chk').prop('checked', true);
			$('#post_views .featured').addClass('selected');
			$('#btn_hotspot').removeClass('selected');
		}
		else if(type == 'hotspot' && value != 0)
		{
			$('#featured_chk').prop('checked', false);
			$('#featured_image_selection').hide();
			$('#post_views .featured').removeClass('selected');
			$('#btn_hotspot').addClass('selected');
			changeHotspotType(value);
		}
		else
		{
			changeHotspotType(0);
			$('#featured_chk').prop('checked', false);
			$('#featured_image_selection').hide();
			$('#post_views .featured').removeClass('selected');
			$('#btn_hotspot').removeClass('selected');
		}
	}
	
	function changeHotspotType(hotspotType)
	{
		hotspotType = parseInt(hotspotType, 10);
		
		switch(hotspotType)
		{
			case 0:
				$('#hotspot').hide();
				$('#post_content').css('width', '100%');
				break;
			case 1:
				$('#hotspot').removeClass('top').insertBefore('#post_content').show();
				$('#post_content').css('width', '');
				break;
			case 2:
				$('#hotspot').addClass('top').insertBefore('#post_content').show();
				$('#post_content').css('width', '100%');
				break;
			case 3:
				$('#hotspot').removeClass('top').insertAfter('#post_content').show();
				$('#post_content').css('width', '');
				break;
		}
		
		$('#hotspot_image_selection').children().remove();
		
		if(hotspotType > 0)
		{
			for(var i = 0; i < hotspotImages.length; i++)
			{
				if(hotspotImages[i].type == hotspotType)
					$('#hotspot_image_selection').append('<option value="' + hotspotImages[i].name + '">' + hotspotImages[i].name + '</option>');
			}
			
			$('#hotspot_image_selection').show();
		}
		else
			$('#hotspot_image_selection').hide();
		
		$('input[name=hotspot_type]').val(hotspotType);
	}
});
