

var Files = Class.create();

Files.prototype = {
	initialize: function() {
		
	},
	
	addShow: function(el)
	{
		if(typeof(el) == 'undefined')
		{
			var el = $('addFileLink');
			var needsScrolling = true;
		}

		if($(el).hasClassName('bottomCurrent'))
		{
			$(el).removeClassName('bottomCurrent');
			Effect.SlideUp($('bottomAjaxSlider'), {duration:0.3, afterFinish: function(){$('bottomAjaxContainer').update('');}});
			return;
		}

		$$('.bottomCurrent').each(function(currentEls) { currentEls.removeClassName('bottomCurrent');});
		$(el).addClassName('bottomCurrent');

		isEditingPage = (page.isEditing.main||page.isEditing.second) ? 1 : 0;
		isSlided = true;
		container = $('bottomAjaxContainer');
		var content = '<div id="bottomInnerContainer">';
		content    +='<form id="addFileForm" target="addFileUploadTarget" action="' + sysUrl + 'file/upload/' + $F('pagePageId') + '" method="post" enctype="multipart/form-data" onsubmit="files.checkBeforeUpload(); return false;">';
		content    += '<p><span class="ajaxContainerTitle">Add File</span></p>';
		content    += '<p><input value="Name" class="text" type="text" name="description" id="file_description" maxlength="32" /> <input class="text" type="file" name="file" id="file_file" /></p>';
		content    += '<p><input type="submit" value="Upload" class="button"  />  ' +  CloseBottomButton() + ' <input type="hidden" name="isEditingPage" value="'+isEditingPage+'" /></p></form>';
		content    += '<iframe id="addFileUploadTarget" name="addFileUploadTarget" src="" style="width:0px;height:0px;border:0px solid #fff;"></iframe>';
		content    += '</div>';
		var newContainer = Builder.build(content);

		if(!$('bottomInnerContainer'))
		{
			container.appendChild(newContainer);
			new Effect.SlideDown('bottomAjaxSlider', {duration:0.3, afterFinish: function() 
				{ 
					if(needsScrolling)
					{
						Effect.ScrollTo('bottomAjaxContainer',{duration:0.3, afterFinish:function(){ focusFirst('addFileForm'); }});
					}
					else
						focusFirst('addFileForm'); 
				}});
		}
		else
		{
			new Effect.SlideUp('bottomAjaxSlider', {duration:0.3, afterFinish: function() { $('bottomAjaxContainer').update(''); container.appendChild(newContainer); Down('bottomAjaxSlider');} });
		}
	},
	
	checkBeforeUpload: function()
	{
		var valid = true;
		if(!$('file_file').present()) 
		{
			valid = false;
			Shake('file_file');
		}	
		if(!$('file_description').present()) 
		{
			valid = false;
			Shake('file_description');
		}
		else
		{
			if($('file_description').length > 32)
			{
				valid = false;
				alert('The filename is too big. Please make it smaller.');
			}
			else if($F('file_description').indexOf('/')!=-1)
			{
				valid = false;
				alert('Unfortunately your filename can\'t have slashes.');
				Shake('file_description');
			}
		}


		if(!valid)
			return false;

		var pageId = $F('pagePageId');
		var pars = 'ajaxAction=checkFileBeforeUpload&pageId=' + pageId + '&' + Form.serialize('addFileForm');
		
		showLoading($('bottomAjaxContainer').down('span.ajaxContainerTitle'));
		new Ajax.Request(ajaxUrl, {parameters: pars, onComplete: this._checkBeforeUpload_callback.bindAsEventListener(this)});
	},
	
	_checkBeforeUpload_callback: function(request)
	{
		if(request.responseText == 'no-access')
		{
			hideLoading($('bottomAjaxContainer').down('span.ajaxContainerTitle'));
			alert("You don't have permission to upload this file.");
		}
		else if(request.responseText == 'duplicate')
		{
			hideLoading($('bottomAjaxContainer').down('span.ajaxContainerTitle'));
			alert("Unfortunately your Jumpchart can't have two files with the same name and the same parent.");
			Form.Element.focus('file_description');
		}
		else
		{
			this.cleanUpIFrame();
			this.periodicalUploadInit();
			// showLoading($('bottomAjaxContainer').down('span.ajaxContainerTitle'));
			$('addFileForm').submit();
			$('bottomAjaxContainer').down('form').disable();
		}
	},
	
	editShow: function(el, id)
	{
		// var container = $('editFile-' + id);
		
		if($(el).hasClassName('bottomCurrent'))
		{
			$(el).removeClassName('bottomCurrent');
			Effect.SlideUp($('bottomAjaxSlider'), {duration:0.3, afterFinish: function(){$('bottomAjaxContainer').update('');}});
			return;
		}

		$$('.bottomCurrent').each(function(currentEls) { currentEls.removeClassName('bottomCurrent');});
		$(el).addClassName('bottomCurrent');
		
		var container  = $('bottomAjaxContainer');

		var pars      = ajaxUrl + '?ajaxAction=editFile&id=' + id;


		// if(!$('bottomInnerContainer'))
		// {
		// 	container.appendChild(newContainer);
		// 	new Effect.SlideDown('bottomAjaxSlider', {duration:0.3, afterFinish: function() 
		// 		{ 
		// 			if(needsScrolling)
		// 			{
		// 				Effect.ScrollTo('bottomAjaxContainer',{duration:0.3, afterFinish:function(){ focusFirst('addFileForm'); }});
		// 			}
		// 			else
		// 				focusFirst('addFileForm'); 
		// 		}});
		// }
		// else
		// {
		// 	new Effect.SlideUp('bottomAjaxSlider', {duration:0.3, afterFinish: function() { $('bottomAjaxContainer').update(''); container.appendChild(newContainer); Down('bottomAjaxSlider');} });
		// }


		new Ajax.Request(ajaxUrl, 
		{
			parameters: pars,
			onComplete: function (request)
			{
				if(request.responseText == 'false')
					alert("There was an error requesting your file edit.");
				else if(request.responseText == 'no-access')
					alert("You don't have permission to edit this file.");
				else
				{
					if(!$('bottomInnerContainer'))
					{
						$('bottomAjaxContainer').update(request.responseText);
						new Effect.SlideDown('bottomAjaxSlider', {duration:0.3, afterFinish: function() {focusFirst('editFileForm-' + id);}});
					}
					else
					{
						new Effect.SlideUp('bottomAjaxSlider', {duration:0.3, afterFinish: function() 
							{ 
								$('bottomAjaxContainer').update(''); 
								$('bottomAjaxContainer').update(request.responseText);
								new Effect.SlideDown('bottomAjaxSlider', {duration:0.3, afterFinish: function() {focusFirst('editFileForm-' + id);}});
							}});
					}
				}
			}
		});

	},
	
	editCancel: function(id)
	{
		var container = $('editFile-' + id);
		Up(container);
	},

	editSave: function(id)
	{
		if(!Field.present('edit_file_description-' + id))
		{
			Shake('edit_file_description-' + id);
		}
		else
		{
			// showLoading('allFiles');
			showLoading($('bottomAjaxContainer').down('span.ajaxContainerTitle'));
			var myAjax = new Ajax.Request(ajaxUrl + '?ajaxAction=saveEditFile', 
			{
				onComplete: this._editSave_callback.bindAsEventListener(this,id),
				parameters: Form.serialize('editFileForm-' + id) + '&page_id=' + $F('pagePageId')
			});
		}
	},

	_editSave_callback: function(request, id)
	{
		hideLoading($('bottomAjaxContainer').down('span.ajaxContainerTitle'));
		if(request.responseText == 'duplicate')
		{
			alert("Unfortunately your Jumpchart can't have two files with the same name and the same parent.");
			Form.Element.focus('edit_file_description');
		}
		else
		{
			$('allFiles').innerHTML = request.responseText;
			CloseBottomSlider();
		}
	},
	
	remove: function(id)
	{
		showLoading('allFiles');
		var isEditing = (page.isEditing.main || page.isEditing.second) ? 1 : 0;
		
		var myAjax = new Ajax.Request(ajaxUrl + '?ajaxAction=removeFile', {	parameters: 'isEditing='+isEditing+'&file_id=' + id + '&page_id=' + $F('pagePageId') + '&project_id=' + $F('pageProjectId'),
			onComplete: this._remove_callback.bindAsEventListener(this,id,isEditing)});
	},

	_remove_callback: function(request, id,isEditing)
	{
		hideLoading('allFiles');
		if(request.responseText == 'false')
			Shake('pageFile-' + id);
		else
		{
			if(!isEditing) page.rebuildPageContent();
			Fade('pageFile-' + id);
			if($('syntaxHelperBarFile-'+id))
				$('syntaxHelperBarFile-'+id).remove();
			
		}
	},

	/*
	 * Ajax upload related
	 */
	cleanUpIFrame:function() {
		var iframeUpload = $('addFileUploadTarget');
		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){files.periodicalUploadVerifier(periodicalExecuterObj);},1);
	},
	
	periodicalUploadVerifier:function(periodicalExecuterObj){
		var iframeUpload = $('addFileUploadTarget');
		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.filesAddSave(iframeDocument.body.innerHTML);
			}	
		}
	},
	
	filesAddSave:function(response) {
		
		var response = response.evalJSON();
		hideLoading($('bottomAjaxContainer').down('span.ajaxContainerTitle'));
		$('bottomAjaxContainer').down('form').enable();

		if(response.status == false)
			alert("There was an error processing your request.");
		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)
		{
			$('allFiles').insert({'bottom':response.xhtmlContent.unescapeHTML()});
			
			if(page.isEditing.main || page.isEditing.second)
			{
				var fragmentOfLastEditedColumn = $(syntaxHelperBar.lastTextarea).id.split('-')[1];
				
				$('formPageContent-'+fragmentOfLastEditedColumn).value += "\n\n(" + $F('file_description') + ')';	
			}
			else
				page.rebuildPageContent();

			if($('syntaxHelperBarPane-files') && response.syntaxHelperBarItem)
				$('syntaxHelperBarPane-files').down('ul').insert({'top':response.syntaxHelperBarItem.unescapeHTML()});
				
			$('addFileForm').reset();
		}
	},
	
	refreshFilesListing: function(pageId, projectId) {
		new Ajax.Request(ajaxUrl, { postBody: 'ajaxAction=filesRefreshList&pageId='+pageId+'&projectId='+projectId, onComplete: this.refreshFilesListing_callback.bindAsEventListener(this)});
	},
	
	refreshFilesListing_callback: function(request) {
		if(request.responseText != 'false')
			$('allFiles').replace(request.responseText);
	}
	
};

var files = new Files();
