/**
 * 附件操作
 */
// var iphost="http://116.10.196.223:8080/doc-service/";
// var iphost=$("#fileservice").val();
var rootPath="";// 当前公文附件根目录
var copyPath="";
var currentPath="";
var electronState = "";
var serviceState = "";
var originflag=false;
var attachflag=false;
var gwstate=true;
var file_type="";
//var meetingFileState="";//hyh  新增  会议附件可否上传全局变量    2017、9、20
//用户信息
var userid="";
var username="";


var attachmentSrc = [];
var operation = false;
var parentid= "-1";
var folderid="-1";
var user_=null;
var pagetype;
var showFlag = "up";
var projectType="";
var openPath = "";

var originaldocFolderId = "";
var addfileControl = "";//hyh 从公文documentAuthorit移动过来的 ,不然除公文外的调用会报未定义的错  2017/10/19

var isSP;
var isHY;
var isGG;
var isOther;

var privilegeStr = '';

contentpath=global.contextPath;
var status=$("#status").val();


//function update_material(doctype){
//	createDirInService(doctype,"general");
//	createDirInService(doctype,"originaldoc");	
//	$("#divNoAttachment,#update_material").css("display","none");
//}


/**
 * 根据目录创建文件夹 发文是默认多创建一级目录:一般附件根目录为:/FW/xxx(uuid)/general
 * 原始来文为:/FW/xxx(uuid)/原始来文
 * 
 * @param doctype
 *            公文类型
 * @returns 目录
 */
function createDirInService(doctype,flodername){
	var year=new Date().getFullYear();
	var type=doctype;
	var iphost=CONF_DOC_SERVERURL;
	var url=iphost +"ftpfile/createDirectory.do";
	var remotePath="";
	var foldid;
	if($.cookie('uuid')=="null"||$.cookie('uuid')==undefined||$.cookie('uuid')==""){
		foldid=uuid();
		$.cookie('uuid',foldid);
		currentuuid = foldid;
	}else{
		foldid=$.cookie('uuid');
	}
		
	if(doctype=="FW"&&flodername=="general"){
		if(rootPath==""){
			rootPath=doctype+"/"+foldid+"/general";
		}
	}else if(doctype!="FW"){
		if(rootPath==""){
	//		rootPath = doctype+"/"+foldid;
			//新增附件带年文件
			rootPath=doctype+'/'+year+'/'+foldid;
		}
	}
	//若当前路径已经包含general文件夹等则不自动创建
	if(doctype=="FW"){
		//这两个文件夹只可以自动创建一次,且是在根目录
		if(currentPath.indexOf("general")!=-1||currentPath.indexOf("originaldoc")!=-1){
		//	flodername=="general"||flodername=="originaldoc"||
			return;
		}
	}
	
	
	if(flodername.length==0){
			remotePath=rootPath;
	}else{
		if(currentPath.length==0){
			if(doctype=="FW"&&flodername=="originaldoc"){
				var originalPath = doctype+"/"+foldid;
				remotePath=doctype+'/'+foldid+"/originaldoc";
				if(rootPath==""){
				//	rootPath = doctype+"/"+ym+"/"+foldid;
					rootPath = doctype+"/"+foldid;
				}
				parentid = getParentId(originalPath);
			}else if(doctype=="FW"&&flodername=="general"){
				remotePath=rootPath;
			}else{
				remotePath=rootPath+"/"+flodername;
			}
		}else{
			remotePath=rootPath+"/"+currentPath+"/"+flodername;
		}	
	}
	$.ajaxSetup({
		async : false //取消异步
	});	
	 $.post(url,{remotePath:remotePath,
		    	flodername:flodername,
		    	parentId:parentid,
		    	username:username,
		    	userId:userid}, function (result) {
		  if(result)
		  {
			  if(result.message!="目录已存在!"){
				  if(currentPath.length!=0){
						loadAttachment(rootPath+"/"+currentPath);
					
				  }else{
					  if(type == "FW"){
						  rootPath = doctype+"/"+foldid+"/general"
					  }
							loadAttachment(rootPath);
					
				  }
				  // 更新主表根目录和时间
				  if(doctype =="HY"){
					  //updateHytime();
				  }else if(doctype == "ZD"){
					  updateZDRootPath();
				  }else if(doctype =="SP"){
					  
				  }else if(doctype =="GG"){//hyh 新增  2017、9、29
					  updateGGrootpath();
				  }else if(doctype =="KZX"){//新增控制线    hufeng   20180904
					  updateKZXrootpath();
				  }else{
					  updaterootortime()
				  }
			  }
/*			  else{
				  layer.msg("目录已存在!",{icon:2}); 
			  }*/
		  return;
//		  $("#divNoAttachment").css("display","none");
		  }
	});
   
    return remotePath;
}

function updateZDRootPath(){
	var status=$("#status").val();
	var importid=$("#importid").val();	
	if(importid!=undefined){
		$.post(global.contextPath + "/mvc/major/updateRootPath.do",
			 {importid:importid,rootPath:rootPath},
				 function (result) {
				 
		       });
	}
}

function copyfile(doctype){
	var type=doctype;
	var iphost=CONF_DOC_SERVERURL;
	var url=iphost +"ftpfile/copyfile.do";
//	var url = "http://127.0.0.1:8081/DocService/ftpfile/copyfile.do";
	var foldid;
	if($.cookie('uuid')=="null"||$.cookie('uuid')==undefined||$.cookie('uuid')==""){
		foldid=uuid();
		$.cookie('uuid',foldid);
	}else{
		foldid=$.cookie('uuid');
	}
	var CopyrootPath = doctype+"/"+foldid;
	$.ajaxSetup({
		async : false //取消异步
	});
//	rootPath = "HY/copy";
	$.post(url,{source:rootPath,target:CopyrootPath}, function (result) {
		  if(result)
		  {
			  if(result.message=="复制成功")
				  copyPath = CopyrootPath;	
		  }
	});
}


function documentCopyfile(newFilePath,oldFilePath,tousername,touserid){
	var iphost=CONF_DOC_SERVERURL;
	var url=iphost +"ftpfile/copyfile.do";
	 $.ajax({
	        type: "post",
	        async: true,
	        dataType: "json",
	        url: url,
	        data: {source:oldFilePath,target:newFilePath,username:tousername,userid:touserid},
	        success: function(data) {
	        	console.log("复制附件成功。");
	        },
	        error: function(err) {
	        	console.log("get progress data fail:"+err); 
	        }
	    });
}


//加密算法
function Encrypt(str, pwd) {    
    if(str=="")return "";    
    str = escape(str);    
    if(!pwd || pwd==""){ var pwd="1234"; }    
    pwd = escape(pwd);    
      if(pwd == null || pwd.length <= 0) {    
        alert("Please enter a password with which to encrypt the message.");    
          return null;    
      }    
      var prand = "";    
      for(var I=0; I<pwd.length; I++) {    
        prand += pwd.charCodeAt(I).toString();    
      }    
      var sPos = Math.floor(prand.length / 5);    
      var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));    
      var incr = Math.ceil(pwd.length / 2);    
      var modu = Math.pow(2, 31) - 1;    
      if(mult < 2) {    
        alert("Algorithm cannot find a suitable hash. Please choose a different password. /nPossible considerations are to choose a more complex or longer password.");    
        return null;    
      }    
      var salt = Math.round(Math.random() * 1000000000) % 100000000;    
      prand += salt;    
      while(prand.length > 10) {    
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();    
      }    
      prand = (mult * prand + incr) % modu;    
    var enc_chr = "";    
    var enc_str = "";    
    for(var I=0; I<str.length; I++) {    
        enc_chr = parseInt(str.charCodeAt(I) ^ Math.floor((prand / modu) * 255));    
        if(enc_chr < 16) {    
            enc_str += "0" + enc_chr.toString(16);    
        }else    
            enc_str += enc_chr.toString(16);    
        prand = (mult * prand + incr) % modu;    
    }    
      salt = salt.toString(16);    
      while(salt.length < 8)salt = "0" + salt;    
    enc_str += salt;    
    return enc_str;    
} 
//解密算法
function Decrypt(str, pwd) {    
    if(str=="")return "";    
    if(!pwd || pwd==""){ var pwd="1234"; }    
    pwd = escape(pwd);    
      if(str == null || str.length < 8) {    
        alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");    
        return;    
      }    
      if(pwd == null || pwd.length <= 0) {    
        alert("Please enter a password with which to decrypt the message.");    
        return;    
      }    
      var prand = "";    
      for(var I=0; I<pwd.length; I++) {    
        prand += pwd.charCodeAt(I).toString();    
      }    
      var sPos = Math.floor(prand.length / 5);    
      var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));    
      var incr = Math.round(pwd.length / 2);    
      var modu = Math.pow(2, 31) - 1;    
      var salt = parseInt(str.substring(str.length - 8, str.length), 16);    
      str = str.substring(0, str.length - 8);    
      prand += salt;    
      while(prand.length > 10) {    
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();    
      }    
      prand = (mult * prand + incr) % modu;    
      var enc_chr = "";    
      var enc_str = "";    
    for(var I=0; I<str.length; I+=2) {    
        enc_chr = parseInt(parseInt(str.substring(I, I+2), 16) ^ Math.floor((prand / modu) * 255));    
        enc_str += String.fromCharCode(enc_chr);    
        prand = (mult * prand + incr) % modu;    
    }    
    return unescape(enc_str);    
} 

