
var Comments = Class.create();

Comments.prototype = {
	/*
	 * args: 
	 *  #1 id of the container that holds the new comment form 
	 *  #2 id of the container that holds the list of comments
	 */
	initialize: function(container, list) {
		this.container = container;
		this.list      = list;
	},
	
	showCommentForm: function() {
		if(!$(this.container).visible()) 
			new Effect.BlindDown(this.container, {duration:0.4, afterFinish: function () { focusFirst('formNewComment'); Scroll('comments'); } });
		else 
			new Effect.BlindUp(this.container, { duration: 0.4 });
	},
	
	cancelNewComment: function() {
		new Effect.SlideUp(this.container, { duration: 0.4 });
	},
	
	attachFile: function() {
		if($('attachFileToComment').visible())
		{
			new	Effect.BlindUp('attachFileToComment',{duration:0.2});
			new	Effect.BlindDown('attachFileToCommentUpload',{duration:0.2});
		}
		else
		{
			new	Effect.BlindDown('attachFileToComment',{duration:0.2});
			new	Effect.BlindUp('attachFileToCommentUpload',{duration:0.2});
		}
	},
	
	/*
	 * We use this method before sending out the comments form in order to check for empty fields, and file upload access
	 */
	checkBeforeSending: function() {
		var valid = true;
		if(!$('commentContent').present())
		{
			new Effect.Shake('commentContent');
			valid = false;
		}
		else
		{
			showLoading($('commentSaveBox'));
			if($('comment_file').present())
			{
				var pageId = $F('pagePageId');
				var pars = 'ajaxAction=checkFileBeforeUpload&pageId=' + pageId + '&commentFileName=' + $F('comment_file');

				new Ajax.Request(ajaxUrl, {parameters: pars, onComplete: this._checkBeforeSending_callback.bindAsEventListener(this)});
			}
			else
				this.sendCommentFormForReal();
		}
	},
	
	_checkBeforeSending_callback: function(request) {
		if(request.responseText == 'no-access')
		{
			hideLoading($('commentSaveBox'));
			alert("You don't have permission to upload this file.");
		}
		else if(request.responseText == 'duplicate')
		{
			hideLoading($('commentSaveBox'));
			alert("Unfortunately this page already contains a file attachment with this same name. Please rename the file, and upload it again.");
			Form.Element.focus('file_description');
		}
		else
			this.sendCommentFormForReal();
	},
	
	sendCommentFormForReal: function () {
		this.cleanUpIFrame();
		this.periodicalUploadInit();
		$('formNewComment').submit();
		$('formNewComment').down('input[type=submit]').disable();
	},
	
	/*
	 * Ajax upload related
	 */
	cleanUpIFrame:function() {
		var iframeUpload = $('commentFileUploadTarget');
		if(iframeUpload)
		{
			if(iframeUpload.contentDocument)
				var iframeDocument = iframeUpload.contentDocument;
			else if(iframeUpload.contentWindow)
			    var iframeDocument = iframeUpload.contentWindow.document;
			else
			 	var iframeDocument = window.frames[iframeName].document;
		}
		iframeDocument.body.innerHTML = '';
	},
	
	periodicalUploadInit:function() {
		new PeriodicalExecuter(function(periodicalExecuterObj){comments.periodicalUploadVerifier(periodicalExecuterObj);},1);
	},
	
	periodicalUploadVerifier:function(periodicalExecuterObj){
		var iframeUpload = $('commentFileUploadTarget');
		if(iframeUpload)
		{
			if(iframeUpload.contentDocument)
				var iframeDocument = iframeUpload.contentDocument;
			else if(iframeUpload.contentWindow)
			    var iframeDocument = iframeUpload.contentWindow.document;
			else
			 	var iframeDocument = window.frames[iframeName].document;

			if(iframeDocument.body.innerHTML == 'true' || iframeDocument.body.innerHTML == 'false' || !iframeDocument.body.innerHTML.empty())
			{
				periodicalExecuterObj.stop();
				this.commentSave(iframeDocument.body.innerHTML);
			}	
		}
	},
	
	commentSave:function(response) {
		hideLoading($('commentSaveBox'));
		var response = response.evalJSON();
		$('formNewComment').down('input[type=submit]').enable();

		if(response.status == false)
			alert("There was an error processing your request. Please reload this page and try again.");
		else if(response.status == 'account-limit')
		{
			var alertMsg = "Sorry but you can't upload this file because the project owner's account has reached its storage limit. ";
			if(typeof(response.ownerEmail) != 'undefined')
				alertMsg += 'Please notify '+response.ownerEmail+' that the limit has been reached.';
			else
				alertMsg += 'Please consider an upgrade.';

			alert(alertMsg);
		}
		else if(response.status == true)
		{
			$(this.list).update(response.xhtml.unescapeHTML());
			if(typeof($(response.file_xhtml)) != 'undefined' && $('allFiles'))
				$('allFiles').insert({'bottom':response.file_xhtml.unescapeHTML()});
				
			if(typeof($(response.syntaxHelperBarItem)) != 'undefined' && $('syntaxHelperBarPane-files'))
				$('syntaxHelperBarPane-files').down('ul').insert({'top':response.syntaxHelperBarItem.unescapeHTML()});

			$('formNewComment').reset();
			$('attachFileToCommentUpload').hide();
			$('attachFileToComment').show();
		}
	},
	
	
	saveNewComment: function(projectId) {
		if(!$(this.container).down('form').down('textarea').present())
			new Effect.Shake(this.container);
		else
		{
			showLoading($(this.container).down());
			new Ajax.Updater(this.list, ajaxUrl, {
				onComplete: this.saveNewComment_callback.bind(this),
				parameters: 'ajaxAction=saveNewComment&projectId=' + projectId + '&' + Form.serialize($(this.container).down('form')),
				evalScripts:true, asynchronous:true  
			});
		}
	},
	
	saveNewComment_callback: function(request) {
		new Effect.SlideUp(this.container, {duration: 0.4});
		$(this.container).down('form').down('textarea').clear(); 
		hideLoading($(this.container).down());
	},
	
	removeComment: function(commentId, projectId) {
		if(!confirm('Are you sure?'))
			return false;
		else
		{
			var isEditing = (page.isEditing.main || page.isEditing.second) ? 1 : 0;
			new Ajax.Request(ajaxUrl,
				{ 
					parameters: 'ajaxAction=removeComment&id=' + commentId + '&projectId=' + projectId + '&isEditing='+isEditing, 
					onComplete: this.removeComment_callback.bindAsEventListener(this,commentId)
				});
		}
	},
	
	removeComment_callback: function(request,commentId) {
		if(request.responseText == 'false')
			alert("There was an error removing the comment.");
		else if(request.responseText == 'no-access')
			alert("You don't have permission to remove this comment.");
		else if(request.responseText == 'true')
		{
			files.refreshFilesListing($F('pagePageId'), $F('pageProjectId'));
			new Effect.BlindUp('comment-' + commentId, {duration: 0.3, afterFinish:function(){$('comment-'+commentId).remove();}});
		}
	}
};

var comments = new Comments('newCommentContainer', 'commentsList');
