$(document).ready(function(){
	var profilePhotoURL = rootURL + '/images/vinhkhoa.jpg';

	// Round corners
	$('.corner').corner();
	$('#content').corner('bl');
	$('#contactFormContainer').corner('right');
	$('.treegrad_price').corner('tr bl');
	$('.treegrad_suburb').corner('2px');
	$('.commentBtn').corner('3px');
	
	// Preload images
	var preloadImage = function(imgURL){
		$('<img />').attr('src', imgURL);
	};
	
	preloadImage(profilePhotoURL);
	preloadImage(rootURL + '/images/externalLink_hover.gif');	
	preloadImage(rootURL + '/images/externalLink_visited.gif');	
	preloadImage(rootURL + '/images/externalLink_hover.gif');	

	// Start here
	$('.startHere').focus();
	
	// CKEditor
	/*$('#articleform #articleContent').ckeditor({height: 500});
	$('#articleform #excerpt').ckeditor({height: 200});*/
	
	$('#editExcerpt').click(function(e){
		e.preventDefault();
		$(this).parent().hide().next().show();
	})

	// Open new window links
	$('.newWindow').click(function(e){
		e.preventDefault();
		window.open($(this).attr('href'), $(this).attr('title'), 'width=800,height=600,scrollbars=yes,resizable=yes');
	})
	
	//Put AJAX submit to the contact form
	$postResult = $('#contactResult');
	var postOptions = {
		dataType: 'xml',
		data: {format: 'xml' },
		beforeSubmit: function(data, $frm, options){
			$postResult.attr('class', 'waiting').text('Sending your message...');
		},
		success: function(response, status){
			var error = $(response).find('error').text();
			var message = $(response).find('message').text();
			
			// Any error?
			if (error != '')
			{
				$postResult.attr('class', 'error').html(error);
			}
			else
			{
				$postResult.attr('class', 'message').html(message).delay(2000).animate({opacity: 0}, 500, function(){
					$postResult.attr('class', '').html('').css('opacity', 1);
				});
				$('#contactForm input[type!=hidden],#contactForm textarea').val('');
			}
		}
	};	
	$('#contactForm').append('<input type="hidden" name="isAjax" id="isAjax" value="1" />');
	$('#contactForm').ajaxForm(postOptions);

	// Syntax highlight
	dp.SyntaxHighlighter.HighlightAll('code', true, true, false, 1, false);
	
	$('a.localscroll').click(function(e){
		e.preventDefault();
		$.scrollTo($(this).attr('href'), 500, {easing:'easeOutCubic'});
	})
	
	// Show where the business logo will appear on the sidebar
	$('a#showSidebarSpot').click(function(e){
		e.preventDefault();
		$('#businesslogo_container').remove();
		var $lastSideBox = $('#sidebar > div:last');
		$.scrollTo($(this).attr('rel'), 500, 
			{
				easing:'easeOutCubic', 
				onAfter: function(){
					$lastSideBox.after('<div id="businesslogo_container"><div id="businesslogo"><p>Your logo will be displayed here once you donate an iPad.</p><p>This appears on every page of the blog.</p></div></div>').next().fadeIn(2000);
				}
			}
		);
	})

	// Fancy article content images
	$(".fancy").fancybox({ 
		'overlayShow': true, 
		'overlayOpacity': .8,
		'overlayColor': '#000',
		'padding': 8
	});
	
	// Reply comment
	$('.commentReply a').click(function(){
		var headingname = $.trim($(this).parents('.commentContent').find('.headingname').text());
		var commentId = $.trim($(this).parents('li').attr('id').replace('comment_', ''));
		$('#replyToContainer').show();
		$('#replyToName').text(headingname).attr('href', '#comment_' + commentId);
		$('#replyToId').val(commentId);
		$('#comment_content').focus();
	})
	$('#removeReplyTo').click(function(e){
		e.preventDefault();
		$('#replyToContainer').slideUp('fast');
		$('#replyToId').val('');
	})
	
	$('#submitComment').attr('value', 'Submit Comment').attr('disabled', '').click(function(e){
		$(this).attr('value', 'Submitting Comment...').attr('disabled', 'disabled').parents('form').append('<input type="hidden" name="submitComment" value="1" />').submit();
	});
	
	// Answer a comment
	$('.answerLink').click(function(e){
		e.preventDefault();
		
		$.prompt('Did you answer all questions in this comment? <input type="hidden" name="linkHREF" value="' + $(this).attr('href') + '" />' ,{
			buttons: { Yes: 'Yes', No: 'Not yet' },
			callback: function(value,m,f){	
				if(value == 'Yes')
				{
					$.get(f.linkHREF, function(data){
						commentId = $(data).find('commentId').text();
						error = $(data).find('error').text();
						$li = $('#comment_' + commentId);
						
						if (error == '')
						{
							$li.removeClass('unanswered').find('.answerLink,.rejectLink').remove().end();
						}
						else
						{
							alert('Cannot mark this comment as answered. ERROR: ' + error);
						}
					})
				}
			}
		});	
	})
	
	// Check all items on the list
	$('.selectAll').click(function(){
		$(this).parents('form').find(':input[type=checkbox]').attr('checked', $(this).attr('checked'));
	})
	
	// Delete podcast
	$('.deletePodcast').click(function(e){
		e.preventDefault();
		$this = $(this);
		$tr = $this.parents('tr');
		
		if (confirm('Delete podcast "' + $tr.find('.podcast_name a').text() + '"?'))
		{
			$.post(baseURL + '/admin/podcast/delete', {podcastId: $this.attr('id').replace('deletePodcast_', '')}, function(data){
				var error = $(data).find('error').text();
				
				if (error == '')
				{
					$this.parents('tr').fadeOut(function(){
						$(this).remove();
						alert('Podcast deleted');
					});
				}
				else
				{
					alert('ERROR: ' + error);
				}
			})
		}
	})
	
	// Toggle podcast row in readonly mode
	$.fn.toggleReadyonlyMode = function(name, directory){
		// Get the podcast name
		if (typeof(name) != 'undefined')
		{
			var _name = name;
		}
		else
		{
			var _name = $(this).find('.podcast_name a').text();
		}
	
		// Get the podcast directory
		if (typeof(directory) != 'undefined')
		{
			var _directory = directory;
		}
		else
		{
			var _directory = $(this).find('.podcast_directory span').text();
		}
	
		$(this)
			.find('.podcast_name')
				.find('input').remove().end()
				.find('span').show().find('a').text(_name).end().end()
				.end()
			.find('.podcast_directory')
				.find('input').remove().end()
				.find('span').show().text(_directory).end()
				.end()
			.find('.cancelEditPodcast,.savePodcast').hide().end()
			.find('.editPodcast,.deletePodcast').show();
	}	
	
	// Update podcast
	$('.editPodcast').click(function(e){
		e.preventDefault();
		$this = $(this);
		$tr = $this.parents('tr');
		
		// Replace podcast name and directory with textboxes
		var podcast_name = $tr.find('.podcast_name a').text();
		var podcast_directory = $tr.find('.podcast_directory span').text();
		$tr.find('.podcast_name').find('input').remove().end()
		   .find('span').hide().end()
		   .append('<input type="text" name="name" value="' + podcast_name + '" />').find('input').focus();
		$tr.find('.podcast_directory').find('input').remove().end()
		   .find('span').hide().end()
		   .append('<input type="text" name="directory" value="' + podcast_directory + '" />');

		// Show/hide action links
		$tr.find('.editPodcast,.deletePodcast').hide().end()
		   .find('.cancelEditPodcast,.savePodcast').show();
	})
	
	// Cancel editing podcast
	$('.cancelEditPodcast').click(function(e){
		e.preventDefault();
		$(this).parents('tr').toggleReadyonlyMode();
	})
	
	// Save editing podcast
	$('.savePodcast').click(function(e){
		e.preventDefault();
		var $this = $(this);
		var $tr = $this.parents('tr');
		var $podcast_name = $tr.find('.podcast_name');
		var $podcast_directory = $tr.find('.podcast_directory');
		var newName = $podcast_name.find('input').val();
		var newDirectory = $podcast_directory.find('input').val();
		var podcastId = $this.attr('id').replace('savePodcast_', '');
		
		$.post(baseURL + '/admin/podcast/update',
				{
					podcastId: podcastId,
					name: newName,
					directory: newDirectory
				},
				function(data){
					var error = $(data).find('error').text();
					
					if (error == '')
					{
						$tr.toggleReadyonlyMode(newName, newDirectory);
						alert('Podcast updated');
					}
					else
					{
						alert('ERROR: ' + error);
					}
				}
		)		
	})
	

})

