var installed = 'true';
var fileList = '';
var plus_size = parseInt('0');
var arr_files_list = new Array();

$(document).ready(function(){
  //installChk();
  var num = 0;
  var chkInterval = setInterval(function(){
    if(installed == 'true'){
      clearInterval(chkInterval);
    }else{
      num = (parseInt(num) + 1);
      if(parseInt(num) == 3){
        clearInterval(chkInterval);
      }
      installChk();
    }
  },2000);
});

function installChk(){
  $.ajax({
    url: "http://127.0.0.1:8887",
    dataType: 'jsonp',
    jsonpCallback: "Installed",
    success: function(data) {
      installed = 'true';
    },
    error: function(x,e) {
      if(x.status == 0){ installed = 'false'; }
      else if(x.status == 404){ installed = 'false'; }
      else if(x.status == 500){ installed = 'false'; }
      else if(e == 'parsererror'){ installed = 'true'; }
      else if(e == 'timeout'){ installed = 'false'; }
      else{ installed = 'false'; }
    }
  });
}

function mmsv_Upload_Insert(type, userId){
  if(installed == 'false'){
    alert('파일마루 프로그램 설치 확인중입니다\n\n잠시 후 다시 이용해 주세요\n\n미설치 시 프로그램을 설치 후 이용해 주세요');
    return false;
  }else{
    /*
    if(type == 'file'){
      if(!confirm('[알림]\n파일등록은 다중 파일을 지원하지 않습니다\n다중 파일은 폴더 등록을 이용해주세요\n\n* ActiveX 를 쓰지 않는 프로그램으로 업데이트 됨에 따라 이전 버전 사용자분들은 파일 및 폴더 선택창이 뜨지 않을 수 있습니다.\n이럴 경우 기존 버전을 삭제 후 수동설치 파일을 받아 설치해주세요')){
        return flase;
      }
    }else{
      alert('* ActiveX 를 쓰지 않는 프로그램으로 업데이트 됨에 따라 이전 버전 사용자분들은 파일 및 폴더 선택창이 뜨지 않을 수 있습니다.\n이럴 경우 기존 버전을 삭제 후 수동설치 파일을 받아 설치해주세요')
    }
    */
    searchOpen(type);
  }
}

function searchOpen(openType){
  var status = 'false';
  $.ajax({
    url: "http://127.0.0.1:8887",
    type: 'GET',
    dataType: 'jsonp',
    jsonpCallback: "Upload",
    data : 'type='+openType,
    success: function(data) {
      threadUploadChk(openType);
    },
    error: function(x, e) {
      console.log(e);
      status = 'false';
    }
  });
}

function threadUploadChk(openType){
  uploadList(openType);

  var num = 0;
  var chkInterval = setInterval(function(){
    if(fileList != ''){
      clearInterval(chkInterval);
    }else{
      num = (parseInt(num) + 1);
      /*
      if(parseInt(num) == 3){
        clearInterval(chkInterval);
      }
      */
      uploadList(openType);
    }
  },800);

}