/**
 * 添加文件夹按钮事件
 * 
 * @param type
 *            类型
 */
var childfilename;
function adddir(type){	
	layer.open({
		  type: 2,
		  title:'输入文件夹名称',
		  shadeClose: true,
		  area: ['350px', '200px'], //宽高
		  btn: ['确认', '取消'],
		  content: CONF_FRONT_SERVERURL+"view/folder.jsp?type="+type,
		  yes:function(index,layero){
			  var name = childfilename;
			  folerFile(type,name);
		  },
		});
}
//获取创建文件页面文件名
function getfilename(name){
	childfilename = name;
}
//创建文件夹
function folerFile(type,foldname){
	var re =/^[^`~*#%|\\\][\]\{\}:;'\,.<>/?]{1,}$/;
	if(!re.test(foldname)){
		layer.msg("创建失败,目录存在特殊字符!",{icon:0});
		return;
	}
	var isOK = true;
	// 当前文件夹全路径
	var cPath = rootPath;
	if(currentPath && currentPath != ""){
		cPath = rootPath + "/" + currentPath;
	}

	var url = CONF_DOC_SERVERURL+ "ftpfile/list.do";
	$.post(url,{target:cPath}, function (result) {
		var files = result;
		if(files && files.length>0){
			for(var i=0;i<files.length;i++){
				var f = files[i];
				if(f.name == foldname){
					isOK = false;
					break;
				}
			}
		}
		if(isOK){
			userid_ = $("#userid_").val();
			if(type=="FW"&&rootPath.length==0){
				createDirInService(type,"general");
				createDirInService(type,"originaldoc");
			}
			createDirInService(type,foldname);
			layer.closeAll();
		}else {
			layer.closeAll();
			layer.msg("创建失败,目录已存在!",{icon:0});
		}
	});
}


/**
 *js截取字符串,中英文都能用
 *@param str:需要截取的字符串 
 *@param len: 需要截取的长度
 */
function cutstr(str,len)  
{  
   var str_length = 0;  
   var str_len = 0;  
      str_cut = new String();  
      str_len = str.length;  
      for(var i = 0;i<str_len;i++)  
     {  
        a = str.charAt(i);  
        str_length++;  
        if(escape(a).length > 4)  
        {  
         //中文字符的长度经编码之后大于4  
         str_length++;  
         }  
         str_cut = str_cut.concat(a);  
         if(str_length>=len)  
         {  
         str_cut = str_cut.concat("...");  
         return str_cut;  
         }  
    }  
    //如果给定字符串小于指定长度,则返回源字符串;  
    if(str_length<len){  
     return  str;  
    }  
}
/**
 * 重构附件加载方法
 */
var  hasAttachment=false;//判断当前是否存在附件
function loadAttachment(cupath){
	//用于控制控制线附件权限    lx -------------------------
	getRoleChildrenPrivilege("控制线审查");
	for(var p in listPrivilege){
		privilegeStr += listPrivilege[p].name + ",";
	}
	if(privilegeStr.indexOf("编辑") != -1){
		addfileControl = "可写";
	}else{
		addfileControl = "只读";
	}
// 用于控制控制线附件权限    lx -------------------------
	var path;
	if(cupath==undefined||cupath.length==0){
		path=rootPath;
	}else{
		path=cupath;
	}

	var rootbool = false;
	//判断传入的是否为根目录
	if(rootPath==cupath){rootbool = true;}	
	
	openPath = path;
	
	var fileList=getFileList(path);
	var node;
	
	//向上向下展开查看
	if('' !=fileList && undefined != fileList && null != fileList && fileList.length>3){
		var showMsg = "";
		 if(showFlag == "up"){
			 fileList.length=3;
			 showFlag = "down";
			 showMsg = "向下展开<span class=\"glyphicon glyphicon-arrow-down\"></span>";
		 }else{
			
			 showFlag = "up";
			 showMsg = "向上收起<span class=\"glyphicon glyphicon-arrow-up\"></span>";
		 }
		 $("#morebtn").css("display","block");
		 $("#morebtn").html(showMsg);
	}
	
	
	if(file_type=="document"){
		
		node=$(".div-attachment");
		
		//若存在附件
		if('' !=fileList && undefined != fileList && null != fileList &&fileList.length>0){
			setFileTitle(node,rootbool);
			hasAttachment=true;
			 $("#label_notice").css('display','none');
			//附件权限控制 longwending 2017.10.10
			if(addfileControl=="可写"){
				$("#addfiledir,#uploadbtn").css("display","inline-block"); 
			}else{
				 $("#addfiledir,#uploadbtn").css("display","none"); 
			}
			$("#divNoAttachment").css("display","none");
			loadFileHtml(fileList,node,cupath);
		}else{
			hasAttachment=false;
			$(".div-attachment").html("");
			$("#addfiledir,#uploadbtn").css("display","none"); 
			//没有附件的时候  这几个列表下才能上传附件  其他的则隐藏
//			if(listType=="endorsementdocumentsData"
//				||listType=="circulatedocumentsData"
//					||listType=="draftlistData"
//						||listType=="managerlistData"){
////				$("#divNoAttachment").css("display","block");
//			}else{
			var upattach_display=$("#divNoAttachment").css("display");
			//附件不可写的时候 并且上传附件的div为隐藏
			if(upattach_display=="none"&&!attachOperate){
				//不存在附件,并且上传附件不显示的时候 则提示
				$(".div-attachment").append("<div id='label_notice'><label>无上传附件</label></div>");
			
			}else{
				//不存在附件且附件可写时显示
				$("#divNoAttachment").css("display","block");
				setFileTitle(node,rootbool);
			}
//			$("#divNoAttachment ,.div-attachment").css("display","none");
//			}
		}
	}
	
	/***************hyh  新增  2017、9、20 ****************/
	else if(file_type=="hy"){
		isHY=true;
		node=$(".div-attachment");
		setFileTitle(node,rootbool);
		if(fileList!=undefined||fileList!=null){//hyh 新增  ,当服务器挂掉的时候就不执行里面的方法了  2017/10/26
		if(fileList.length>0){
			if(electronState=="retrieves")
				$(".div-document-content-right").find("button").css("display","none");
			else
				$(".div-document-content-right").find("button").css("display","");
			$("#divNoAttachment").css("display","none");
			$("#divNoMeeting").css("display","none");
			loadFileHtml(fileList,node,cupath);
		}else{
			/***********hyh  新增判断,针对纪要查询中打开时没有附件的情况下*************/
			if(electronState=="retrieves"){
				$("#divNoAttachment").css("display","none");
				$(".div-attachment-path").find("label").remove();
				$("#divNoMeeting").css("display","");
			}else{
					$("#addfiledir,#uploadbtn").css("display","none"); 
					$("#divNoAttachment").css("display","block");
			}
			$(".div-document-content-right").find("button").css("display","none");
		}
		}
	}
	//hyh 新增  公告附件
	else if(cupath.indexOf("GG")!=-1){
		node = $(".div-notice-attachment");
		isGG="true";
		
		setFileTitle(node,rootbool);
		if(fileList!=undefined||fileList!=null){//hyh 新增  ,当服务器挂掉的时候就不执行里面的方法了  2017/10/26
	    var re_size=fileList.length;
		if(fileList.length>0){
			node.html("<div><img src='../../../image/index/icon-attachment.png' style='width:14px;height:12px'/>附件("+re_size+")</div>");
			loadFileHtml(fileList,node,cupath);
			$(".div-document-content-right").find("button").css("display","");
		}else{
		    var gg_attachNumberStr="";
			gg_attachNumberStr="<img src='../../../image/index/icon-attachment.png' style='width:14px;height:12px' />附件("+re_size+")";
			node.html(gg_attachNumberStr);
		}
		}
	}
	
	//hyh 新增  审批附件
	else if(cupath.indexOf("SP")!=-1){
		//node = $(".div-document-content-right");
		isSP=true;
		node=$(".div-attachment");
		contentpath=global.contextPath;
		setFileTitle(node,rootbool);
		if(fileList!=undefined||fileList!=null){//hyh 新增  ,当服务器挂掉的时候就不执行里面的方法了  2017/10/26
	    var re_size=fileList.length;
		if(fileList.length>0){
			setFileTitle(node,rootbool);
			loadFileHtml(fileList,node,cupath);
			$(".div-document-content-right").find("button").css("display","");
			$("#addfiledir").css("display","inline-block"); 
			$("#uploadbtn").css("display","inline-block"); 
			$("#divNoAttachment").css("display","none");
		}else{
			$("#divNoAttachment").css("display","block");
			$("#addfiledir").css("display","none"); 		
			$("#uploadbtn").css("display","none"); 		
		}
		}
	}
	
	//新增    控制线附件     hufeng  20180904
	else {
		isOther=true;
		node=$(".div-attachment");
		setFileTitle(node,rootbool);
		if(fileList!=undefined||fileList!=null){//hyh 新增  ,当服务器挂掉的时候就不执行里面的方法了  2017/10/26
			if(fileList.length>0){
				setFileTitle(node,rootbool);
				loadFileHtml(fileList,node,cupath);
			}
			$(".div-document-content-right").find("button").css("display","");
			if(addfileControl == "可写"){ // 控制附件权限
				$("#addfiledir").css("display","inline-block"); 
				$("#uploadbtn").css("display","inline-block"); 
				if(fileList.length == 0 && path != ''){
					$("#addfiledir").css("display","none"); 
					$("#uploadbtn").css("display","none"); 
					$(".div-attachment-path").css("display","none");
					$("#divNoAttachment").css("display","block");
				}
			} else {
				$("#addfiledir").css("display","none"); 
				$("#uploadbtn").css("display","none"); 
				$("#delebtn").css("display","none");
				if(fileList.length == 0 && path != ''){
					$(".div-attachment-path").css("display","none");
					$("#divNoAttachment").css("display","block");
					$("#divNoAttachment").empty();
					$("#divNoAttachment").append("<div id='label_notice'><label>无上传附件</label></div>");
				}
			}
		}
	}
}
/**
 * 加载附件
 * @param fileList
 * @param node
 * @param cupath
 */
function loadFileHtml(fileList,node,cupath){
	var content;
	var item;
	for(var i=0;i<fileList.length;i++){
		item = fileList[i];
		content = jointFileDiv(item,cupath); 
		node.append(content);
	}

	 addAttachmentEvent();
}
/**
 * 重新拼接附件的html
 * hepo 20170914
 */
function jointFileDiv(item,cupath,arg){
	if(cupath.indexOf("GG")!=-1){ contentpath=global.contextPath;}//hyh 新增  2017/10/22
	// 图片类型
	var typecontent="";
	var path;
	var downloadcontent="";
	var uploadname = item["uploadUser"]==null?"":item["uploadUser"];
	var username = item["username"] || "";
	var filename = item["name"];
	
	if(item["isDir"]=="true"){// 是不是文件夹
		if(currentPath.length==0){
			path = "/"+rootPath+"/"+filename;
		}else{
			path = "/"+rootPath+"/"+currentPath+"/"+filename;
		}
		typecontent=contentpath+"/image/attachment/fileicon/folder.png";// 文件图标路径
		downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>";
	}else{// 文件则用后缀判断文件类型
		var filetype=filename.substring(filename.lastIndexOf("."),filename.length);
		typecontent=getFileType(filetype);
		if(currentPath.length==0){
			path = "/"+cupath+"/"+filename;
	//		path = "/"+rootPath+"/"+filename;
		}else{
			path = "/"+rootPath+"/"+currentPath+"/"+filename;
		}
		if(filetype.indexOf(".doc")!=-1 || filetype.indexOf(".docx")!=-1){
			downloadcontent = downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>"+
			" <span title=\"预览\" class=\"glyphicon glyphicon-eye-open\"  onclick=\"preview({filename:\'"+path+"\'})\"  ></span>"+
			" <span title=\"编辑\" class=\"glyphicon glyphicon-pencil\" onclick=\"openWindow({filename:\'"+path+"\'})\"  >" +
			"</span>";
		}else{
			downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>"+
			" <span title=\"预览\" class=\"glyphicon glyphicon-eye-open\"  onclick=\"preview({filename:\'"+path+"\'})\"  ></span>";
		}

	}
	var content = "";
	var fieldStr = "";
	if(item["isDir"]!="true"){
		fieldStr = "onclick=\"preview({filename:\'"+path+"\'})\"";
		
	}
	content ="<div class=\"div-attachment-item\"  onclick=\"clickreshlist(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\" ><img src=\""
		+typecontent+"\" /> <div class=\"div-attachment-file\"><div class=\""
		+"div-attachment-name\" "+ fieldStr +">"+item["name"]+"</div><label class=\"div-attachment-size\">"+username+" " +uploadname+"上传于"+
						item["time"]+"</label><label class=\"div-attachment-size\">" +
						"</label></div> <div class=\"div-attachment-control\" >"+downloadcontent+ 
						"<span id=\"delebtn\" title=\"删除\" class=\"glyphicon glyphicon-trash\" onclick=\"deletefile(\'"+item["name"]+"\','"+item["isDir"]+"\',event,event,'"+item["id"]+"')\"></span></div></div>";                           
	return content;
}
function setFileTitle(node,rootbool){
	var foldid=$.cookie('uuid');
	var head;
	node.children().filter('div').remove();
	var paths = currentPath.split("/");
	var pathdir="";
	var clickpath="";
	if(paths[0].length!=0){
	if(paths.length>3){
		var patgsArr = paths.slice(-3);
		var index = paths.length-3;
		for(var i=0;i<patgsArr.length;i++){
			rootbool = false;
			var pathArrStr = ""
			if(clickpath.length==0){
				for(var m=0;m<index;m++){
					if(pathArrStr.length==0)
						pathArrStr = paths[m];
					else{
						pathArrStr = pathArrStr + "/"+ paths[m];
					}				
				}
				clickpath=pathArrStr+"/"+patgsArr[i];
			}else{
				clickpath=clickpath+"/"+patgsArr[i];
			}
				patgsArr[i] = cutstr(patgsArr[i],6);
			if(pathdir.length==0){
				pathdir ="<a class=\"link\" onclick=\" backroot(\'"+clickpath+"\')\" >"+patgsArr[i]+"</a>";
			}else{
				pathdir=pathdir+"<span style=\"padding:0 5px;\">></span>"+"<a class=\"link\" onclick=\" backroot(\'"+clickpath+"\')\" >"+patgsArr[i]+"</a>";
			}
		}
	}else{
		for(var j=0;j<paths.length;j++){
			rootbool = false;
			if(clickpath.length==0){
				clickpath=paths[j];
			}else{
				clickpath=clickpath+"/"+paths[j];
			}
				//字符串大于12个长度截取
				paths[j] = cutstr(paths[j],6);
				if(pathdir.length==0){
					pathdir ="<a class=\"link\" onclick=\" backroot(\'"+clickpath+"\')\" >"+paths[j]+"</a>";
				}else{
					pathdir=pathdir+"<span style=\"padding:0 5px;\">></span>"+"<a class=\"link\" onclick=\" backroot(\'"+clickpath+"\')\" >"+paths[j]+"</a>";
				}
		    }
	  }		
    }
			if(rootbool){
				 head = "<div class=\"div-attachment-divpath\" >" +
						"<div class=\"div-attachment-path\">" +
						"<label class=\"link\" onclick=\" backroot(\'根目录\')\"><span class=\"glyphicon glyphicon-home\">" +
						"</span>根目录</label>" +pathdir +
						"</div></div>";
			}else{
			 if(paths.length>3)
				 headRoot = "<a>...</a><span style=\"padding:0 5px;\">></span>";	
			 else
				 headRoot = "<a onclick=\" backroot(\'根目录\')\"><span class=\"glyphicon glyphicon-home\"></span>根目录</a><span style=\"padding:0 5px;\">></span>";	 
			     head = "<div class=\"div-attachment-divpath\" >" +
					"<div class=\"div-attachment-path-history\">" +
					"<ul class=\"ul_none\"><li onclick=\"backDir()\"><a class=\"glyphicon\">返回上一级 </a><span style=\"padding:0 5px;\">|</span></li>" +headRoot
					+pathdir+
					"</li></ul></div></div>";
			}
		

	
	node.append(head);
}
/**
 * 调用接口 获取路径下的附件相关信息
 * hepo20170914
 */
function getFileList(path){
	 var data;
	 $.ajaxSetup({async:false});
	 $.post(CONF_DOC_SERVERURL +"ftpfile/listkzx.do",{target:path},
   		  function (result) {
		  data=result;
		  var currentPathIdUrl = CONF_DOC_SERVERURL +"ftpfile/getPathId.do";  		
		  //获取当前路径下的文件foldid以及父文件夹的id
		  $.post(currentPathIdUrl,{target:path}, function (json) {
				var data = json;
				if(json && json != ""){
					parentid = json.id;
					folderid = json.id;
				}
		   });
	 });
	return data;
}

function morelist(){
	if(serviceState == "projectAsk"){
		var currcheckbox = event.currentTarget;
		rootPath = $(currcheckbox).parent().find("#divpath").val();
		attHtml = $(currcheckbox).parent().find("#divlistId").val();
		listAttachment(rootPath+"/"+currentPath, "more");
	}else 
		if(currentPath.length!=0){
				loadAttachment(rootPath+"/"+currentPath);
		
		}else{
				loadAttachment(rootPath);
		
		}
}
/**
 * 发文来文附件上传加载
 */
function listOriginFiles(){
	var iphost=CONF_DOC_SERVERURL;
	var repath = "FW/"+$.cookie('uuid')+"/originaldoc";
	var url=iphost +"ftpfile/list.do";
	var node = $("#originattachment");
	node.children().filter('div').remove();
    $.post(url,{target:repath}, function (result) {
    	if(result.length==0){
    		//来文附件权限控制 20171025 hepo
			if(addfileControl=="可写"){
	    		$("#origin").css("display","block");
	    		$("#originhead").find("button").css("display","none");
			}else{
	    		$("#uploadOriginbtn,#origin").css("display","none");
			}
    		
    	}else{
    		
    		if(!originflag){
				loadOriginButton();
				originflag=true;
				}
    		//$("#originhead").find("button").css("display","block");
    		for(var k=0;k<result.length;k++){
   			 var item = result[k];
   			var uploadname = item["uploadUser"]==null?"":item["uploadUser"];
   			 var filename=item["name"];
   			 var path =item["path"];
   			 var username = item["username"] || "";
   			 
   			if(filename.indexOf(".doc")!=-1 || filename.indexOf(".docx")!=-1){
   				downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>"+
					"<span title=\"预览\" class=\"glyphicon glyphicon-eye-open\"  onclick=\"preview({filename:\'"+path+"\'})\"  ></span>"+
					" <span id=\"btnedit\" title=\"编辑\" class=\"glyphicon glyphicon-pencil\" onclick=\"openWindow({filename:\'"+path+"\'})\"  >" +
	   				"</span>";;
   			}else{
   				downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>"+
   			 					"<span title=\"预览\" class=\"glyphicon glyphicon-eye-open\"  onclick=\"preview({filename:\'"+path+"\'})\"  ></span>";
   			} 
   			 
   			var typecontent = contentpath+"/image/attachment/fileicon/default.png";
   			var filetype=filename.substring(filename.lastIndexOf("."),filename.length);
   			typecontent=getFileType(filetype);
//   			 var content="<div class=\"div-attachment-item\"><a class=\"a-file-name\" href=\"javascript:void(0)\" style=\" height: 40px !important; line-height: 40px !important;\" ><img style=\"width:32px\" src=\""+contentpath+"/assets/images/fileicon/doc.png\">"+item["name"]+"</a>"+" <div class=\"div-attachment-control\" style=\"line-height: 40px;\" >"+downloadcontent+ "<span id=\"delebtn\" title=\"删除\" class=\"glyphicon glyphicon-trash\" onclick=\"deletefile(\'"+item["name"]+"\','"+item["isDir"]+"\','origin',event)\"></span></div>"+"</div>"
   			content ="<div class=\"div-attachment-item\"  onclick=\"clickreshlist(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\" ><img src=\""
			+typecontent+"\" /> <div class=\"div-attachment-file\"><div class=\""
			+"div-attachment-name\" onclick=\"preview({filename:\'"+path+"\'})\">"+item["name"]+"</div><label class=\"div-attachment-size\">"+username+ " " +uploadname+"上传于"+
							item["time"]+"</label><label class=\"div-attachment-size\">" +
							"</label></div> <div class=\"div-attachment-control\" >"+downloadcontent+ "<span id=\"delebtn\" title=\"删除\" class=\"glyphicon glyphicon-trash\" onclick=\"deletefile(\'"+item["name"]+"\','"+item["isDir"]+"\','origin',event,'"+item["id"]+"')\"></span></div></div>";  
   			
   			node.append(content);
//   			if(pagetype=="3"){
//   				
//   				$(".div-attachment-control #btnedit").css("display","none"); 
//   				$(".div-attachment-control #delebtn").css("display","none"); 
//   			 }
   			 addAttachmentEvent();
    		}
    		//来文附件权限控制 20171025 hepo
			if(addfileControl=="可写"){
	    		$("#origin").css("display","none");
	    		$("#uploadOriginbtn").css("display","inline-block");
			}else{
	    		$("#uploadOriginbtn,#origin").css("display","none");
			}
    	}
    });
}

var  index_attach;

/**
 * 上传文件或创建文件夹
 * 
 * 
 * 
 * 
 * type:file或folder
 * 
 * @returns
 */
var hydoctype = "";

function upload_click(type,doctype,folderorigin){
	//else if(folderorigin=="general"){
//	createDirInService(doctype,"");
//	createDirInService(doctype,folderorigin);// 新建当前附件文件夹
//}
	hydoctype = doctype;
	if(doctype=="FW" && $.cookie('uuid')=="null"){
		createDirInService(doctype,"");
		createDirInService(doctype,folderorigin);
		
	}else if(folderorigin=="originaldoc"||folderorigin=="general"){

		createDirInService(doctype,folderorigin);// 新建当前附件文件夹
	}else{
		createDirInService(doctype,"");
	}
	
	
	
	
	if(folderorigin!=undefined){
		$("#origintext").val(folderorigin);
	}else{
		$("#origintext").val("false");
	}
   // url=encodeURI(encodeURI(contentpath+"/fileupload/upload.jsp?type="+type+"&currentPath="+rootPath+"/"+currentPath));
	var height="150px";
	if(type=="file"){
		height="178px";
	}
	//$("#_fileForm").css('display','block');
	$('#_upfile').attr('disabled',false); 
	$("#_upfile").trigger("click");
	//$("#fileBrower").trigger("click");
}

//进度条方法
function getProgress(){
	var iphost=CONF_DOC_SERVERURL;
	var now = new Date();
    $.ajax({
        type: "post",
        dataType: "json",
        url: iphost+"ftpfile/getuploadprocess.do?md5str="+md5str,
        data: now.getTime(),
        success: function(data) {
			
			if(data.message!="0%"){
				console.log("get progress data is:"+data.message);
				$(".progress-bar").width(data.message); 
			}
        },
        error: function(err) {
        	console.log("get progress data fail:"+err); 
        }
    });
}

// 判断文件是否以js..等结尾
function safe(suftype){
	// 获取可上传文件类型     将后缀改为小写  避免上传格式异常被拦截
	var suffix=suftype.toLowerCase();
	
	if("zip" == suffix || "war" == suffix ||
		"jar" == suffix || "jpg" == suffix ||
		"pdf" == suffix || "mp3" == suffix ||
		"dwg" == suffix || "doc" == suffix ||
		"docx" == suffix || "xls" == suffix ||
		"xlsx" == suffix || "ppt" == suffix ||
		"pptx" == suffix || "bmp" == suffix ||
		"gif" == suffix || "png" == suffix ||
		"svg" == suffix || "txt" == suffix ||
		"3gp" == suffix || "mp4" == suffix ||
		"avi" == suffix || "rmvb" == suffix ||
		"rm" == suffix || "mkv" == suffix ||
		"jpeg" == suffix || "cad" == suffix ||
		"wmv" == suffix || "mov" == suffix ||
		"rar" == suffix 
	){
		return true;
	}else {
		return false;
	}
}

var oTimer = null;
var md5str = "";
var filename="";
function onchangeFileName(obj){
	var fileadress = CONF_DOC_FILEADDRESURL;
	var docviewservice = CONF_DOC_VIEWSERVERURL;
	var pid = $("#pid").val();
	var state = $("#status").val();
//	var detailurl = window.location.href;//详细页面url
	
	var iphost=CONF_DOC_SERVERURL;
//	var iphost = "http://127.0.0.1:8080/DocService/";
	var origindoc=$("#origintext").val();
	var meetingNoticeAll = $("#meetingNoticeAll").val();	//会议通知默认展开标记
	filename = document.getElementById("_upfile").value;
	filename = filename.substring(filename.lastIndexOf("\\")+1, filename.length);
	
	var endwidth = filename.substring(filename.lastIndexOf(".")+1);
	
	// 判断文件是否小于0
	var fileSize = obj.files[0].size;   
	if(fileSize<=0){
		layer.msg("不允许上传空文件",{icon:2});
		return;
	}
	
	// 判断文件是否不安全
	if(safe(endwidth)){
		md5str = hex_md5(filename+new Date().getTime());
//		if(rootPath!=null&&rootPath.indexOf("FW")!=-1){
		url=iphost+"ftpfile/ncUploadfiles.do?md5str="+md5str;
//		}else{
//			 url=iphost+"ftpfile/uploadfiles.do?md5str="+md5str;
//		}
	    var uploadpath=null;
	    if(origindoc!="general"&&origindoc!=undefined){
	    	uploadpath="/FW/"+$.cookie('uuid')+"/originaldoc";
	    	folderid = getParentId("FW/"+$.cookie('uuid')+"/originaldoc");
	    }else{
	    	if(currentPath.length==0){
	    		uploadpath= "/"+rootPath;
	    		folderid = getParentId(rootPath);
	    	}else{
	    		uploadpath= "/"+rootPath+"/"+currentPath;
	    		folderid = getParentId(rootPath+"/"+currentPath);
	    	}
	    	
	    }
	   
	    var folerid_ = folderid;
	    var viewurl =uploadpath+"/"+filename;//预览url
	    $("#filepath").val(rootPath);
	    $("#_fileForm").ajaxSubmit({
	        type: "post",
	        data: {
	            'dirPath': uploadpath,
	            'viewurl':viewurl,
	            'detailurl':pid,
	            'state':state,
	            'username':username,
	            "folderid":folerid_,
	            'userid':userid,
	            'filename':filename,
	        },
	        url:url ,
	        async:true,
	        beforeSend: function() 
			{ 
	        	if(origindoc!="general"&&origindoc!=undefined){
	        		$("#lw").show();    			
	        	}else{
        			if(serviceState=="serviceyes")
            			$("#fj"+attHtml).show();
            		else if(serviceState=="serviceno")
            			fjHtml.show();
            		else
            			$("#fj").show(); 
	        	}
	        	$(".progress-bar").width('0%'); 
	        	
	        	$("#attachmentfile").hide();	
	        	$("#attachmenting").show();
        		oTimer = setInterval("getProgress()", 100);
			}, 
	        success: function (data) {
	        	//档案模块
	            $("#AMfilePath").val(rootPath);
	        	layer.msg("上传成功!",{icon:1});
	        	if(origindoc!="general"&&origindoc!=undefined){
	        		listOriginFiles();
	        	}else{       		
	        		if(currentPath.length!=0){

	        			loadAttachment(rootPath+"/"+currentPath);
	        		}else{
	        			loadAttachment(rootPath);
	        		}
	        	}
	        	
	        	$('#_fileForm').clearForm();
	        	clearInterval(oTimer);
	        	$(".progress-bar").width('100%'); 
	        	$("#attachmentfile").show();	
	        	$("#attachmenting").hide();
	        	if(origindoc!="general"&&origindoc!=undefined){
	            	$("#lw").hide();
	          
	        	}else{
	        		if(serviceState=="serviceyes")
	        			$("#fj"+attHtml).hide();
	        		else if(serviceState=="serviceno")
	        			fjHtml.hide();
	        		else	
	        			$("#fj").hide();       		
	        	}
	        	$(".progress-bar").width('0%'); 
	        	
	        	//更新时间和root
	        	if(hydoctype == "HY"){
	        		//updateHytime();
	        	}else if(hydoctype == "ZD"){
	        		updateZDRootPath();
	        	}else if(hydoctype=="SP"){
	        		
	        	}else if(hydoctype =="GG"){//hyh 新增  2017、9、29
					  updateGGrootpath();
				}else if(hydoctype =="KZX"){//新增控制线     hufeng   20180904 
					  updateKZXrootpath();
				}  
					  
				else{
	        		updaterootortime();
	        	}
	           	 	
	        },
	        error: function (msg) {
	        	if(origindoc!="false"&&origindoc!=undefined){
	        		$(".progress[id='lw']").hide();
	            	$(".progress-bar[id='lw']").width('0%'); 
	        	}else{
	        		$(".progress[id='fj']").hide();
	            	$(".progress-bar[id='fj']").width('0%'); 
	        	}
	        	
	        	layer.msg("文件上传失败!",{icon:0});  
	        	clearInterval(oTimer);
	        	$('#_fileForm').clearForm();
	        }
	    });
	}else{
		layer.msg("存在不安全因素,禁止上传",{icon:2});
		document.getElementById("_upfile").value="";
		
		/*layer.confirm('您上传的文件包含存在安全因素,确定继续上传吗?', {
		  btn: ['确定','取消'] //按钮
		}, function(){
		});*/
	}
}


function updatefjlog(pid,path){
	if(path!=undefined){
		if(path.indexOf("GG")!=-1){rootPath=path;}
	}
	var iphost=CONF_DOC_SERVERURL;
	var url=iphost+"ftpfile/updatefj.do";
	$.post(url,{rootpath:rootPath,pid:pid}, function (result) {
		console.log(result);
	});
}


/**
 * 返回上一级目录
 * 
 * @returns
 */
function backDir()
{
var pArray = currentPath.split('/');
if(pArray.length>=2){
	var path = currentPath.substring(0,currentPath.lastIndexOf("/"));
	currentPath=path;
		 loadAttachment(rootPath+"/"+currentPath);

	}else if(pArray.length==1){
		currentPath="";
			loadAttachment(rootPath);
	
	}
}

function backroot(node){
	if(node=="根目录"){
		currentPath="";
			loadAttachment(rootPath);

		
	}else{
		currentPath=node
			loadAttachment(rootPath+"/"+node);

	}
	
}

/**
 * 拼接文件列表
 * 
 * @param item
 * @returns
 */
function createFileDiv(item,isGG,action,cupath){
	
	// 图片类型
	var typecontent="";
	var path;
	var downloadcontent="";
	var uploadname = item["uploadUser"]==null?"":item["uploadUser"];
	 var username = item["username"] || "";
	if(item["isDir"]=="true"){// 是不是文件夹
		var filename = item["name"];
		if(currentPath.length==0){
			path = "/"+rootPath+"/"+filename;
		}else{
			path = "/"+rootPath+"/"+currentPath+"/"+filename;
		}
		typecontent=contentpath+"/image/attachment/fileicon/folder.png";// 文件图标路径
		downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>";
	}else{// 文件则用后缀判断文件类型
		
		var filename=item["name"];
		var filetype=filename.substring(filename.lastIndexOf("."),filename.length);
		typecontent=getFileType(filetype);
		if(currentPath.length==0){
			path = "/"+rootPath+"/"+filename;
		}else{
			path = "/"+rootPath+"/"+currentPath+"/"+filename;
		}
		if(filetype.indexOf(".doc")!=-1 || filetype.indexOf(".docx")!=-1){
			downloadcontent = downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>"+
			" <span title=\"预览\" class=\"glyphicon glyphicon-eye-open\"  onclick=\"preview({filename:\'"+path+"\'})\"  ></span>"+
			" <span title=\"编辑\" class=\"glyphicon glyphicon-pencil\" onclick=\"openWindow({filename:\'"+path+"\'})\"  >" +
//			"<a href=PageOffice://|"+global.contextPath+"/editfile.jsp?filename="+path.filename+"|width=1300px;height=730px|DlELURlHBUwPQnMwCzR6MHhDdzR5QQk/fEF/N3swZD93N38wezZ7NAtAdzk=|></a>"
			"</span>";
		}else{
			downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>"+
			" <span title=\"预览\" class=\"glyphicon glyphicon-eye-open\"  onclick=\"preview({filename:\'"+path+"\'})\"  ></span>";
		}

	}
	var content = "";
	if(electronState=="retrieves" || electronState=="zdProject"){
		var fieldStr = "";
		if(item["isDir"]!="true"){
			fieldStr = "onclick=preview({filename:\'"+path+"\'})";
			
		}
		content ="<div class=\"div-attachment-item\"  onclick=\"clickreshlist(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\" ><img src=\""
		+typecontent+"\" /> <div class=\"div-attachment-file\"><div class=\""
		+"div-attachment-name\" "+fieldStr+">"+item["name"]+"</div><label class=\"div-attachment-size\">"+username+ " " +

		
		name+"上传于"+
				item["time"]+"</label><label class=\"div-attachment-size\">" +
						"</label></div> <div class=\"div-attachment-control\" >"+downloadcontent+ "</div></div>";                   
	}else if(electronState=="elect"){
		var strclick = "";
		if(path==undefined)
			strclick= "onclick=\"preview({filename:\'"+path+"\'})\"";
		else
			strclick = "onclick=\"preview({filename:\'"+path+"\'})\"";
		
		content ="<div class=\"div-attachment-item\"  onclick=\"clickreshlist(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\" ><img src=\""
		+typecontent+"\" /> <div class=\"div-attachment-file\"><div class=\"div-attachment-name\""+strclick+">"
		+item["name"]+"</div><label class=\"div-attachment-size\">"+username+" " +uploadname+"上传于"+
				item["time"]+"</label><label class=\"div-attachment-size\">" +
						"</label></div> <div class=\"div-attachment-control\" >"+downloadcontent+ "</div></div>";

		
	}else{
		var fieldStr = "";
		if(item["isDir"]!="true"){
			fieldStr = "onclick=\"preview({filename:\'"+path+"\'})\"";
			
		}
		content ="<div class=\"div-attachment-item\"  onclick=\"clickreshlist(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\" ><img src=\""
			+typecontent+"\" /> <div class=\"div-attachment-file\"><div class=\""
			+"div-attachment-name\" "+ fieldStr +">"+item["name"]+"</div><label class=\"div-attachment-size\">"+username+" " +uploadname+"上传于"+
							item["time"]+"</label><label class=\"div-attachment-size\">" +
							"</label></div> <div class=\"div-attachment-control\" >"+downloadcontent+ "<span id=\"delebtn\" title=\"删除\" class=\"glyphicon glyphicon-trash\" onclick=\"deletefile(\'"+item["name"]+"\','"+item["isDir"]+"\',event,event,'"+item["id"]+"')\"></span></div></div>";                           
	}
	if(!gwstate)
		attachflag=true;
	if(isGG=="true"){
		var divString="";
		if(action=="1")return;
//		alert("path:"+path);
//		alert("rootPath:"+rootPath);
//		alert("filename:"+filename);
		//弹窗详情(notice-window.jsp)
		if(action=="2"){
			path=cupath;
//		content=" <div onclick=scan({filename:'"+path+"/"+item["name"]+"'})>" 
//			+"<img src=\""+typecontent+"\" /> "+item["name"]+"</div>";
		
		content ="<div class=\"div-attachment-item\"  onclick=\"clickreshlist(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\" ><img src=\""
		+typecontent+"\" /> <div class=\"div-attachment-file\">" +
				"<div class=\"div-attachment-name\" onclick=\"preview({filename:\'/"+item["name"]+"\'})\">"+item["name"]+"</div>" +
						"<label class=\"div-attachment-size\">"+username+" " +uploadname+"上传于"+
						item["time"]+"</label><label class=\"div-attachment-size\">" +
						"</label></div> <div class=\"div-attachment-control\" >"+downloadcontent+
		 "<span id=\"delebtn\" title=\"删除\" class=\"glyphicon glyphicon-trash\" onclick=\"deletefile(\'"+item["name"]+"\','"+item["isDir"]+"\',event,event,'"+item["id"]+"')\"></span></div></div>";                           

		}else{				
		 //新建或者编辑action=="3"时可以进行删除,若为查看状态则不能删除
			if(action==="lookover"){
				divString="";
				
			}else{
				divString=" <div class='div-notice-add-fileremove' onclick=\"deletefile(\'"+item["name"]+"\','"+item["isDir"]+"\',event,event,'"+item["id"]+"')\">" 
//            	+"<label class=\"div-attachment-size\">" +item["size"]+"</label>"
            	+"<span class='glyphicon glyphicon-trash' style='display:none;'></span>" 
            	+"</div>";
			}
		 content="<div class='div-notice-attachment-item' onclick=\"preview({filename:\'"+path+"\'})\" >"
            	+"<img src=\""+typecontent+"\" /> "
            	+" <div class='div-notice-add-filename'>"+item["name"]+"</div>"
            	+divString
            	+"</div>";
		}
	}else{
		//不是公告附件的情况下执行按钮加载(如发文、收文等表单界面的附件按钮)
		 if(!attachflag){
//				loadAttachButton(cupath);
				attachflag=true;
				}
	}
	return content;
}

function openWindow(item){
	
	var filename = item.filename
	var encodename = encodeURI(encodeURI(filename));
	var url = $("#linkUrl").attr('href');
	url = url.replace("***",encodename);
//	var basepath = $("#basepath").val();
//	var url = "PageOffice://|"+basepath+"/editfile.jsp?name="+encodename+"|width=1300px;height=730px;|DlELURlHBUwPQnNEZzN4MgkyZkB6P2QwZC4JNAlBZjF7Q3wwe0J2RGQvfTk=|";
	window.location.href = url;

	
}


/**
 * 点击文件夹刷新列表
 * 
 * @param filename
 *            文件夹名称
 * @param isDir
 *            是否为文件夹
 * @returns
 */
function clickreshlist(filename,isDir,e){
	e = window.event || e;
    if (e.stopPropagation) {
        e.stopPropagation();
        if(isDir=="true"){
    		if(currentPath.length==0){
    			currentPath=filename;
    		}else{
    			currentPath=currentPath+"/"+filename;
    		}
				loadAttachment(rootPath+"/"+currentPath);
		
    	}
    } else {
        e.cancelBubble = true;
    }
}

/**
 * 删除文件
 * 
 * @returns
 */
function deletefile(filename,isDir,origin,e,id){
	var iphost=CONF_DOC_SERVERURL;	
	e = window.event || e;
    if (e.stopPropagation) {
        e.stopPropagation();
        var url=iphost +'ftpfile/delete.do';
        var dirpath=null;
        if(origin!="origin"){
        	if(currentPath=="")
        		dirpath="/"+rootPath+"/"+currentPath;
        	else
        		dirpath="/"+rootPath+"/"+currentPath+"/"
        }else{
        	dirpath="/FW/"+$.cookie('uuid')+"/originaldoc/";
        }
        var viewurl =CONF_DOC_VIEWSERVERURL+ encodeURI(CONF_DOC_FILEADDRESURL+dirpath+"/"+filename);//预览url
//        var userid = getUserId();
        layer.open({
    		content: '是否删除文件?',
    		btn: ['确认', '取消'],
    		shadeClose: true,
    		icon: 3,
    		yes: function(){
    			$.post(url,{filename:filename,
    						dirPath:dirpath,
    						username:username,
    						userid:userid,
    						id:id,
    						isDir:isDir}, function (result) {
    	    		  if(result.message=="删除成功!")
    	    		  {
    	    			  if(origin!="origin"){
    	    				  if(currentPath.length!=0){
    	    							loadAttachment(rootPath+"/"+currentPath);
    	    					
    	        			  }else{
    	        						loadAttachment(rootPath);
    	        				
    	        			  }	 
    	    			  }else{
    	    				  listOriginFiles();
    	    			  }
    	    			  layer.msg(result.message,{icon:6}); 
    	    		  return;
    	    		  }else{
    	    			  layer.msg(result.message,{icon:0}); 
    	    		  }
    	    	});
    		}
    	});
        
    } else {
        e.cancelBubble = true;
    }
}

/**
 * 下载文件
 * 
 * @returns
 */
function downloadfile(params,e){
	e = window.event || e;
	if (e.stopPropagation) {
		e.stopPropagation();
		var iphost=CONF_DOC_SERVERURL;
		var url = iphost+"ftpfile/downloadfile.do";	
		var temp = document.createElement("form");
		temp.action = url;
		temp.method = "post";
		temp.style.display = "none";
		for (var x in params) {
			var opt = document.createElement("textarea");
			opt.name = x;
			opt.value = params[x];
			temp.appendChild(opt);
		}
		document.body.appendChild(temp);
		temp.submit();
		return temp;
	}else {
		e.cancelBubble = true;
	}
}


function preview(params){
	var fileadress = params["filename"];
	var filedir = fileadress.substring(fileadress.lastIndexOf("/")+1,fileadress.length);
	var protocol = window.location.protocol;
	var host= protocol + "//" + window.location.host;
//	var filename=params["filename"];
//	var name = filename.substring(filename.lastIndexOf("/")+1,filename.length);
//	var url = host+"/file"+filename;
	$('#fileUrl').val(url);
	$('#filename').val(name);
	var strs= new Array(); // 定义一数组
	strs=filename.split("."); 
/*	if(filename!="undefined"){
		if(strs[strs.length-1]=='pdf'){	
			layer.open({
				  type: 2,
				  title: name,
				  shadeClose: true,
				  maxmin : true,
				  shade: 0.6,
				  area: ['80%', '90%'],
				  content: "../../../libs/PDFViewer/web/viewer.html?file="+url
				});	
			console.log('pdf单独预览---'+name);
		}*/
//		else{	
			var fileadress = CONF_DOC_FILEADDRESURL;
			var docviewservice = CONF_DOC_VIEWSERVERURL;//附件在線預覽
			var url = fileadress+params["filename"];
			var path = params["filename"];
			var name = path.substring(path.lastIndexOf("/")+1,path.length);
			var encodeurl = encodeURIComponent(url);
	//		var encodeurl = encodeURIComponent(encodeURIComponent(url));
			var encodename = encodeURIComponent(encodeURIComponent(name));

			parent.layer.open({
				  type: 2,
				  title: name,
				  shadeClose: true,
				  maxmin : true,
				  shade: 0.6,
				  area: ['80%', '90%'],
				  content: docviewservice+encodeurl
				  
				});
				
			
			//改为弹窗预览
//			window.open("../../previewAttachment.jsp?fileUrl="+encodeurl+"&filename="+encodename+"&openPath="+openPath);
//		}
//	}
	
}
/**
 * 公告预览文档
 * 
 * @param params
 */
function scan(params){
	var fileadress = CONF_DOC_FILEADDRESURL;
	var docviewservice = CONF_DOC_VIEWSERVERURL;
	var url = fileadress+params["filename"];
	var path = params["filename"];
	var name = path.substring(path.lastIndexOf("/")+1,path.length);
	if(path!="undefined"){
		parent.layer.open({
			  type: 2,
			  title: name,
			  shadeClose: true,
			  shade: 0.6,
			  area: ['80%', '90%'],
			  content: docviewservice+encodeURI(url)
			}); 
	}
	
}
/**
 * 弹出层形式预览文档
 * 
 * @param params
 */
var layerindex = 0;
function getlayer() {
	return layerindex;
}

function openlayerdoc(params){
	var fileadress = params["filename"];
	var filedir = fileadress.substring(fileadress.lastIndexOf("/")+1,fileadress.length);
	var protocol = window.location.protocol;
	var host= protocol + "//" + window.location.host;
	var docviewservice = $("#docviewservice").val();//附件在線預覽
	var filename=params["filename"];
	var name = filename.substring(filename.lastIndexOf("/")+1,filename.length);
	var url = host+"/file"+filename;
	$('#fileUrl').val(url);
	$('#filename').val(name);
	var strs= new Array(); // 定义一数组
	strs=filename.split("."); 
	if(filename!="undefined"){
		/*if(strs[strs.length-1]=='pdf'){	
			layer.open({
				  type: 2,
				  title: name,
				  shadeClose: true,
				  shade: 0.6,
				  area: ['80%', '90%'],
				  content: "../../../common/js/pdf/web/viewer.html?file="+url
				});	

		}
		else{
			if(filename!="undefined"){*/
				layerindex = layer.open({
					  type: 2,
					  title: name,
					  shadeClose: true,
					  shade: 0.6,
					  area: ['80%', '90%'],
			//		  content: "../../attachment.jsp"
					  content: docviewservice+encodeURI(url)
			//		  content:"../../previewAttachment.jsp?fileUrl="+params.encodeurl+"&filename="+params.encodename+"&openPath="+params.openPath
					});
			
			//}
//			parent.layer.msg('该类型文件无法在线预览',{icon:2});
//			return;
		//}
	}
	
}
//新增公告更新主表 
function updateGGrootpath(){
	var status=$("#status").val();	
	var announcementtype=jQuery("#Select1  option:selected").text();
	var title =$("#title").val();
	var content=$("#content").val();
	var filepath=$("#filepath").val();
			var arg= {
					announcementtype:announcementtype,
					title:title,
					content:content,
					action:"edit",
					gid:gid,
					filepath:rootPath
			};
			
			var dataArg=JSON.stringify(arg);
			$.ajax({
				 type: "POST",
				   async: false,
				   url: CONF_BACK_SERVERURL + global.modelctls.homepage.alter,
				   headers:{
			    		"token":$.cookie('ftoken')
				    },
				   data:{data:dataArg},
				   success: function(result){
						console.log("主表附件路径更新成功");
					},
					error:function(XMLHttpRequest, textStatus, errorThrown){
						console.log("主表附件路径更新失败");
						console.log(errorThrown);
					}
			});
}


/**
 * 更新控制线审查表的附件路径    hufeng 20180904
 */
function updateKZXrootpath(){
	var id=$("#id").val();	
	if(id!=""){
		$.ajax({
			url:CONF_CONTROLLINE_SERVIERURL+ global.modelctls.controlline.update,
			data:JSON.stringify({id:id,annexpath:rootPath}),
			type:"post",
			contentType: "application/json;charset=UTF-8",
			dateType:"json",
			success:function(result){
				console.log("主表附件路径更新成功");
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				console.log("主表附件路径更新失败");
				console.log(errorThrown);
			}
		})
	}
}
/**
 * 更新主表的根路径和更新时间
 */
function updaterootortime(){
	var status=$("#status").val();	
	
	 if(pid==""||pid==undefined||pid==null){pid=$("gid").val();} //hyh  注释   附件用只用gid  2017、9、29
		if(pid!=undefined){
			var arg = {
					"id":pid,"docattachmentpath":rootPath
					//"id":gid,"filepath":rootPath
			};
			$.ajax({
				 type: "POST",
				   async: false,
				   contentType:"application/json",
				   url: CONF_DOCUMENT_SERVIERURL + global.modelctls.document.updateForm,
				   data: JSON.stringify(arg),
				   //dataType: "json",//请求参数类型
				   success: function(data){
						console.log("主表附件路径更新成功");
					},
					error:function(XMLHttpRequest, textStatus, errorThrown){
						console.log("主表附件路径更新失败");
						console.log(errorThrown);
					}
			});
//		$.post(global.contextPath + global.modelctls.document.updateroot,
//			 {pid:pid,rootpath:rootPath},
//				 function (result) {
//				 
//		       });
		}
}


function updateHytime(){
	var projectId=$("#projectId").val();	
	if(projectId!=""){
		$.post(global.contextPath+"/mvc/meetingProject/updateroot.do",
			 {projectId:projectId,rootpath:rootPath},
				 function (result) {
		       });
	}
}

//更新附件操作信息表
//参数pid ,rootpath 根路径
//
function fujianEvent(){
	//显示删除图标
    $(".div-notice-attachment-item").mouseover(function (evt) {
        $(evt.currentTarget).css("background-color", selectedbg);
        $(".div-notice-add-fileremove").show("fast");
//        $(evt.currentTarget).find(".glyphicon-trash").show("fast");
//        $(evt.currentTarget).find(".glyphicon-eye-open").show("fast");
//        $(evt.currentTarget).find(".div-notice-add-fileremove span").slideDown("fast", function () {
//            if ($(this).parent().parent().css("background-color") == selectedbg) {
//                $(this).hide("fast");
//            }
//        });
        $(evt.currentTarget).find(".div-notice-add-fileremove span").css("display","inline");
    });
    $(".div-notice-attachment-item").mouseleave(function (evt) {
        $(evt.currentTarget).css("background-color", "white");
//        $(evt.currentTarget).find(".glyphicon-trash").hide("fast");
//        $(evt.currentTarget).find(".glyphicon-eye-open").hide("fast");
        $(evt.currentTarget).find(".glyphicon-trash").css("display","none");
        $(evt.currentTarget).find(".glyphicon-eye-open").css("display","none");
    });
    //删除事件
//    $(".div-notice-add-fileremove").click(removeNotice);
}

/**
 * 生成UUID
 * 
 * @returns uuid
 */
function uuid(){
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
	s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the
														// clock_seq_hi_and_reserved
														// to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
	}



/*
 * 获取登录用户id
 */
function getParentId(rootPath){
	var id = "-1";
	$.ajaxSetup({
		async : false // 取消异步
	});	
	var currentPathIdUrl = CONF_DOC_SERVERURL +"ftpfile/getPathId.do";
	var path_ = rootPath;
	$.post(currentPathIdUrl,{target:path_}, function (json) {
		var data = json;
		if(json && json != ""){
			id = json.id;
		}
	});
    return id; 
}

/**
 * 获取用户ID
 * @returns
 */
function getUserId(){
//	var id = null;
//	$.ajaxSetup({
//		async : false // 取消异步
//	});	
//	$.post(global.contextPath + global.modelctls.user.loginInfo, function (result) {
//		if(result==null||result==undefined){return;}
//		id = result.data.user.id;
//     })
//	alert(logginUserId);
//  return $("#logginUserId").val(); 
}

/**
 * 是否含有附件,是否上传
 * @returns
 */
function attachYn(){
	var iphost=CONF_DOC_SERVERURL;
	var foldid;
	var path;
	var bool;
	if($.cookie('uuid')=="null"||$.cookie('uuid')==undefined||$.cookie('uuid')=="")
		bool = "false";	
	else{
		foldid=$.cookie('uuid');
		path = "SP/"+foldid;
		var url=iphost +"ftpfile/list.do";
		$.post(url,{target:path}, function (result) {
		    	if(result.length==0)
		    		bool = "false"	
		    	else
		    		bool = "true";
		    });
	}
	return bool;
}



//重点项目服务记录附件
function createServiceDiv(item,cupath){	
		// 图片类型
		var typecontent="";
		var path;
		var downloadcontent="";
		var uploadname = item["uploadUser"]==null?"":item["uploadUser"];
		 var username = item["username"] || "";
		if(item["isDir"]=="true"){// 是不是文件夹
			typecontent=contentpath+"/assets/images/projecttask/folder.png";// 文件图标路径
			downloadcontent="<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},event)\" ></span>";
		}else{// 文件则用后缀判断文件类型
			
			var filename=item["name"];
			var filetype=filename.substring(filename.lastIndexOf("."),filename.length);
			typecontent=getFileType(filetype);
			path = "/"+cupath+"/"+filename;
			downloadcontent=" <span title=\"预览\" class=\"glyphicon glyphicon-eye-open\"  onclick=\"preview({filename:\'"+path+"\'})\"  ></span>"+"<span id=\"downloadbtn\" title=\"下载\" class=\"glyphicon glyphicon-save\"  onclick=\"downloadfile({filename:\'"+path+"\'},e)\" ></span>";
			
		}
		var fieldStr = "";
		if(item["isDir"]!="true"){
			fieldStr = "onclick=preview({filename:\'"+path+"\'})";
			
		}
		var	content ="<div class=\"div-attachment-item\"  onclick=\"clickreshlist(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\" ><img src=\""
			+typecontent+"\" /> <div class=\"div-attachment-file\"><div class=\""
			+"div-attachment-name\" "+ fieldStr +">"+item["name"]+"</div><label class=\"div-attachment-size\">"+username+" " +uploadname+"上传于"+
							item["lastUpdateTime"]+"</label><label class=\"div-attachment-size\">" +
							"</label></div> <div class=\"div-attachment-control\" >"+downloadcontent+ "<span id=\"delebtn\" title=\"删除\" class=\"glyphicon glyphicon-trash\" onclick=\"deletefile(\'"+item["name"]+"\','"+item["isDir"]+"\',event)\",event,'"+item["id"]+"')\"></span></div></div>";                         
		return content;
}

/**
 * 获取附件的后缀名 并匹配相应的图片
 * 20171101 hepo
 */
function getFileType(filetype){
	var typecontent="";
	//默认用小写字符串
	filetype=filetype.toLowerCase(); 
	if(filetype==".doc"||filetype==".docx"){
		typecontent=contentpath+"/image/attachment/fileicon/doc.png";
	}else if(filetype==".pdf"){
		typecontent=contentpath+"/image/attachment/fileicon/pdf.png";
	}else if(filetype==".ppt"||filetype==".pptx"){
		typecontent=contentpath+"/image/attachment/fileicon/ppt.png";
	}else if(filetype==".jpg"||filetype==".png"||filetype==".gif"||filetype==".jpeg"||filetype==".bmp"){
		typecontent=contentpath+"/image/attachment/fileicon/jpg.png";	
	}else if(filetype==".xls"||filetype==".xlsx"){
		typecontent=contentpath+"/image/attachment/fileicon/xls.png";
	}else if(filetype==".zip"||filetype==".rar"){
		typecontent=contentpath+"/image/attachment/fileicon/zip.png";
	}else if(filetype==".txt"){
		typecontent=contentpath+"/image/attachment/fileicon/txt.png";
	}else if(filetype==".cad"){
		typecontent=contentpath+"/image/attachment/fileicon/cad.png";
	}else if(filetype==".avi"||filetype==".wmv"||filetype==".mov"||filetype==".mp4"){
		typecontent=contentpath+"/image/attachment/fileicon/avi.png";
	}else {
		typecontent=contentpath+"/image/attachment/fileicon/default.png";
	}
	return typecontent;
}
/**
 * 档案模块:清除附件栏残留的操作
 * 
 */
function clear_operation(){
	$(".div-attachment-divpath").css("display","none");
	$(".div-attachment-path").css("display","none");
	$(".div-attachment-item").css("display","none");
	$(".div-no-attachment").css("display","block");
	rootPath = "AM/"+uuid();
}

/**
 * 附件大于20M时,不使用预览
 */
function moreThan20M(fileSize){
	if(fileSize){
		if(fileSize.indexOf('G')!=-1){
			return true;
		}else if(fileSize.indexOf('M')!=-1){
			var size=parseFloat(fileSize.replace('M',''));
			if(size>20)return true;
		}
	}
	return false;
}
function allowPreviewOrNot(){
	$('.div-attachment .div-attachment-item').each(function(i){
		var fileSize=$(this).find('.div-attachment-file .div-attachment-size:last').text()
		if(moreThan20M(fileSize)){
			$(this).find('.div-attachment-control span.glyphicon-eye-open').remove();
			$(this).find('.div-attachment-file .div-attachment-name').removeAttr('onclick').css("cursor","default");;
		}
	})
}


// 按钮
function loadAttachButton(attachpath) {

	var doctype = "";
	if (attachpath.indexOf("FW") != -1||attachpath.indexOf("发文") != -1) {
		doctype = "FW";
	} else if (attachpath.indexOf("HY") != -1) {
		doctype = "HY";
	} else if (attachpath.indexOf("SW") != -1||attachpath.indexOf("收文") != -1) {
		doctype = "SW";
	} else if (attachpath.indexOf("XJ") != -1||attachpath.indexOf("信件") != -1) {
		doctype = "XJ";
	} else if (attachpath.indexOf("officehelper") != -1) {
		doctype = "officehelper";
	} else if (attachpath.indexOf("SP") != -1) {
		doctype = "SP";
	} else if (attachpath.indexOf("CY") != -1||attachpath.indexOf("传阅") != -1) {
		doctype = "CY";
	}else if (attachpath.indexOf("DA") != -1) {
		doctype = "DA";
	}
	//新增控制线审查    hufeng  20180904
	else if (attachpath.indexOf("KZX") != -1) {
		doctype = "KZX";
	} 
	
	else {
		doctype = "other";
	}
	var clickStr = "";
	if(doctype=="FW"){
		clickStr =  "onclick=\"upload_click('file','"+ doctype+"','general";
	}else{
		clickStr =  "onclick=\"upload_click('file','"+ doctype;
	}
	if(typeof(listType) == "undefined"
		||doctype == "KZX"){		
		// 附件按钮		
		$("#_fileForm ").before(
				"<button id='addfiledir' style='display:none;' class=\"btn btn-info\" onclick=\"adddir('"
						+ doctype
						+ "')\">"
						+ "<span class=\"glyphicon glyphicon-folder-close\"></span>创建文件夹"
						+ "</button>"
						+ "<button  style='display:none;' class=\"btn btn-info progress-button\" id=\"uploadbtn\""
						+ clickStr
						+ "')\" data-style=\"fill\""
						+ "data-horizontal>"
						+ "<span class=\"glyphicon glyphicon-file\"></span>上传文件"
						+ "</button>");
	}else if (listType=="endorsementdocumentsData"
			||listType=="circulatedocumentsData"
			||listType=="draftlistData"
			||listType=="managerlistData"){
		$("#_fileForm ").before(
				"<button id='addfiledir' style='display:none;' class=\"btn btn-info\" onclick=\"adddir('"
						+ doctype
						+ "')\">"
						+ "<span class=\"glyphicon glyphicon-folder-close\"></span>创建文件夹"
						+ "</button>"
						+ "<button  style='display:none;' class=\"btn btn-info progress-button\" id=\"uploadbtn\""
						+ clickStr
						+ "')\" data-style=\"fill\""
						+ "data-horizontal>"
						+ "<span class=\"glyphicon glyphicon-file\"></span>上传文件"
						+ "</button>");
	}


}

//附件操作
function addAttachmentEvent() {
	users = JSON.parse($.cookie('cookieuser'));
	roles=users.roles;
    $(".div-attachment-control").css("display","block");
    if(addfileControl=="可写"){
    }
    else{
        $(this).find(".div-attachment-control #delebtn").css("display","none");
    }
    //公告附件按钮权限设置
    if ('undefined'!=typeof isGG && isGG==true){
        for (var i in roles){
            var rol=roles[i].name;
            if(rol=="管理员"||rol=="学习园地管理员"){
                $(this).find(".div-attachment-control #delebtn").css("display","");
                break;
            }else{
                $(this).find(".div-attachment-control #delebtn").css("display","none");
            }
        }
    }
    $('.div-document-content-right div[name="removerbtn"]').attr("onclick","morelist()");
	return;
// 		$(".div-attachment-item").mouseover(function () {
// 			//查询时不显示附件操作按钮     hufeng  20180711
// 			if(addfileControl=="可写"){
// 				$(this).find(".div-attachment-control").css("display","block");
// 			}
// //			else if(isSP||isHY||isGG||isOther){// isOther 新增,为控制线审查,以及以后的通用判断    20180905
// //				$(this).find(".div-attachment-control").css("display","block");
// //			}
// 			else{
// 				$(this).find(".div-attachment-control").css("display","block");
// 				$(this).find(".div-attachment-control #delebtn").css("display","none");
// 			}
// 			//公告附件按钮权限设置
// 			if ('undefined'!=typeof isGG && isGG==true){
// 				for (var i in roles){
// 					var rol=roles[i].name;
// 					if(rol=="管理员"||rol=="学习园地管理员"){
// 						$(this).find(".div-attachment-control #delebtn").css("display","");
// 					break;
// 					}else{
// 						$(this).find(".div-attachment-control #delebtn").css("display","none");
// 					}
// 				}
//
// 			}
//
// 		});
// 		$(".div-attachment-item").mouseleave(function (evt) {
// 			$(this).find(".div-attachment-control").css("display","none");
// 		});
// 		$('.div-document-content-right div[name="removerbtn"]').attr("onclick","morelist()");
}

function removerMouseover(){
	 $(".div-attachment-item").unbind("mouseover");
	 $('.div-document-content-right div[name="removerbtn"]').removeAttr("onclick");
	 $(".div-attachment-item").removeAttr("onclick");
	 $(".div-attachment-item .div-attachment-name").removeAttr("onclick");
}