FileInfo = function(manager) {
	this.manager = manager;
	this.setSuccess = function() {
		this.manager.setSuccess(this);
	};
	this.setError = function(msg) {
		this.manager.setError(this,msg);
	};
};
FileUpload = function(fileUrl,$f,container,num,size,totalSize,acceptExt) {
	this.fileUrl = fileUrl;
	this.container = container;
	this.delBtn = ".del";
	this.$f = $f;
	this.maxNum = num;
	this.maxSize = size;
	this.maxTotalSize = totalSize;
	this.fileInfoArr = [];
	this.allowExt = acceptExt.split(',');
	
	this.num = 0;
	this.count = -1;
	this.totalSize = 0;
	this.canceled = false;
	
	 var obj = $j("button");

     obj.on('dragenter', function (e) {
          e.stopPropagation();
          e.preventDefault();
          var files = e.originalEvent.dataTransfer.files;
          console.log(files);
          $j(this).addClass('sel');
     });

     obj.on('dragleave', function (e) {
          e.stopPropagation();
          e.preventDefault();
          $j(this).removeClass('sel');
     });

     obj.on('dragover', function (e) {
          e.stopPropagation();
          e.preventDefault();
          $j(this).addClass('sel');
     });

     obj.on('drop', function (e) {
    	 e.stopPropagation();
         e.preventDefault();
         $j(this).removeClass('sel');
		 var files = e.originalEvent.dataTransfer.files;
		 fileUpload.fileLoad(files,function(data){});
     });
     
	this.infoUpdate = function() {
		$j("#fileSize").html(humanFileSize(this.totalSize));
		$j("#fileNum").html(this.count+1);
	};
	
	this.infoUpdate();
	
	this.statusClear = function() {
		this.status.setProgress(100);
		this.status.abort();
		var parent = $f.parent();
		var newFile = $f.clone();
		$f.remove();
		$f = newFile;
		
		$j(parent).append(newFile);
		
		$j("input[name='files']").val("");
	};
	
	this.setSuccess = function(loader) {
		//this.fileInfoArr.push(loader);
		this.loadCount++;
		this.count++;
		if( (this.loadCount+1) == this.fileList.length ) {
			this.statusClear();
		} else {
			this.status.setProgress(((this.loadCount+1)*100/this.fileList.length));
		}
		this.infoUpdate();
	};
	
	
	this.setError = function(loader,msg) {
		if( loader ) {
			this.loadCount++;
			if( (this.loadCount+1) >= this.fileList.length ) {
				this.statusClear();
			} else {
				this.status.setProgress(((this.loadCount+1)*100/this.fileList.length));
			}
		} else {
			this.statusClear();
		}
		this.infoUpdate();
		alert(msg);
	};
	
	this.sendTotal = 0;
	this.sendToServer= function() {
		fileUpload.isSending = true;
		var uploadURL = $j("#boardForm").attr("action");
		var fd = new FormData($j("#boardForm")[0]);
		fd.append("fileType", "file" );
		for(var i=0;i<fileUpload.fileInfoArr.length;i++) {
			var file = fileUpload.fileInfoArr[i].file;
			fd.append("file", file );
		}
		var error = false;
		var token = $j("meta[name='_csrf']").attr("content");
		var header = $j("meta[name='_csrf_header']").attr("content");
		$j.ajax({
			beforeSend:function(xhr) {
				if(token != undefined && header != undefined){
					xhr.setRequestHeader(header, token);
				}
			},
			xhr: function() {
                var xhrobj = $j.ajaxSettings.xhr();
                /*
                if (xhrobj.upload) {
                    xhrobj.upload.addEventListener('progress', function(event) {
                   	 if( !error ) {
                         var position = event.loaded || event.position;
                         fileUpload.sendTotal += position;
                         var percent = fileUpload.sendTotal * 100/fileUpload.totalSize;
                         if (fileUpload.status != undefined) {
                        	 fileUpload.status.setProgress(percent);
                         }
                   	 }
                    }, false);
                }
                */
                return xhrobj;
            },
	        url: uploadURL,
	        type: "POST",
	        contentType:false,
	        processData: false,
	        cache: false,
	        data: fd,
	        error:function(textStatus, data) {
	       	 	error = true;
	       	 	submitted = false;
	        },
	        success: function(data, stat){
	        	if(data.status == undefined){
	        		submitted = false;
	        		$j("html").html(data);
	        	} else {
		        	if(data.status == "ERROR") {
		        		alert(data.msg);
		        	}
		        	submitted = false;
		        	if(fileUpload.status != undefined) {
		        		//fileUpload.status.abort();
		        	}
		        	if(data.mode != undefined) {
		        		if(data.mode == "reloadClose") {
		        			window.opener.location.reload();
		        			self.close();
		        		}
		        	} else {
		        		document.location.href = data.url;
		        	}
	        	}
	        }
    	});
	};
	
	this.submit = function(e) {
		if (fileUpload.status != undefined) {
			//fileUpload.status.show();
		}
		this.sendToServer();
	};
	
	this.setCancel = function() {
		this.canceled = true;
	};

	this.URL = function() {
		return window.URL || window.webkitURL;
	};
	this.fileLoad = function(fileList, successFunc) {
		if(fileList.length == 0 ) return;
		if( confirm("잠깐만요!\n첨부하신 파일에 개인정보는 확인하셨나요?\n-홈페이지 문서 게시는 PDF 파일로 변환하여 게시\n-부득이하게 엑셀파일 탑재 시 숨김 메모 및 숨기기 처리된 행·열·시트 사전 확인 필수\n우리 모두의 소중한 개인정보를 보호해주세요~") ) {
			this.loadCount = -1;
			this.fileList = fileList;
			this.status = this.createStatusbar();
			
			function fileCheck(filename) {
				var idx = filename.lastIndexOf('.');
				if(idx==-1) {
					return false;
				}
				
				var ext = filename.substring(idx).toLowerCase();
				for(var i=0;i<fileUpload.allowExt.length;i++) {
					if(ext == fileUpload.allowExt[i]) {
						return true;
					}
				}
				return false;
			}
			
			$j.each(fileList,function(idx,file) {
				fileInfo=new FileInfo(fileUpload);
				
				if( file.size > fileUpload.maxSize ) {
					fileUpload.setError(fileInfo, "파일 하나당 최대 " + humanFileSize(fileUpload.maxSize) + "까지만 올릴 수 있습니다.");
					return true;
				}
				
				if( (fileUpload.num+1) > fileUpload.maxNum ) {
					fileUpload.setError(null, fileUpload.maxNum + "개 까지만 추가할 수 있습니다.");
					return false;
				}
				
				if(!fileCheck(file.name)) {
					fileUpload.setError(null, file.name + "은 허용되지 않은 파일입니다.");
					return false;
				}
				
				if( (fileUpload.totalSize+file.size) > fileUpload.maxTotalSize ) {
					fileUpload.setError(null, "한번에 올릴 수 있는 최대 용량은 " + humanFileSize(fileUpload.maxTotalSize) + "까지만 올릴 수 있습니다.");
					return false;
				}
				fileUpload.totalSize += file.size;
				fileInfo.file = file;
				
				
				var $info = $j("<div class='fileInfo' data-index='"+fileUpload.num+"'/>");
				var $item = $j("<div class='name'>"+file.name+"</div>");
				$info.append($item);
				var $alt = $j("<div class='alt'><input type='text' name='file_alt' title='파일설명' placeholder='파일설명'></div>");
				$info.append($alt);
				$item = $j("<div class='size'>"+humanFileSize(file.size)+"</div>");
				$info.append($item);
				$delBtn = $j("<div><span class='usm-btn usm-sm'><button class='del' type='button'>삭제</button></span></div>");
				
				$delBtn.on('click keydown', function(e) {
					if (e.type === 'click' || (e.type === 'keydown' && e.key === 'Enter')) {
						var parent = $j(this).parent();
						var selectedIndex = parseInt(parent.data("index"));
						var file = fileUpload.fileInfoArr[selectedIndex].file;
						fileUpload.num--;
						fileUpload.totalSize -= file.size;
						fileUpload.fileInfoArr.splice(selectedIndex,1);
						if( fileUpload.count != -1 ) { fileUpload.count--;}
						parent.remove();
						
						$infoList = $j(".fileInfo");
						for(var i=0;i<fileUpload.maxNum;i++) {
							$j($infoList[i]).attr("data-index",i+"");
						}
						
						fileUpload.infoUpdate();
						return false;
					}
				});
	
				$info.append($delBtn);
				
				$j(fileUpload.container).append($info);
				
				fileInfo.manager.fileInfoArr.push(fileInfo);
				fileUpload.num++;
				fileUpload.setSuccess();
			});
		}
	};

    this.createStatusbar=function(){
        var statusBar = function() {
	        this.statusbar = $j(".tch-statusbar");
	        this.size = $j(".tch-percent");
	        this.progressBar = $j(".tch-progress");
	        this.percent = $j(".tch-percent");
	        
	        var width = $j(window).width();
	    	var height = $j(window).height();
	    	var statusHeight = $j(".tch-bar-wrap").outerHeight();
	    	
	    	this.statusbar.outerHeight(height);
	    	$j(".tch-bar-wrap").css("margin-top", "100px");
	    	$j(".tch-bar-bg").css("margin-left", (width-350)/2+"px");
	    	
	    	this.statusbar.show();
	    	this.show = function() {
	    		this.setProgress(0);
	    		this.statusbar.show();
	    	};
	         
	        this.setProgress = function(progress){ 
	        	var per = parseInt(progress);
	        	if(per <= 100) {
		            this.percent.html(per + "% ");
		            this.progressBar.css("width", per+"%");
	        	}
	        };
	         
	        this.setAbort = function(){
	            var sb = this.statusbar;
	            this.abortObj.click(function() {
	                jqxhr.abort();
	                sb.hide();
	            });
	        };
	        
	        this.abort = function(){
	            var sb = this.statusbar;
				sb.hide();
	        };
        
        };
        
        return new statusBar();
    };
};
