
var Comment = {
	open: [],
	loaded: [],
	comments: function(type, id) {
		if (typeof Comment.open[type+id] == 'undefined' || Comment.open[type+id] == false) {
			if (typeof Comment.loaded[type+id] == 'undefined') {
				$('#comments-'+type+'-'+id).load('/comment/comments/'+type+'/'+id+'/', {}, function(){
					$('#comments-'+type+'-'+id).slideDown(200);
				});
				Comment.loaded[type+id] = true;
				Comment.open[type+id] = true;
			} else {
				$('#comments-'+type+'-'+id).slideDown(200);
				Comment.open[type+id] = true;
			}
		} else {
			$('#comments-'+type+'-'+id).slideUp(200);
			Comment.open[type+id] = false;
		}
	},
	load: function(type, id, page) {
		$('#comments-'+type+'-'+id).load('/comment/comments/'+type+'/'+id+'/'+page+'/', {}, function(){
			//$('#comments-'+type+'-'+id).show();
		});
	},
	remove: function(id) {
		if (confirm('Are you sure you wish to remove this comment?')) {
			$.post('/comment/delete/'+id+'/', {}, function(folder){
				$('#comment-'+id).html('');
			});
		}
	},
	submit: function(type, id) {
		$('.comment-reply').html('');
	
		var reply = $('#comment-reply-' + type + '-' + id);
		var finish = function(){
			$.post('/comment/submit/'+type+'/'+id+'/', $('#comment-form').serializeArray(), function(folder){
				reply.html('');
				$('#comments-'+type+'-'+id).show();
				$('#comments-'+type+'-'+id).load('/comment/comments/'+type+'/'+id+'/last/');
			});
			reply.html('Sending...');
			return false;
		}
		
		reply.html('Loading...');
		reply.load('/comment/submit/?' + (new Date()).getTime(), function(data){
			$('#comment-form').bind('submit', finish);
			$('#comment-close').bind('click', function(){
				$('.comment-reply').html('');
				return false;
			});
		});
		
	},
	Submission: {
		addEmote: function(emoticon) {
			Comment.Submission.addText('', emoticon);
		},
		addText: function(open, close) {
			var entry = $('#comment-entry');
			var textarea = entry.get(0);
			
			try{
				var str 	= document.selection.createRange().text;
				
				entry.focus();
				
				var sel 	= document.selection.createRange();
				sel.text 	= open + str + close;
			}
			catch(e){
				try{
					var text_content	=	entry.val();
					text_left		=	text_content.substr(0, textarea.selectionStart);
					text_middle		=	text_content.substr(textarea.selectionStart, textarea.selectionEnd	-	textarea.selectionStart);
					text_right		=	text_content.substr(textarea.selectionEnd, textarea.textLength		-	textarea.selectionEnd);
					
					entry.val( text_left + open + text_middle + close + text_right);
					entry.focus();
				}
				catch(e){
					entry.val(entry.val() + open + close);
				}
			}
		}
	}
};