function uploadList(openType){
  var f = document.uploadForm;
  var zeroSizeArray = new Array();		//제로사이즈 체크
  var filePath = '';
  var section = '';

  $.ajax({
    url: "http://127.0.0.1:8887",
    //url:"./mmsv/test.php",
    dataType: 'jsonp',
    jsonpCallback: "Selected",
    success: function(data) {
      fileList = data;
      zeroSizeArray = Array();

      //통신 성공하면 등록하기전 기존 등록된 자료들 삭제 시킴
      mmsv_UploadSelect('select');
      mmsv_UploadRemove();
      arr_files_list = Array();
      plus_size = 0;
      arr_size = '';

      if(fileList){
        $("#uploadFileListDisp").show();
        $('#uploadFileSeletor').attr('rowspan','2');

        if(openType == 'folder'){
          section = '';
        }else{
          section = '-1';
        }

        $.each(data.file, function(index){
          filePath = '';
          filePath = data.file[index].path.replace(/\*/gi,"\\");

          if($.inArray(filePath, arr_files_list) != -1){
            alert('이미 선택된 파일입니다');
            return false;
          }

          //용량 계산
          if(parseInt(data.file[index].size) <= 0){
            zeroSizeArray.push(data.file[index].size);
            arr_files_list.push(section+"||-1||"+filePath);
            $("#uploadFileListDisp select").append('<option value="||-1||'+filePath+'">'+filePath+'</option>');
          }else{
            arr_files_list.push(section+"||"+data.file[index].size+"||"+filePath);
            $("#uploadFileListDisp select").append('<option value="||'+data.file[index].size+'||'+filePath+'">'+filePath+'</option>');
          }

          plus_size += parseInt(data.file[index].size);
          arr_size += data.file[index].size + '||';
        });

        $("#filesize").val(plus_size);
        $("#fileArrSize").val(arr_size);

        var mega = Round($("#filesize").val() / 1045576 , 0 ,''); //메가로 변경
    		var permWonMin = Math.round(mega/10);
    		//permWonMin = Math.round(permWonMin/2);
    		permWonMin = Math.round(permWonMin/10)*10;//정수형 첫째자리 처리
    		if(permWonMin < 50) permWonMin = 50;

        document.uploadForm.cash.value = permWonMin;
        document.uploadForm.filetype.value=openType;
        document.uploadForm.filepath.value=data.file[0].path.replace(/\*/gi,"\\");
        document.uploadForm.mmsv_files.value = arr_files_list.join("**");
        var splitFileName = data.file[0].path.replace(/\*/gi,"\\").split('\\');
        var firstPath = '-1';

        if(data.file[0].size <= 0){
          firstPath = '';
          for(var i=0; i<splitFileName.length; i++){
            var comma = '';
            if(i < (splitFileName.length - 1)){comma = "\\";}else{comma = "";}
            firstPath += splitFileName[i] + comma;
          }
        }
        document.uploadForm.firstPath.value = firstPath;
        document.uploadForm.filename.value = splitFileName[splitFileName.length-1];
    		$('#printSize').html(parseSize(document.uploadForm.size.value,2));
      }
    },
    error: function(x,e) {
      fileList = '';
      /*
      if(x.status == 0){ alert('(0)인터넷 연결을 확인해주세요.'); }
			else if(x.status == 404){ alert('(40)잘못된 경로로 호출 되었습니다.'); }
			else if(x.status == 500){ alert('(50)관리자에게 문의해 주세요.'); }
			else if(e == 'parsererror'){ alert('(60)관리자에게 문의해 주세요.'); }
			else if(e == 'timeout'){ alert('(70)연결이 원할하지 않습니다. 잠시후 다시 시도하여 주세요.'); }
			else{ alert('Unknow Error.n'+x.responseText); }
      */
    }
  });
}

function mmsv_UploadRemove(){
  var form = document.uploadForm;
	var deleted = 0;

	// 폴더가 선택되었는지 체크
	for (i = form.mmsv_upload_list.length - 1; i > 0; i--) {
		if (form.mmsv_upload_list.options[i].selected == true) {
			info = form.mmsv_upload_list[i].value.split("||");
			if (info[1] == "-1") {
				for (j = 1; j < form.mmsv_upload_list.length; j++) {
					if (form.mmsv_upload_list[j].text.indexOf(form.mmsv_upload_list[i].text) >= 0) {
						form.mmsv_upload_list.options[j].selected = true;
					}
				}
			}
		}
	}

	for (i = form.mmsv_upload_list.length - 1; i > 0; i--) {
		if (form.mmsv_upload_list.options[i].selected == true) {
			for (j = i; j < form.mmsv_upload_list.length-1; j++) {
				form.mmsv_upload_list[j].value = form.mmsv_upload_list[j+1].value;
				form.mmsv_upload_list[j].text = form.mmsv_upload_list[j+1].text;
			}
			deleted++;
		}
	}

	form.mmsv_upload_list.length -= deleted;

  arr_files_list = Array();
  var sizeChk = 0;
  var tmpVal = '';

  if(form.mmsv_upload_list.length > 1){	// 파일이나 폴더가 선택되었을때만		1과 비교하는 이유는 -------첨부된 파일목록------- 이것 때문
    //파일리스트 가져와서 select리스트로 뿌리기
    if(deleted > 0){
      for (i = 1; i < form.mmsv_upload_list.length; i++) {
        arr_files_list[i-1]=form.mmsv_upload_list.options[i].value;
        tmpVal = form.mmsv_upload_list.options[i].value.split("||");
        if(tmpVal[1] > 0){
          sizeChk += parseInt(tmpVal[1]);
        }
      }

      console.log(sizeChk);

      $("#filesize").val(sizeChk);
      var mega = Round($("#filesize").val() / 1045576 , 0 ,''); //메가로 변경
      var permWonMin = Math.round(mega/10);
      permWonMin = Math.round(permWonMin/2);
      permWonMin = Math.round(permWonMin/10)*10;//정수형 첫째자리 처리
      if(permWonMin < 10) permWonMin = 10;

      $('#printSize').html(parseSize(document.uploadForm.size.value,2));
      form.cash.value = permWonMin;
      form.mmsv_files.value = arr_files_list.join("**");
    }
  }else{
    $('#printSize').html('0.0B');
    form.cash.value = '0';
    form.mmsv_files.value = '';
  }

	mmsv_UploadSelect("unselect");
}

/* 추가 업로드 목록 리스트 */
function mmsv_UploadSelect(mode)
{
	var form = document.uploadForm;
	for (i = 1; i < form.mmsv_upload_list.length; i++) {
		form.mmsv_upload_list.options[i].selected = (mode == "select") ? true : false;
	}
}
