/**
 * Upload <input type="file"> nodes like jquery ajax requests
 * 
 * @author Christiaan Baartse
 * @copyright 2010 Web Power, http://www.webpower.nl
 * 
 * 	Example:
	$('#file1').ajaxUpload({
		file_types	: ['jpg', 'gif', 'png'],
		url		: '/index.php/upload?ajax&upload_key=files',
		placeholder	: '<div class="placeholder"><img src="/pics/loading.gif" /></div>',
		error		: function(msg){ alert('Kon het bestand niet uploaden '+ msg); return true; },
		success		: function(data, file){
			file.val('');
			data = eval('(' + data + ')');
			if(data) buildThumbs(data);
			
			return true; // Places the File input back to its original spot on true
		},
		timeout		: 60000 // Seconds so 1 minute here
	});
 */
;(function($) {

	var	counter = 0,
	inactive = [];
	
	$.fn.ajaxUpload = function(options) {
		var opt = $.extend({}, $.fn.ajaxUpload.defaults, options);
		
		if($.inArray('jpg', opt.file_types) != -1 && $.inArray('jpeg', opt.file_types) == -1) {
			opt.file_types.push('jpeg');
		}
		
		this.each(function(){
			var file = $(this);
			if(file.is('input[type="file"]') && file.val() != '') {
				var ext = file.val().toLowerCase().substr(file.val().toLowerCase().lastIndexOf('.') + 1);
				if(opt.file_types.length == 0 || $.inArray(ext, opt.file_types) != -1) {
					++counter;
					var placeholder = $(opt.placeholder).insertBefore(file),
					tmp_div = $('<div></div>').appendTo('body').hide(),
					tmp_iframe = $('<iframe src="" id="ajaxUpload_'+counter+'" name="ajaxUpload_'+counter+'"></iframe>').appendTo(tmp_div),
					tmp_form = $('<form target="ajaxUpload_'+counter+'" enctype="multipart/form-data" action="' + opt.url + '" method="post" name="ajaxUploadForm_'+counter+'" id="ajaxUploadForm_'+counter+'"></form>'),
					loaded = false,
					tmp_timeoutfc = function(){
						if(true !== loaded) {
							if(false !== opt.error.call(file, 'timeout_expired', tmp_iframe.contents().find('body').html(), file, placeholder)) {
								file.insertAfter(placeholder);
								placeholder.remove();
							}
							tmp_iframe.unbind('load').attr('src', 'about:blank');
							tmp_div.remove();
							tmp_form.remove();
						}						
					},
					tmp_timeout = setTimeout(tmp_timeoutfc, opt.timeout);
					
					tmp_form.insertBefore(tmp_iframe).hide().append(file);
					
					tmp_iframe.one('load', function(){ // When the form is submitted
						clearTimeout(tmp_timeout);
						
						if(false !== opt.success.call(file, $(this).contents().find('body').html(), file, placeholder)) {
							file.insertAfter(placeholder);
							placeholder.remove();
						}
						
						tmp_iframe.unbind('load').attr('src', 'about:blank');
						tmp_div.remove();
						tmp_form.remove();
					});
					
					tmp_form.submit();				
					
				} else {
					opt.error.call(file, 'invalid_extension', '', file, {});
				}
			}
		});		
	};
	
	$.fn.ajaxUpload.defaults = {
		file_types	: ['jpg', 'gif', 'png'],
		url			: '/index.php/upload',
		placeholder	: '<div class="placeholder"></div>',
		error		: function(){ return true; },
		success		: function(){ return true; },
		timeout		: 180000
	};
	
})(jQuery);
