/**
 * Form Attachements class
 * 
 * @author Christiaan Baartse
 * @copyright 2010 Web Power, http://www.webpower.nl
 * 
 var attachments = new FormAttachments(
 	{
		fileprefix_thumb	: '/uploaded/IMAGES/thumb/',		// Prefix that is added before the tmp_name of the files
		fileprefix_zoom		: '/uploaded/IMAGES/zoom/',		// Same as above but then for zoom
		file_input			: '#file_input',
		thumbnails			: false, // False lets the FormAttachments create a thumbnails pane itself
		placeholder			: '<div class="placeholder"></div>', // Replaces the input while uploading
		file_types			: ['jpg', 'gif', 'png'], // Empty array for all file extensions
		url					: '/index.php/upload?ajax&upload_type=Reactionfiles&upload_key=10',
		delete_url			: '/index.php/upload/remove?ajax&upload_type=Reactionfiles&upload_key=10&key=', // Image key gets added to the end
		maxfiles			: 10, // 0 is infinite
		maxfilesmessage		: '<div class="maxfilesmessage">Maximum files uploaded</div>',
		callbacks			: {
			postBuildThumbnails : function(){
				$('.current_size').html(this.files.length + '  foto(s)');
				return true;
			},
			error				: function(code, responseText) {
				switch(msg)
				{
					case 'timeout_expired':
						alert('Timeout verstreken.');
					break;
					case 'invalid_extension':
						alert('Bestandstype niet toegestaan.');
					break;
					case 'invalid_data':
						alert('De server gaf een ongeldig antwoord terug');
					break;
					default:
					alert('Kon het bestand niet uploaden '+ msg);
				}
			
				return true;						
			},
			deleted				: function() { return true; },
			uploaded			: function() {
				if(submitted) {
					$('form.reaction_form', reactiongroup).submit();
				}
				return true;
			},
			preUpload			: function(file_input) {
				$('.current_size', reactiongroup).html('');
				return true;
			}
		},
		timeout		: 180000
	},
	[
		{"name":"IMG_5873.jpg","tmp_name":"phpojaKRT.jpg","size":192328},
		{"name":"Strange_World_VI_by__kol.jpg","tmp_name":"phpYCO4Gd.jpg","size":309967}
	]
);
 */
function FormAttachments(options, files)
{
	this.options = $.extend(true, {}, this.defaults, options);
	this.file_input = $(this.options.file_input);
	this.maxfilesmessage = $(this.options.maxfilesmessage).insertAfter(this.file_input).hide();
	this.maxtotalsizemessage = $(this.options.maxtotalsizemessage).insertAfter(this.maxfilesmessage).hide();
	this.files = files ? files : [];
	this.uploading = false;
	if(false === this.options.thumbnails) {
		this.thumbnails_pane = $('<div class="thumbnails"></div>').insertBefore(this.file_input);
	} else {
		this.thumbnails_pane = $(this.options.thumbnails);
	}
	
	var self = this;
	this.thumbnails_pane.click(function(e){
		var clicked = $(e.target);
		if(clicked.is('a.delete') && clicked.parent('div').is('.thumb')) {
			e.preventDefault();
			if(true === self.options.callbacks.preDelete.call(self, clicked)) {
				$.ajax({
					type	: 'GET',
					dataType: 'json',
					url		: self.options.delete_url + clicked.attr('rel'),
					success	: function(data) {
						if(true === self.options.callbacks.deleted.call(self, data))
						{
							self.files = data;
							self.buildThumbnails();
						}
					},
					error	: function() {
						self.options.callbacks.error.call(self, 'delete_error');
					}
				});
			}
			return false;
		}
	});
	
	self.buildThumbnails();
};

/**
 * Upload an attachment
 * 
 * @param {DOMNode} file_input <input type="file"> node other than the default (optional)
 */
FormAttachments.prototype.upload = function(file_input)
{
	file_input = file_input ? file_input : this.file_input;
	if(this.options.maxfiles && this.options.maxfiles <= this.files.length)
	{
		this.options.callbacks.error.call(this, 'max_files_uploaded');
	}
	else if(this.options.maxtotalsize && this.options.maxtotalsize <= this.getSize())
	{
		this.options.callbacks.error.call(this, 'max_filesize_exceeded');
	}
	else if(true === this.options.callbacks.preUpload.call(this, file_input))
	{
		var self = this;
		this.uploading = true;
		$(file_input).ajaxUpload({
			file_types	: this.options.file_types,
			url			: this.options.url,
			placeholder	: this.options.placeholder,
			error		: function(msg, data, file, placeholder) {
				this.uploading = false;
				if(true === self.options.callbacks.error.call(self, msg, data)) {
					// Set the file_input to blank, isn't it easy!
					var new_file = self.file_input.clone(true).val('').insertBefore(self.file_input);
					self.file_input.remove();
					self.file_input = new_file;
				}
				if(placeholder.length) {
					self.file_input.insertAfter(placeholder);
					placeholder.remove();					
				}
				return false;
			},
			success		: function(data, file, placeholder){
				self.uploading = false;
				files = eval('(' + data + ')');
				if(files){
					if(true === self.options.callbacks.uploaded.call(self, files)) {
						self.files = files;
						self.buildThumbnails();
						
						// Set the file_input to blank, isn't it easy!
						var new_file = self.file_input.clone(true).val('').insertBefore(self.file_input);
						self.file_input.remove();
						self.file_input = new_file;
					}
					self.file_input.insertAfter(placeholder);
					placeholder.remove();
				} else {
					this.options.callbacks.error.call(self, 'invalid_data', data)
				}
				return false;
			},
			timeout		: self.options.timeout
		});
	}
};

