/* Minification failed. Returning unminified contents.
(56,23-24): run-time error JS1195: Expected expression: )
(56,26-27): run-time error JS1195: Expected expression: >
(64,39-40): run-time error JS1195: Expected expression: >
(66,10-11): run-time error JS1195: Expected expression: )
(71,44-45): run-time error JS1195: Expected expression: >
(73,3-4): run-time error JS1002: Syntax error: }
(77,9-10): run-time error JS1002: Syntax error: }
(87,39-40): run-time error JS1195: Expected expression: )
(87,42-43): run-time error JS1195: Expected expression: >
(89,3-4): run-time error JS1002: Syntax error: }
(94,3-4): run-time error JS1002: Syntax error: }
(115,16-17): run-time error JS1195: Expected expression: .
(115,29-30): run-time error JS1195: Expected expression: .
(115,41-42): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ]
 */
/*
 * One Click Upload - jQuery Plugin
 * Copyright (c) 2008 Michael Mitchell - http://www.michaelmitchell.co.nz
 */
(function ($) {
    $.fn.upload = function (options) {
        options = $.extend({
            name: 'file',
            enctype: 'multipart/form-data',
            action: '',
            autoSubmit: true,
            onSubmit: function () { return true },
            onComplete: function () { },
            onError: function () { },
            onSelect: function () { },
            params: {}
        }, options);

        return new $.ocupload(this, options);
    },

		$.ocupload = function (element, options) {
	    var self = this;

	    var id = new Date().getTime().toString().substr(8);

	    /** Upload Iframe */
	    //		document.frames.hiddenDownloader
	    //		var iframe = $('#hiddenDownloader');

	    var iframe = $('<iframe id="iframe' + id + '" name="iframe' + id + '" style="display: none;"></iframe>'
		            ).css({
		                display: 'none'
		            });

	    var form = $('<form method="post" id="upload_form" enctype="' + options.enctype + '" action="' + options.action + '" target="iframe' + id + '">'
        + '<input type="hidden" name="uploadtime"/>'
        + '</form>'
		).css({ margin: 0, padding: 0 });

	    /** File Input */
		var input = $('<input id="file_upload"  name="' + options.name + '" type="file" multiple="multiple" />'
		).css({ position: 'absolute', display: 'block', opacity: 0, top: '0px', left: '0px', right: '0px', bottom: '0px', width: '100%', cursor: 'pointer' });

		var filesArr = [],
			btnAddDocs = document.querySelector('.add_document'),
			btnDownload = document.querySelector('#upload_button');
	    /** Put everything together */
	    element.wrap("<div class='row'></div>");
	    form.append(input);
	    element.after(form);
		element.after(iframe);

		const select = document.querySelector('#slFile_documentType');

		const clearInput = () => {
			const input = document.querySelector('#file_upload');

			input.value = '';
			input.files.length = 0;
			filesArr.length = 0;
        }

		select.addEventListener('click', e => {
			clearInput()
        })

		var isLoading = true,
			isClick = true;

		btnDownload.addEventListener('click', e => {
			clearInput();
		})

		btnAddDocs.addEventListener('click', e => {
			clearInput()
        })

		// dnd
		const dropzone = document.querySelector('.dropzone');

		input.click(function (e) {
			isLoading = true;
			isClick = true;
        })

		dropzone.addEventListener('click', () => {
			input.click()
		})

		dropzone.addEventListener('dragover', (e) => {
			e.preventDefault();
			e.dataTransfer.dropEffect = 'copy';
		})

		dropzone.addEventListener('drop', (e) => {
			e.preventDefault();
			const input = document.querySelector('#file_upload'),
				files = e.dataTransfer.files;

			if (!isClick) {
				isLoading = true;
            }

			if (files && files.length > 0 && isLoading) {
				addFiles(files)
				isLoading = false;
			}

			isClick = false;

			if (input.files && input.files.length > 0) {
				const fileList = Array.from(input.files),
					eventList = Array.from(files),
					newArr = [...fileList, ...eventList],
					newFileList = new DataTransfer()

				newArr.forEach(item => {
					newFileList.items.add(item)
				})

				input.files = newFileList.files;
			} else {
				input.files = files;
			}
		});

		input.change(function (e) {
			e.stopPropagation();
			e.preventDefault();

			const files = e.target.files;

			if (isLoading) {
				addFiles(files);
				//isLoading = true;
			}

			for (let i = 0; i < files.length; i++) {
				filesArr.push(files[i])
			}
			
			if (filesArr.length > 0) {
				const newArr = [...filesArr, ...files],
					newFileList = new DataTransfer();

				Array.from(new Set(newArr)).forEach(item => {
					newFileList.items.add(item)
				})

				e.target.files = newFileList.files;
			} else {
				e.target.files = files;
			}
		})

		const addFiles = (files) => {
			/** Do something when a file is selected. */
			for (let i = 0; i < files.length; i++) {
				self.onSelect(files[i].name)
			}

			DropZoneScroll()

			/** Submit the form automaticly after selecting the file */
			if (self.autoSubmit) {
				self.submit();
			}
		}

	    /** Methods */
	    $.extend(this, {
	        autoSubmit: true,
	        onSubmit: options.onSubmit,
	        onComplete: options.onComplete,
	        onSelect: options.onSelect,

	        /** get filename */
			filename: function () {
	            return input.attr('value');
	        },

	        /** get/set params */
			params: function (params) {
	            var params = params ? params : false;

	            if (params) {
	                options.params = $.extend(options.params, params);
	            }
	            else {
	                return options.params;
	            }
	        },

	        /** get/set name */
			name: function (name) {
	            var name = name ? name : false;

	            if (name) {
	                input.attr('name', value);
	            }
	            else {
	                return input.attr('name');
	            }
	        },

	        /** get/set action */
			action: function (action) {
	            var action = action ? action : false;

	            if (action) {
					form.attr('action', action);
	            }
				else {
	                return form.attr('action');
	            }
	        },

	        empty_file: function () {
	            $(input).val("");
	        },

	        /** get/set enctype */
	        enctype: function (enctype) {
	            var enctype = enctype ? enctype : false;

	            if (enctype) {
	                form.attr('enctype', enctype);
	            }
	            else {
	                return form.attr('enctype');
	            }
	        },

	        /** set options */
	        set: function (obj, value) {
				var value = value ? value : false;

	            function option(action, value) {
	                switch (action) {
	                    default:
	                        throw new Error('[jQuery.ocupload.set] \'' + action + '\' is an invalid option.');
	                        break;
	                    case 'name':
	                        self.name(value);
	                        break;
	                    case 'action':
	                        self.action(value);
	                        break;
	                    case 'enctype':
	                        self.enctype(value);
	                        break;
	                    case 'params':
	                        self.params(value);
	                        break;
	                    case 'autoSubmit':
	                        self.autoSubmit = value;
	                        break;
	                    case 'onSubmit':
	                        self.onSubmit = value;
	                        break;
	                    case 'onComplete':
	                        self.onComplete = value;
	                        break;
	                    case 'onError':
	                        self.onError = value;
	                        break;
	                    case 'onSelect':
	                        self.onSelect = value;
	                        break;
	                }
	            }

	            if (value) {
	                option(obj, value);
	            }
	            else {
	                $.each(obj, function (key, value) {
	                    option(key, value);
	                });
	            }
	        },

	        submit: function () {
	            if (this.onSubmit()) {

	                $('input[type=hidden]', form).remove();
					
					$.each(options.params, function (key, value) {
	                    form.append($(
						'<input ' +
							'type="hidden" ' +
							'name="' + key + '" ' +
							'value="' + value + '" ' +
						'/>'
					));
	                });

	                $('input[name=uploadtime]', form).val(getNTime());
					form.submit();

					iframe.load(function () { 
						iframe.unbind("load");

	                    var response;
	                    try {
	                        var myFrame = document.getElementById(iframe.attr('name'));
	                        response = myFrame.contentWindow.document;

	                        $('input[name=uploadtime]', form).val(getNTime());
	                    }
	                    catch (err) {
	                        self.onError(err);
	                    }

	                    self.onComplete(response);
	                });
	            }
	        }



	    });
	}
})(jQuery);;
