var MultiFileUploader = Class.create({
	initialize : function (containerId, uploaderURL, encPath, options,
							strAddAFile, strUpload, strCancel, strExtensionNotAllowed, BlankPageURL)
	{
		// strAddAFile = 'Add a file'
		// strUpload = 'Upload'
		// strCancel = 'Cancel'
		// strExtensionNotAllowed = 'This type of file is not allowed'

		this.strExtensionNotAllowed = strExtensionNotAllowed;
		this.uploadedFileCallback = function(){};
		this.removedFileCallback = function(){};
		this.encPath = encPath;

		this.options = options || {};

		if (typeof options.showInputAtStart != 'undefined') this.options.showInputAtStart = options.showInputAtStart;
		else this.options.showInputAtStart = false;

		if (typeof options.allowRemove != 'undefined') this.options.allowRemove = options.allowRemove;
		else this.options.allowRemove = true;

		if (typeof options.allowPost != 'undefined') this.options.allowPost = options.allowPost;
		else this.options.allowPost = true;
		
		if (typeof options.allowedExtensions != 'undefined') this.options.allowedExtensions = ','+options.allowedExtensions.replace(/ /g,'')+',';
		else this.options.allowedExtensions = ',doc,docx,xls,xlsx,ppt,pptx,txt,htm,html,css,pdf,gif,jpg,jpeg,png,psd,zip,gz,tgz,rar,7z,';

		if (typeof options.bShowAuthor != 'undefined') this.options.bShowAuthor = options.bShowAuthor;
		else this.options.bShowAuthor = true;
		
		if (typeof options.bShowDate != 'undefined') this.options.bShowDate = options.bShowDate;
		else this.options.bShowDate = true;
		
		this.uploaderURL = uploaderURL
		this.xmlrpcURL = this.options.xmlrpcURL || uploaderURL + 'xmlrpc.php';

		this.options.uploadMethod = options.uploadMethod || 'uploadFile';
		this.options.listFilesMethod = options.listFilesMethod || 'listFiles';
		this.options.removeFileMethod = options.removeFileMethod || 'removeFile';

		this.waitAnimationURL = uploaderURL + 'ajax_progressbar.gif';

		this.files = Array();

		this.id = containerId;
		this.container = $(this.id);

		// Create upload Form
		this.uploadFormId = this.id+'UploadForm';
		this.uploadFormFrameId = this.id+'UploadFormFrame';
		this.uploadForm = new Element('form', {'method':'post', 'enctype':'multipart/form-data',
												'id':this.uploadFormId, 'target':this.uploadFormFrameId})

		//this.container.insert(this.uploadForm);
		this.container.insert('<form method="post" enctype="multipart/form-data" id="' + this.uploadFormId + '" target="' + this.uploadFormFrameId + '"></form>');
		this.uploadForm = $(this.uploadFormId);
		this.uploadForm.insert(new Element('input', {'type':'hidden','name':'encPath','value':this.encPath}));
		// Create upload frame
		this.uploadFormFrame = new Element('iframe', {'id':this.uploadFormFrameId, 'name':this.uploadFormFrameId, 'src':BlankPageURL});

		this.uploadFormFrame.hide();
		this.uploadForm.insert(this.uploadFormFrame);

		this.filesContainerId = this.id + 'FilesContainer';
		this.uploadForm.insert(new Element('ul', { 'id':this.filesContainerId}));
		this.filesContainer = $(this.filesContainerId);
		this.filesContainer.addClassName('multifile-uploader-filelist');

		this.newFileContainerId = this.id + 'NewFileContainer';
		this.newFileLinkContainerId = this.id + 'NewFileLinkContainer';
		this.newFileInputContainerId = this.id + 'NewFileInputContainer';

		if (this.options.allowPost)
		{
			this.uploadForm.insert(new Element('div', {'id':this.newFileContainerId}));
			this.newFileContainer = $(this.newFileContainerId);

			var link = new Element('a', {'class':'edit_record_link', 'id':this.newFileLinkContainerId}).update(strAddAFile);

			link.setStyle({'cursor' : 'pointer'});
			Event.observe(link, 'click', this.showNewFileInput.bindAsEventListener(this));

			this.newFileContainer.insert(link);
			this.newFileLinkContainer = $(this.newFileLinkContainerId);

			this.newFileContainer.insert(new Element('div', { 'id':this.newFileInputContainerId}));
			this.newFileInputContainer = $(this.newFileInputContainerId);
			this.newFileInputContainer.insert(new Element('input', {'size': '30', 'type':'file', 'name':'uploadFile'}));
			
			this.buttonUpload = new Element('button', {'type':'button'}).update(strUpload);
			Event.observe(this.buttonUpload, 'click', this.sendFile.bindAsEventListener(this));

			this.buttonCancel = new Element('button', {'type':'button'}).update(strCancel);
			Event.observe(this.buttonCancel, 'click', this.hideNewFileInput.bindAsEventListener(this));

			var buttonsDiv = new Element('div');
			buttonsDiv.insert(this.buttonUpload);
			buttonsDiv.insert(this.buttonCancel);
			
			this.newFileInputContainer.insert(buttonsDiv);

			if (this.options.showInputAtStart)
				this.showNewFileInput();
			else
				this.hideNewFileInput();
		}

		this.animation = new Element('img', {'src':this.waitAnimationURL});
		this.animation.hide();
		this.getFileList();
		this.uploadForm.insert(this.animation);
	},


	showNewFileInput : function()
	{
		this.newFileInputContainer.show();
		this.newFileLinkContainer.hide();
	},

	hideNewFileInput : function()
	{
		this.newFileInputContainer.hide();
		this.newFileLinkContainer.show();
	},

	startAnimate : function()
	{
		if (this.buttonUpload)
			this.buttonUpload.hide();
		
		if (this.buttonCancel)
			this.buttonCancel.hide();
		
		this.animation.show();
	},

	endAnimate : function()
	{
		if (this.buttonUpload)
			this.buttonUpload.show();
		
		if (this.buttonCancel)
			this.buttonCancel.show();
		this.animation.hide();

	},

	sendFile : function()
	{
		this.newFileInputContainer.hide();
		this.startAnimate();

		this.uploadForm.action = this.xmlrpcURL + '?method=uploadFileInFrame';
		if (!this.checkFileExtension())
		{
			alert(this.strExtensionNotAllowed);
			this.endAnimate();
			this.showNewFileInput();
			return false;
		}
		
		this.uploadForm.submit();
		this.checkUploadStatus();
	},
	
	checkFileExtension : function ()
	{
		var fileInput = this.newFileInputContainer.down('input');
		var fileExt = /\.[^.]+$/.exec(fileInput.value) + '';
		if (this.options.allowedExtensions.indexOf(','+fileExt.substring(1)+',') != -1)
			return true;
		
		return false;
		
	},

	checkUploadStatus : function()
	{
		new PeriodicalExecuter(this.getResponseFromFrame.bindAsEventListener(this), 1);
	},

	getResponseFromFrame : function(scheduler)
	{
		if (!this.uploadFormFrame.contentWindow.document.body)
			return;

		var frameHTML = this.uploadFormFrame.contentWindow.document.body.innerHTML;

		if (frameHTML == '')
			return;

		scheduler.stop();
		this.endAnimate();

		var parts = frameHTML.split('|');
		if (parts[0] == 'Failure')
			alert(parts[1]);
		else if (parts[0] == 'Success')
		{
			this.newFileInputContainer.down('input', 0).value = '';
			this.uploadFormFrame.contentWindow.document.body.innerHTML = '';
			this.getFileList();
			if(typeof this.uploadedFileCallback != 'undefined')
				this.uploadedFileCallback(parts[1]);
		}

		this.hideNewFileInput();
	},

	getFileList : function()
	{
		var params = this.uploadForm.serialize(true);
		params.method = this.options.listFilesMethod;

		var request = new Ajax.Request(this.xmlrpcURL,
						{parameters : params,
						onSuccess: this.getFileListOnSuccess.bind(this)});
		
		this.endAnimate();
	},

	getFileListOnSuccess : function(ajaxResponse)
	{
		this.filesContainer.update('');
		if (ajaxResponse.responseJSON && ajaxResponse.responseJSON.Return == 'Success')
		{
			if (ajaxResponse.responseJSON.Files.length == 0)
				return;
			for(var i = 0; i < ajaxResponse.responseJSON.Files.length; i++)
				this.addFileInList(ajaxResponse.responseJSON.Files[i]);
		}

		HideSpinner();
	},

	addFileInList : function(file)
	{
		var fileIndex = this.files.length;
		this.files[fileIndex] = file.id;
		var newFileLI = new Element('li');

		var newFileImageIcon = new Element('img', {'src':file.icon});
		if (this.options.allowRemove && file.CanRemove == 1)
		{
			var newFileImageDelete = new Element('img', {'src':this.uploaderURL + 'Delete.gif', 'id':'Delete_' + fileIndex});

			newFileImageDelete.setStyle({verticalAlign:'middle', cursor:'pointer'});
			Event.observe(newFileImageDelete, 'click', function()
				{
					this.removeFile(fileIndex);
				}.bind(this));
		}

		var newFileNameLink = new Element('a', {'href':file.link, 'target':this.uploadFormFrameId}).update(file.filename);
		var newFileSize = new Element('span').update('&nbsp;(' + file.filesize + ')');
		var newFileAuthor = new Element('span').update('&nbsp;' + file.author).setStyle({'fontStyle':'italic'});
		var newFileDate = new Element('div').update(file.upload_date).setStyle({'fontStyle':'italic', 'textIndent':'30px'});

		newFileLI.insert(newFileImageIcon);
		newFileLI.insert(newFileNameLink);
		newFileLI.insert(newFileSize);
		newFileLI.insert(newFileImageDelete);

		if (this.options.bShowAuthor)
			newFileLI.insert(newFileAuthor);
		if (this.options.bShowDate)
			newFileLI.insert(newFileDate);

		this.filesContainer.insert(newFileLI);
	},

	removeFile : function(fileIndex)
	{
		if (!confirm('Are you sure you want to remove this file ?'))
			return;

		this.startAnimate();

		var params = this.uploadForm.serialize(true);
		params.method = this.options.removeFileMethod;
		params.id = this.files[fileIndex];
		var request = new Ajax.Request(this.xmlrpcURL,
						{parameters : params,
						onSuccess: function()
						{
							this.getFileList();
							if(typeof this.removedFileCallback != 'undefined')
								this.removedFileCallback();

						}.bind(this)
					});
	},
	
	setFileUploadedCallback : function(func)
	{
		this.uploadedFileCallback = func;
	},
	
	setFileRemovedCallback : function(func)
	{
		this.removedFileCallback = func;
	}
});