/**
 * Build thumbnails for the files
 * 
 * @param {Object} files An array containing data about the uploaded files (optional)
 */
FormAttachments.prototype.buildThumbnails = function(files)
{
	var self = this, counter = 0;
	files = files ? files : this.files;
	this.thumbnails_pane.children().remove();
	$.each(files, function(i) {
		var div = [], thumb, zoom,
		ext = this.name.substr(this.name.lastIndexOf('.') + 1).toLowerCase();
		if ($.inArray(ext, self.options.img_types) != -1) {
			thumb = this.thumb_url ? this.thumb_url : self.options.fileprefix_thumb + this.tmp_name;
			zoom = this.zoom_url ? this.zoom_url : self.options.fileprefix_zoom + this.tmp_name;
		}
		
		div.push('<div class="thumbwrapper">');
		div.push('<div title="'+this.name+'" class="thumb'+(thumb?'':' no_thumb')+' filetype_'+ext+'" style="');
		if (thumb) {
			div.push('background-image: url('+thumb+');');
		}
		div.push('">');
		div.push('<a class="delete" href="#" title="Delete" rel="'+i+'">Delete</a>');
		if (zoom) {
			div.push('<a class="zoom" href="'+zoom+'" target="_blank" title="Zoom">Zoom</a>');
		}
		div.push('</div>');
		div.push('</div>');
		
		$(div.join("")).appendTo(self.thumbnails_pane);
		counter += 1;
	});
				
	if(true === self.options.callbacks.postBuildThumbnails.call(self))
	{
		if((self.options.maxfiles && self.options.maxfiles <= counter) || (self.options.maxtotalsize && self.options.maxtotalsize <= this.getSize()))
		{
			self.file_input.hide();
			(self.options.maxfiles && self.options.maxfiles <= counter) ? self.maxfilesmessage.show() : self.maxfilesmessage.hide();
			(self.options.maxtotalsize && self.options.maxtotalsize <= this.getSize()) ? self.maxtotalsizemessage.show() : self.maxtotalsizemessage.hide();
		}
		else
		{
			self.file_input.show();
			self.maxfilesmessage.hide();
			self.maxtotalsizemessage.hide();
		}
	}
};

/**
 * Get the current size of all files added together
 * 
 * @return {int} Number of bytes
 */
FormAttachments.prototype.getSize = function()
{
	var size = 0;
	$.each(this.files, function(i) { size += this.size; });
	return size;
};

/**
 * The defaults used for every instance
 */
FormAttachments.prototype.defaults = {
	fileprefix_thumb	: '/',		// Prefix that is added before the tmp_name of the files
	fileprefix_zoom		: '/',		// Same as above but then for zoom
	file_input			: '#file_upload',
	thumbnails			: false,
	placeholder			: '<div class="placeholder"></div>',
	file_types			: [], // Empty array for all file extensions
	img_types			: ['jpg', 'jpeg', 'gif', 'png'], // The file extensions that should be treated as images
	url					: '',
	delete_url			: '',
	maxfiles			: 0, // 0 is infinite
	maxfilesmessage		: '<div class="maxfilesmessage">Maximum files uploaded</div>',
	maxtotalsize		: 0, // 0 is infinite
	maxtotalsizemessage	: '<div class="maxtotalsizemessage" style="height: 21px;">Maximum filesize exceeded</div>',
	callbacks			: {
		postBuildThumbnails : function(){ return true; },
		error			: function(code, msg) {
			switch(code)
			{
				case 'timeout_expired':
					alert('Timeout verstreken.');
				break;
				case 'invalid_extension':
					alert('Bestandstype niet toegestaan.');
				break;
				case 'invalid_data':
					alert('De server gaf een ongeldig antwoord terug');
				break;
				default:
				alert('Kon het bestand niet uploaden '+ msg);
			}
			
			return true;
		},
		preDelete		: function() { return true; },
		deleted			: function() { return true; },
		uploaded		: function() { return true; },
		preUpload		: function(file_input) { return true; }
	},
	timeout		: 180000
};
