(function(window, $, undefined) {
	
var _parent = window.dialogArguments || opener || parent || top;

$.fn.wplupload  = function($options) {
	var $up, $defaults = { 
		runtimes : 'gears,browserplus,html5,flash,silverlight,html4',
		browse_button_hover: 'hover',
		browse_button_active: 'active'
	};
	
	$options = $.extend({}, $defaults, $options);
	
	return this.each(function() {
		var $this = $(this);
				
		$up = new plupload.Uploader($options);
					
		$up.bind('FilesAdded', function(up, files) {
			$.each(files, function(i, file) {
				// Create a progress bar containing the filename
				$('#progress').css({'visibility':'visible', 'display':'block'});
				$('#select-files').hide();

				// Hide drag-drop overlay and remove fullscreen extension when upload starts
				$('#wpallimport-fullscreen-drag-overlay').hide();
				$('#wpallimport-drag-drop-area').removeClass('fullscreen-active');
			})
		});
		
		$up.init();				
		
		$up.bind('Error', function(up, err) {
			// Check if this is an Excel file and we haven't tried alternative processing yet
			var file = err.file;
			var isExcelFile = file && file.name && /\.(xls|xlsx)$/i.test(file.name);
			var hasTriedAlternative = file && (file.wpai_tried_alternative || false);

			if (isExcelFile && !hasTriedAlternative) {
				// Mark that we've tried alternative processing for this file
				file.wpai_tried_alternative = true;

				// Show retry message
				$('#progressbar').html('<span>Retrying with alternative Excel processing method...</span>');
				$('#progress').show();

				// Set flag for alternative Excel processing
				$up.settings.multipart_params.use_alternative_excel = '1';

				// Reset file status and retry
				setTimeout(function() {
					file.status = plupload.QUEUED;
					file.percent = 0;
					file.loaded = 0;
					$up.start();
				}, 1000);

				return; // Don't show error yet
			}

			//$('#upload_process').html(err.message);
			//$('.wpallimport-header').next('.clear').after(err.message);
			$('.error-upload-rejected').show();

			// Reset drag-drop state on error
			$('#wpallimport-fullscreen-drag-overlay').hide();
			$('#wpallimport-drag-drop-area').removeClass('fullscreen-active');
			if (typeof window.isDragDropUpload !== 'undefined') {
				window.isDragDropUpload = false;
			}
			if (typeof window.dragCounter !== 'undefined') {
				window.dragCounter = 0;
			}
		});
		
		$up.bind('FilesAdded', function(up, files) {
			// Disable submit and enable cancel
			
			$('.error.inline').remove();

			$('.first-step-errors').hide();

			$('.wpallimport-choose-file').find('.wpallimport-upload-resource-step-two').slideUp();

			$('#cancel-upload').removeAttr('disabled');

			//$('.auto-generate-template').removeAttr('rel').hide();

			$('.wpallimport-upload-type-container[rel=upload_type]').find('.wpallimport-note').hide();

			$up.start();
		});
		
		$up.bind('UploadFile', function(up, file, r) {			
				
		});
		
		$up.bind('UploadProgress', function(up, file) {
			// Lengthen the progress bar
			$('#progressbar').html('<span>Uploading</span> ' + file.name + ' ' + file.percent + '%');
			$('#upload_process').progressbar({value:file.percent});

		});
		
		
		$up.bind('FileUploaded', function(up, file, r) {
			var fetch = typeof(shortform) == 'undefined' ? 1 : 2;
			var response = r.response;
			r = _parseJSON(r.response);

			if (r.OK === 0)
			{
				// Check if this is an Excel file and we haven't tried alternative processing yet
				var isExcelFile = file.name && /\.(xls|xlsx)$/i.test(file.name);
				var hasTriedAlternative = file.wpai_tried_alternative || false;

				if (isExcelFile && !hasTriedAlternative) {
					// Mark that we've tried alternative processing for this file
					file.wpai_tried_alternative = true;

					// Show retry message
					$('#progressbar').html('<span>Retrying with alternative Excel processing method...</span>');
					$('#progress').show();

					// Set flag for alternative Excel processing
					$up.settings.multipart_params.use_alternative_excel = '1';

					// Reset file status and retry
					setTimeout(function() {
						file.status = plupload.QUEUED;
						file.percent = 0;
						file.loaded = 0;
						$up.start();
					}, 1000);

					return; // Don't show error yet
				}

				$('.wpallimport-choose-file').find('.wpallimport-submit-buttons').hide();
				$('.wpallimport-import-from.selected').click();
				$('#wpallimport-url-upload-status').html('');

				$('#progress').hide();
				$('#progressbar').html('<span></span>');
				$('#select-files').fadeIn();

				//$('.wpallimport-header').next('.clear').after('<div class="error inline"><p>' + response + '</p></div>');
				$('.error-upload-rejected').show();
			}
			else
			{
				if (r.error !== null){

					// Check if this is an Excel file and we haven't tried alternative processing yet
					var isExcelFile = file.name && /\.(xls|xlsx)$/i.test(file.name);
					var hasTriedAlternative = file.wpai_tried_alternative || false;

					if (isExcelFile && !hasTriedAlternative) {
						// Mark that we've tried alternative processing for this file
						file.wpai_tried_alternative = true;

						// Show retry message
						$('#progressbar').html('<span>Retrying with alternative Excel processing method...</span>');
						$('#progress').show();

						// Set flag for alternative Excel processing
						$up.settings.multipart_params.use_alternative_excel = '1';

						// Reset file status and retry
						setTimeout(function() {
							file.status = plupload.QUEUED;
							file.percent = 0;
							file.loaded = 0;
							$up.start();
						}, 1000);

						return; // Don't show error yet
					}

					$('.wpallimport-choose-file').find('.wpallimport-submit-buttons').hide();
					$('.wpallimport-import-from.selected').click();
					$('#wpallimport-url-upload-status').html('');

					$('#progress').hide();
					$('#progressbar').html('<span></span>');
					$('#select-files').fadeIn();

					if (typeof(r.is_valid) != 'undefined')
					{
						$('.error-file-validation').find('h4').html(r.error.message);
						$('.error-file-validation').show();
					}
					else
					{
						$('.wpallimport-header').next('.clear').after('<div class="error inline"><p>' + r.error.message + '</p></div>');
					}

				}
				else{

					// Check if this was a successful retry with alternative Excel processing
					var isExcelFile = file.name && /\.(xls|xlsx)$/i.test(file.name);
					var hasTriedAlternative = file.wpai_tried_alternative || false;
					var usedAlternative = $up.settings.multipart_params.use_alternative_excel === '1';

					if (isExcelFile && hasTriedAlternative && usedAlternative) {
						// Reset the flag for future uploads
						$up.settings.multipart_params.use_alternative_excel = '0';
						// Check the alternative Excel processing checkbox on the page
						$('#use_alternative_excel_processing').prop('checked', true);
					}

					if (r.post_type)
					{
						// Find the option with the matching value
						var $option = $('#custom_type_selector option[value="'+ r.post_type +'"]');
						if ($option.length)
						{
							$('#custom_type_selector').val(r.post_type).trigger('change');

							if (r.taxonomy_type){
								var $taxOption = $('#taxonomy_to_import option[value="'+ r.taxonomy_type +'"]');
								if ($taxOption.length){
									$('#taxonomy_to_import').val(r.taxonomy_type).trigger('change');
								}
							}
							if (r.gravity_form_title){
								var $gfOption = $('#gravity_form_to_import option[value="'+ r.gravity_form_title +'"]');
								if ($gfOption.length){
									$('#gravity_form_to_import').val(r.gravity_form_title).trigger('change');
								}
							}

							if (typeof r.url_bundle != "undefined")
							{
								$('input[name=url]').val(r.name);
								$('input[name=template]').val(r.template);
								$('input[name=bundle_xpath]').val(r.bundle_xpath);
								$('.auto-generate-template').css({'display':'inline-block'}).attr('rel', 'url_type');
								$('.wpallimport-url-type').click();
								$('.wpallimport-download-from-url').click();
							}
							else
							{
								$('.auto-generate-template').css({'display':'inline-block'}).attr('rel', 'upload_type');
							}
						}
						else
						{
							$('.auto-generate-template').hide();
						}
					}
					else
					{
						$('.auto-generate-template').hide();
					}

					$('#filepath').val(r.name);

					$('#progressbar').html('<span>Upload Complete</span> - ' + file.name + ' (' + ( (file.size / (1024*1024) >= 1) ? (file.size / (1024*1024)).toFixed(2) + 'mb' : (file.size / (1024)).toFixed(2) + 'kb') + ')');
					$('.wpallimport-import-types').find('h2').slideUp();

					setTimeout(function() {

						if (r.post_type && r.notice !== false)
						{
							var $note = $('.wpallimport-upload-type-container[rel=upload_type]').find('.wpallimport-note');
							$note.find('span').html("<div class='wpallimport-free-edition-notice'>" + r.notice + "</div>");
							$note.show();
							$('.wpallimport-choose-file').find('.wpallimport-submit-buttons').hide();
							$('.wpallimport-choose-file').find('.wpallimport-upload-resource-step-two').slideUp();
							$('input[name=filepath]').val('');
						}
						else
						{
							$('.wpallimport-choose-file').find('.wpallimport-upload-resource-step-two').slideDown();
							$('.wpallimport-choose-file').find('.wpallimport-submit-buttons').show();
						}

						if (r.OK) {

						} else if (r.error != undefined && '' != r.error.message) {
							//$('#progressbar').html(r.error.message);
							$('.error-upload-rejected').show();
						}

					}, 1000);
				}
			}					
		});
		
		$up.bind('UploadComplete', function(up) {
			$('#cancel-upload').attr('disabled', 'disabled');
			$('#advanced_upload').show();

			// Reset drag-drop state
			if (typeof window.isDragDropUpload !== 'undefined') {
				window.isDragDropUpload = false;
			}
		});
		
		$('#cancel-upload').on('click', function() {
			var i, file;
			
			$up.stop();		
						
			i = $up.files.length;
			for (i = $up.files.length - 1; i >= 0; i--) {
				file = $up.files[i];
				if ($.inArray(file.status, [plupload.QUEUED, plupload.UPLOADING]) !== -1) {
					$up.removeFile($up.getFile(file.id));					
				}
			}
			
			$('#cancel-upload').attr('disabled', 'disabled');
			
		});
		
	});	
};

function _parseJSON(r) {
	var obj;
	try {
		var matches = r.match(/{.*}/);		
		obj = $.parseJSON(matches[0]);
	} catch (e) {		
		obj = { OK : 0 };	
	}	
	return obj;
}

}(window, jQuery));