/**
 *
 */

(function($) {
	
	$.fn.xqMultiUp = function(options) {
	
		var defaults = {
		
			'api': false,
			'classUploadFrame': 'xqMultiUpFrame',
			'messages': ['Uploading...', 'Success!', 'Failed'],
			'maxFiles': 99,	// Restrict the number of files
			'noduplicates': false, //Check if file ist exists in upload queue
			
			'includeForm': '',	//Form selector to a <form> thats will be included (not implemented)
			
			
			'onUpload': '', // Function called after upload (not implemented)
			'onRemove': '', // Function called after file was removed (not implemented)
			'onBeforeRemove': '' // Function called before file was removed (not implemented)
		};
		
		var options = $.extend(defaults, options, {
		
			version: '0.1'
		});
		
		var $selector = this;
		
		if (this.length > 0) {
		
			function multiup($selector) {
			
				var $plugin = this;
			
				/* +---------- plugin author functions ----------+ */
			
				$plugin.getConf = function(confName) {
				
					return options[confName];
				};
				
				$plugin.setConf = function(confName, confValue) {
				
					options[confName] = confValue;
					return options[confName];
				};
				
				
				
				for (var f in options) {
				
					if (typeof options[f] == 'function') {
					
						$plugin[f] = options[f];
					}
				}
				
				/* +---------- plugin properties ----------+ */
				
				$plugin.uploadMode = getUploadMode();
				$plugin.fileList = $('ul:eq(0)', $selector);
				$plugin.mainForm = $('form:eq(0)', $selector);
				$plugin.frameName = 'xqMultiUpFrame' + $('iframe.' + options.classUploadFrame).length;
				$plugin.templateFileList = $('li:eq(0)', $selector).html();
				$('li:eq(0)', $selector).remove();
				
					$plugin.isUploading = false;
				
				
				/* +---------- plugin methods ----------+ */
				
				$plugin.setup = function() {
				
					if ($plugin.uploadMode == 1) {
					
						$frame = $('<iframe name="' + $plugin.frameName + '" class="' + options.classUploadFrame + '" src="about:blank" width="1px" height="1px" frameborder="0"></iframe>').appendTo($selector);
						$frame.load(function() {
						
							$list = $('li.uploading');
							
							if ($list.length > 0) {
								
								//Get upload status
								try {
									
									var postbackText = (frames[$plugin.frameName].document.documentElement.textContent) ? frames[$plugin.frameName].document.documentElement.textContent : frames[$plugin.frameName].document.documentElement.innerText;
									
									eval("var postback = " + postbackText + ";");
								}
								catch(e) {
									
									
								}
								
								if (postback && postback.files[0].error == 0) {
									
									$list.removeClass('uploading').addClass('success');
									$list.find('.progress').html(options.messages[1]);
								}
								else {
									
									$list.removeClass('uploading').addClass('failed');
									$list.find('.progress').html(options.messages[2]);
								}
								
								$list.find('.size').html(postback.files[0].size);
								$list.find('.type').html(postback.files[0].type);
							}
							
							$plugin.uploadNext();
						});
					}
					
					$plugin.mainForm.attr('target', $plugin.frameName);
					$plugin.mainForm.hide();
					$plugin.addFile(null);
					
					$('.submit', $selector).click(function() {
					
						$plugin.startUpload();
					});
				};
				
				$plugin.startUpload = function() {
				
					$plugin.isUploading = true;
					$plugin.uploadNext();
				};
				
				$plugin.uploadNext = function() {
				
					$list = $('li.ready:eq(0)', $plugin.fileList);
					$form = $('form', $list);
					
					if ($form.length > 0) {
					
						$form.get(0).submit();
						$list.removeClass('ready').addClass('uploading');
						$list.find('.progress').html(options.messages[0]);
					}
				};
				
				$plugin.stopUpload = function() {
				
					$plugin.isUploading = false;
				};
				
				$plugin.addFile = function($file) {
					
					//Check duplicates
					if (options.noduplicates) {
						
						if ($('li span.file', $selector).filter(function(index) {
							
							return $(this).text() == $file.val();
							
						}).length > 0) { //if
							
							//Duplicate found
							//TODO call message
							return false;
						}
					}
				
					var $oldList = $('li:last', $plugin.fileList);
					$oldList.addClass('ready');
					$('form', $oldList).hide();
					
					if (null != $file) {
					
						$($plugin.templateFileList).appendTo($oldList);
						$('span.file', $oldList).text($file.val());
						$('span.remove', $oldList).click(function() {
						
							$plugin.removeFile($(this));
						});
					}
					
					var $list = $('<li></li>').appendTo($plugin.fileList);
					var $form = $plugin.mainForm.clone(true).appendTo($list);
					$(':file', $form).change(function() {
					
						$plugin.addFile($(this));
					});
					$form.show();
					
					if (options.maxFiles < $('li', $plugin.fileList).length) {
					
						$(':file', $form).attr('disabled', 'disabled').css('opacity', '0.5');
					}
				};
				
				$plugin.removeFile = function($file) {
				
					$file.parents('li').remove();
					$('li:last :file:disabled', $plugin.fileList).attr('disabled', '').css('opacity', '1');
				};
				
				/* +---------- plugin construct ----------+ */
				
				$plugin.setup();
				
			}
			
			
			
			this.each(function() {
			
				var plugin = new multiup($(this));

			});
		}
		
		return options.api ? plugin : this;
	
	};
	
	function getUploadMode() {
	
		var uMode = 1;
		
		return uMode;
	}
	
 })(jQuery);
