$(document).ready(function()
{
	$('#photo-comment-form').addClass('hide');
	
	$('#toggle-form').bind('click',function()
	{		
		$('#photo-comment-form').toggleClass('hide');
		
		$(this).toggleClass('closed');
		
		try{
			$('#comment_name').get(0).focus();
		}
		catch(e){}
		
		return false;
	});
	
	$('#photo-comment-form').bind('submit',function(event)
	{
		var the_form = this;

		if(!validate_form({'data': {'the_form': the_form}}))
			return false;
	
		$('.text',the_form).addClass('disabled');
		$('#comment_save').after('<span id="loader"><img src="/images/layout/ajax_loader_small.gif" alt="Loading..."><small>Saving...</small></span>');
		$('#comment_save').attr('disabled','disabled');

		//First we get the comment key to authorize the post
		var key = Math.floor(Math.random() * 1000000);
		
		$.get('/services/get-comment-key?key=' + key,function(key_response)
		{
			$('#comment_key').val($('key',key_response).text());
			
			serialized_form = $('input[type=text],input[type=hidden],textarea',the_form).serialize();
			
			//Submit the comment
			$.post('/services/post-comment',serialized_form,function(comment_response)
			{
				//Check for errors
				if($('errors',comment_response).text().length <= 0)
				{
					//Show the new comment
					$('#no-comments').remove();
					$('#comments li.last').removeClass('last');
					$('#comments').append($('comment',comment_response).text());
					$('#comments li.last').Highlight(4000, '#f8f982');
					
					var end_of_comments_position = $('#end-of-comments').get(0).offsetTop;
					window.scrollTo(0,end_of_comments_position);
					
					//Set the delete trigger
					$('#comments a.delete-comment').bind('click',function(){
						if(!window.confirm('Are you sure you wish to delete this comment?'))
							return false;
						
						$.post(this.href,{comment_key: $('#comment_key').val()},function(delete_response){
							$('#comments li.last').fadeOut('slow');
						});
						
						return false;
					});
					
					//Reset the comment form
					$(the_form).addClass('hide');
					$('#toggle-form').addClass('closed');
					$('#comment_comment').val('');
				}
				else
					alert($('errors',comment_response).text());
					
				$('.text',the_form).removeClass('disabled');
				$('#loader').remove();
				$('#comment_save').removeAttr('disabled');
			});
		});
		
		return false;
	});
	
	//sIFR prettify headings
	$('h1').sifr( { strSWF: './fonts/century.swf', strColor: '#010000', strWmode: 'transparent' } );	
});