
var menuCtrl = {};
menuCtrl.init = function(){
	this.setShowType();
	this.getFile();
	this.initSearch();
	this.addRightClick();
}
menuCtrl.regFolder = new RegExp('^[^\\\\\\/:*?\\"<>|]+$'); //正则验证是否是文件夹
/***
*新建文件夹
***/
menuCtrl.addFile = function () {
    var that = this;
	if(!that.getRole($("#H_rootRole").val(),"add")){
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	var d = dialog({
        title: "新建文件夹",
        content: '<table width="100%" border="0"><tr><td valign="top">输入新名称：</td>\
				<td><input type="text" class="dialog-input" id="newName"  autofocus="autofocus"\
				size="24" maxlength="96" /></td></tr><tr><td valign="top" style="padding-top: 10px;">目录描述：</td><td style="padding-top: 10px;"><textarea id="newNote" \
				cols="22" rows="3" class="dialog-textarea"></textarea></td></tr></table>',
        statusbar: "<span class='dialog-error' id='addError'></span>",
        button: [
        {
            value: '保存并新建',
            callback: function () {
                //验证表单
                var ajaxData = checkForm();
                if (ajaxData == false) {
                    return false;
                }
                sendAjax(ajaxData, function () {
                    //将表单设置为空
                    $(".dialog-input,.dialog-textarea").val("");
                    $(".dialog-error").html("<span style='color:#009933;'>新建目录成功</span>");
					getTree();
                    that.getFile();
                });
                return false;
            },
            autofocus: true
        },
        {
            value: '确定',
            callback: function () {
                var ajaxData = checkForm();
                if (ajaxData == false) {
                    return false;
                }
                sendAjax(ajaxData, function () {
                    that.getFile();
					getTree();
                    //关闭弹出窗口
                    d.close().remove();
                });
                return false;
            },
            autofocus: true
        },
        {
            value: '取消'
        }
    ]
    });
    d.showModal();
	$("#newName").focus();
    // 验证表单
    function checkForm() {
        var error = $("#addError").html("");
        var newName = $.trim($("#newName").val());
        var newNote = $.trim($("#newNote").val());
        var path = $("#H_path").val();
        var pid = $("#H_pid").val(); //
        var GGUser = $("#H_GGUser").val(); //公共空间用户名
        pid = pid == '' ? '/' : pid;
        if (newName == "") {
            error.html("文件名称不能为空");
            return false;
        }
        if (!that.regFolder.test(newName)) {
            error.html("文件名称格式不对");
            return false;
        }
        return { newName: encodeURI(newName), newNote: encodeURI(newNote), filepath: encodeURI(path), pid: pid,gguser:encodeURI(GGUser) };

    }
    //提交表单
    function sendAjax(ajaxData, callback) {
        $.ajax({
            url: "FileSpaceHandler.ashx?cmd=AddFolder&user=" + encodeURI(sessionUser),
            type: "POST",
            data: ajaxData,
			cache :false,
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {

                    typeof callback == "function" && callback();
                } else {
                    $(".dialog-error").html(data.msg)
                }
            }
        })
    }
}          
/***
*显示上传文件窗口
***/
menuCtrl.showUploadFile = function() {
	var that = this;
	if(!that.getRole($("#H_rootRole").val(),"add")){
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	//如果窗口不存在，则绘制
	if(this.iframeDialog){
		this.iframeDialog.close().remove();
	}
	var d = this.iframeDialog = dialog({
	    content: "<iframe src='upload.aspx?user=" + encodeURI(sessionUser) + "&Path=" + encodeURI($("#H_path").val()) + "' frameBorder='0' style='border:none;width:800px;height:500px;'></iframe>",
		title : "上传文件" , 
		oniframeload : function(){
		}
	});
	d.showModal();
}
/***
*关闭上传文件窗口
***/
menuCtrl.closeUploadFile = function(flag){
	if(this.iframeDialog){
		this.iframeDialog.close().remove();
		this.iframeDialog = null ;
	}
	if(flag){
		this.getFile();
		/*var d = dialog({content:flag});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);*/
	}
}
menuCtrl.addRightClick = function(){
	var that = this ;
	// 复制内容
	var copyAddress = "" ;
	//复制地址内容
	$('.menuBlock #copyAddress').zclip({
		path: "js/ZeroClipboard.swf",
		copy: function(){
			var checkTag = $("#fileList [name='checkItem']:checked") ;
			if(!that.getRole(checkTag.data("role"),"all")){
				copyAddress ="";
				var d = dialog({content:"您选择的文件没有权限进行该操作！"});
				d.showModal();
				setTimeout(function () {
					d.close().remove();
				}, 2000);
			}
			return copyAddress;
　　　 　　},
		afterCopy:function(){
			if(copyAddress !=""){
				var d = dialog({
					content: '复制成功'
				});
				d.showModal();
				setTimeout(function () {
					d.close().remove();
				}, 2000);
			}
		}
	});
	
	// 右键菜单的时间绑定
	$(".menuBlock #fileList").live('contextmenu', function (e) {
		e.preventDefault();
		$.fn.menu.defaults.zIndex = 100 ;
		
		if(isCopy()){
			
			// 单选，开启某些功能
			$(".isCopy").removeClass("disabled").siblings().show();
			// 设置复制地址
			copyAddress =location.host+"/"+ $("#fileList [name='checkItem']:checked").parents("li").find("a.files").attr("href") ;
			if(isFolder()){
				$(".isFolder").addClass("disabled").siblings().show();
				$(".isFile").removeClass("disabled").siblings().show();
			}else{
				$(".isFolder").removeClass("disabled").siblings().show();
				$(".isFile").addClass("disabled").siblings().show();
			}
		}else{
			if(isFolder()){
				$(".isFolder").addClass("disabled").siblings().show();
			}else{
				$(".isFolder").removeClass("disabled").siblings().show();
			}
			copyAddress = "";
			$(".isCopy").addClass("disabled").siblings().hide();
		}
		// 设置右键菜单的位置
		$('#right_mm').menu("show", {
			left: e.pageX,
			top: e.pageY
		})
	});
	// 下载文件
	$(".menuBlock #download").bind("click",function(){
		if(!$(this).hasClass("disabled")){
			$("#fileList [name='checkItem']:checked").parents("li").find("a.files").each(function(){
				this.click();
				});
		}
	});
	//删除文件
	$(".menuBlock #delete").bind("click",function(){
		that.removeFile();
	});
	//新建文件夹
	$(".menuBlock #addFolder").bind("click",function(){
		that.addFile();
	});
	//判断是否单选
	function isCopy(){
		return $("#fileList [name='checkItem']:checked").size() == 1 ;
	}
	function isFolder(){
		var flag = true;
		$("#fileList [name='checkItem']:checked").each(function(){
			if($(this).data("folder") != "1"){
				flag = false ;
			}
		});
		return flag;
	}
	// 提取文件
	$(".menuBlock #extractFile").bind("click",function(){
		that.extractFile();
	});
	//转发文件
	$(".menuBlock #forwardFile").bind("click",function(){
		that.forwardFile();
	});
	//发布文件
	$(".menuBlock #sharaOutFile").bind("click",function(){
		that.sharaOutFile();
	});
	//共享文件
	$(".menuBlock #sharaFile").bind("click",function(){
		that.sharaFile();
	});
	// 注释
	$(".menuBlock #notes").bind("click",function(){
		if($(this).hasClass("disabled")){
			return false;
		}
		var checkTag = $("#fileList [name='checkItem']:checked") ;
		if(!that.getRole(checkTag.data("role"),"all")){
			var d = dialog({content:"您选择的文件没有权限进行该操作！"});
			d.showModal();
			setTimeout(function(){d.close().remove();},2000);
			return false ;
		}
		var d = dialog({
			 content: '<table width="100%" border="0"><tr><td valign="top">文件名称：</td>\
				<td>'+checkTag.parents("li").find("a.files").text()+'</td></tr><tr><td valign="top" style="padding-top: 10px;">注释内容:</td><td style="padding-top: 10px;"><textarea id="newNote" \
				cols="22" rows="3" class="dialog-textarea">'+checkTag.parents("li").find(".remark").html()+'</textarea></td></tr></table>',
			statusbar: "<span class='dialog-error' id='addError'></span>",
			title : "注释文件",
			button: [
				 {
					value: '确定注释',
					callback: function () {
						var note = $.trim($("#newNote").val());
						var error = $("#addError").html("");
						$.ajax({
						    url: "FileSpaceHandler.ashx?cmd=AddRemark",
						    data: { fileId: checkTag.val(), remark: encodeURI(note), user: encodeURI(sessionUser) },
							dataType:"json",
							cache: false,
							success : function(data){
								if(data.code == 0 ){
									error.html("<span style='color:#009933;'>注释成功</span>");
									checkTag.parents("li").find(".remark").html(note);
								}else{
									error.html(data.msg);
								}
								setTimeout(function(){d.close().remove();},2000);
							}
						})
						return false ;
					},
					autofocus: true
				},{
					value: '取消',
					callback: function () {
						return true;
					},
					autofocus: true
				},
			]
		});
		d.showModal();
	});
	// 重命名
	$(".menuBlock #rename").bind("click",function(){
		if($(this).hasClass("disabled")){
			return false;
		}
		var checkTag = $("#fileList [name='checkItem']:checked") ;
		if(!that.getRole(checkTag.data("role"),"all")){
			var d = dialog({content:"您选择的文件没有权限进行该操作！"});
			d.showModal();
			setTimeout(function(){d.close().remove();},2000);
			return false ;
		}
		var name = checkTag.parents("li").find("a.files").text();
		var tname = checkTag.data("folder") == "0" ? name.substr(0,name.lastIndexOf(".")) :name ;
		var d = dialog({
			content : '<table width="100%" border="0"><tr><td valign="top">原文件名称：</td>\
				<td>'+name+'</td></tr><tr><td valign="top" style="padding-top: 10px;">文件名:</td><td style="padding-top: 10px;">\
				<input class="dialog-input" id="newName" value="'+tname+'"><br><span style="color: #666;line-height: 2;">输入文件名时请不要包括文件扩展名</span></td></tr></table>',
			title : "重命名文件",
			statusbar: "<span class='dialog-error' id='addError'></span>",
			button: [
				 {
					value: '确定重命名',
					callback: function () {
						var newName = $.trim($("#newName").val());
						var error = $("#addError").html("")
						if(newName == ""){
							error.html("您没有输入新文件名!");
							return false;
						}
						if(!that.regFolder.test(newName)){
							error.html("文件名格式不对!");
							return false;
						}
						$.ajax({
						    url: "FileSpaceHandler.ashx?cmd=ReNameFile",
						    data: { fileId: checkTag.val(), oldName: encodeURI(name), newName: encodeURI(newName), user: encodeURI(sessionUser) },
							dataType:"json",
							cache: false,
							success : function(data){
								if(data.code == 0){
									error.html("<span style='color:#009933;'>重命名成功</span>");
									newName = checkTag.parents("li").find("a.files").hasClass("get-file") ? newName+name.substr(name.lastIndexOf(".")):newName ;
									checkTag.parents("li").find("a.files").html(newName).attr("title",newName);
									getTree();
								}else{
									d.close().remove();
									d = dialog({content:d.msg});
									d.showModal();
								}
								setTimeout(function(){d.close().remove();},1000);
							},
							error : function(data){
								error.html("<span style='color:#f00;'>重命名失败,请稍后再试</span>");
							}
						})
						return false ;
					},
					autofocus: true
				},{
					value: '取消',
					callback: function () {
						return true;
					},
					autofocus: true
				},
			]
		});
		d.showModal();
	});
	// 移动文件
	$(".menuBlock #moveFile").bind("click",function(){
		that.cutFile(1);
	});
	//复制文件
	$(".menuBlock #copyFile").bind("click",function(){
		that.cutFile(2);
	});
	// 关联文件
	$(".menuBlock #linkFile").bind("click",function(){
		if($(this).hasClass("disabled")){
			return false;
		}
		var checkTag = $("#fileList [name='checkItem']:checked") ;
		if(!that.getRole(checkTag.data("role"),"all")){
			var d = dialog({content:"您选择的文件没有权限进行该操作！"});
			d.showModal();
			setTimeout(function(){d.close().remove();},2000);
			return false ;
		}
		var d = that.iframeDialog = dialog({
		    content: "<iframe src='RelevanceMng.aspx?user=" + encodeURI(sessionUser) + "&id=" + checkTag.val() + "' frameBorder='0' style='border:none;width:800px;height:620px;'></iframe>",
			title : "关联文件" , 
			oniframeload : function(){
			}
		});
		d.showModal();
	});
	//设置上传码
	$(".menuBlock #SetUploadCode").bind("click",function(){
		if($(this).hasClass("disabled")){
			return false;
		}
		var checkTag = $("#fileList [name='checkItem']:checked") ;
		if(!that.getRole(checkTag.data("role"),"all")){
			var d = dialog({content:"您选择的文件没有权限进行该操作！"});
			d.showModal();
			setTimeout(function(){d.close().remove();},2000);
			return false ;
		}
		var d = that.iframeDialog = dialog({
		    content: "<iframe src='uploadcode.aspx?user=" + encodeURI(sessionUser) + "&path=" + checkTag.data("postion") + "&dir=" + checkTag.data("dir") + "' frameBorder='0' style='border:none;width:600px;height:400px;'></iframe>",
			title : "设置上传码" , 
			oniframeload : function(){
			}
		});
		d.showModal();
	});

	
	this.removeOtherMenu();
}
menuCtrl.removeOtherMenu = function(){
	// 清楚多余的右键菜单
	if($("#right_mm.rMenu.menu").size()>0){
		$("#right_mm.rMenu.menu").menu("destroy");
	}
	$('.menuBlock #right_mm').menu().css("visibility","visible").find(".menu-line").remove();
	
}
/**
**移动或复制文件
*/
menuCtrl.cutFile = function(type){
	var that = menuCtrl;
	var txttype = type == 1 ? "移动" : "复制";
	var checkTag = $("#fileList [name='checkItem']:checked") ;
	
	// 没有选择任何文件
	if(checkTag.size() == 0 ){
		var d = dialog({content:"您没有选择任何文件，请先选择！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	
	
	var filePath = [] ;
	checkTag.each(function(){
		if(that.getRole($(this).data("role"),"all")){
			filePath.push($(this).data("path"));
		}
	});
	if(filePath.length == 0 ){
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	filePath = "`"+filePath.join("`");
	var d = dialog({
		content:'<table><tr><td valign="top">选择要'+txttype+'到的目标路径：</td><td><select name="vpath" id="vpath" class="dialog-input">\
			<option>正在读取……</option></select></td></tr><tr><td>\
			<a style="color:#0099FF;" href=\'javascript:void(0);\' onclick=\"javascript:shareuser(\'search_userPath.aspx\');\">选择其它位置</a></td><td></td></tr></table>',
		title : txttype + "文件或目录",
		button: [
			 {
				value: '确定'+txttype,
				callback: function () {
					$.ajax({
						url:"FileSpaceHandler.ashx?cmd=MoveOrCopyFile",
						data: { path: encodeURI($("#H_path").val()), filepath: encodeURI(filePath), targepath: encodeURI($("#vpath").val()), type: type, type2: "", user: encodeURI(sessionUser) },
						dataType :"json",
						cache: false,
						success : function(data){
							d.close().remove();
							that.ajaxState(data,txttype + "文件或者目录");
						}
					});
					return false ;
				},
				autofocus: true
			},{
				value: '取消',
				callback: function () {
					return true;
				},
				autofocus: true
			},
		]
	});
	d.showModal();
	//加载路径
	$.ajax({
	    url: "FileSpaceHandler.ashx?cmd=GetAllPath&user=" + encodeURI(sessionUser),
		dataType : "text",
		cache: false,
		success : function(data){
			var data = data.split("^");
			var select = $("#vpath")[0];
			for(var i =0 ;i<data.length ; i++){
				select.options[i] = new Option(data[i],data[i]);
			}
		}
	})
};
/**
**删除文件
*/
menuCtrl.removeFile = function(checkTag){
	var that = menuCtrl ;
	var files = [];
	var deleteIds = [];
	checkTag = checkTag ?checkTag : $("#fileList [name='checkItem']:checked") ;
	var folder = [];
	// 没有选择任何文件
	if(checkTag.size() == 0 ){
		var d = dialog({content:"您没有选择任何文件，请先选择！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	
	$("#fileList [name='checkItem']:checked").each(function(){
		if(that.getRole($(this).data("role"),"all")){
			// 获取删除的文件名
			files.push($.trim($(this).parents("li").find("a.files").text()));
			// 删除文件的文件ID
			deleteIds.push($(this).val());
			if($(this).data("folder") == "1"){
				folder.push($.trim($(this).parents("li").find("a.files").text())) ;
			}
		}
	});
	//权限判断
	if(files.length == 0 ){
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	var d = dialog({
		content : "您确定要删除文件:<br><div style='color:#3399FF;width:350px;overflow: hidden;line-height:20px;word-break: break-all;'>"+files.join("&nbsp;&nbsp;;&nbsp;&nbsp;")+
				(folder.length>0?"<br><span style='color:#f00;'>警告：文件&nbsp;&nbsp;"+folder.join("&nbsp;&nbsp;;&nbsp;&nbsp;")+"&nbsp;&nbsp;可能含有子目录</span>":"")+"</div>",
		title : "删除文件",
		button: [
			 {
				value: '确定删除',
				callback: function () {
					$.ajax({
						url: "FileSpaceHandler.ashx?cmd=del",
						data: { "ids": deleteIds.join(","), user: encodeURI(sessionUser) },
						dataType:"json",
						cache: false,
						success : function(data){
							d.close().remove();
							that.ajaxState(data,"删除文件");
						}
					})
					return false ;
				},
				autofocus: true
			},{
				value: '取消',
				callback: function () {
					return true;
				},
				autofocus: true
			},
		]
	});
	d.showModal();
}
/**
**向上一级目录
*/
menuCtrl.goPrevFile = function(){
	var path = $("#H_path").val();
	if(path.length == 1){
		var d = dialog({
			content : "已经到根目录了"
		});
		d.showModal();
		setTimeout(function(){
			d.close().remove();
		},2000);
		return false ;
	}
	path = path.substr(0,path.length-1);
	$("#H_path").val(path.substring(0,path.lastIndexOf("/")+1));
	$("#H_pid").val("");
	menuCtrl.getFile();
}
menuCtrl.getRole = function(role, operate){
	var path = $.trim($("#H_GGUser").val());
	var flag = false;
	if(path == "/"){
		flag = true;
	}else{
		switch(operate){
			case "all" : 
				flag = parseInt(role) <=1 ;
			break;
			case "add" : 
				flag = parseInt(role) <= 2 ;
			break;
			case "download" :
				flag = parseInt(role) <= 3 ;
			break;
			case "read" : 
				flag = parseInt(role) <= 4 ;
			break;
		}
	}
	
	return flag ;
}
/**
**根目录
*/
menuCtrl.rootFile = function(){
	var path = "/";
	$("#H_path").val(path);
	$("#H_pid").val("");
	menuCtrl.getFile();
}
/**
*压缩文件
**/
menuCtrl.zipFile = function(){
	var that = menuCtrl ;
	var checkTag = $("#fileList [name='checkItem']:checked") ;
	if(checkTag.size() == 0 ) {
		var d = dialog({content:"您没有选择任何文件，请先选择！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	
	var files = [];
	var paths = [];
		
	$("#fileList [name='checkItem']:checked").each(function(){
		if(that.getRole($(this).data("role"),"all")){
			// 获取压缩的文件名
			files.push($.trim($(this).parents("li").find("a.files").text()));
			// 压缩文件的文件ID
			paths.push($(this).data("path"));
		}
	});
	
	//权限判断
	if(files.length == 0 ){
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	
	var d = dialog({
		content : "您确定要压缩文件:<br><div style='color:#3399FF;width:350px;overflow: hidden;line-height:20px;word-break: break-all;'>"+files.join(";&nbsp;&nbsp;&nbsp;&nbsp;")+"</div>",
		title : "压缩文件",
		button: [
			 {
				value: '确定压缩',
				callback: function () {
					$.ajax({
						url: "FileSpaceHandler.ashx?cmd=ZipFile",
						data: { "filepath": encodeURI("`" + paths.join("`")), path: encodeURI($("#H_path").val()), user: encodeURI(sessionUser) },
						dataType:"json",
						cache: false,
						success : function(data){
							d.close().remove();
							that.ajaxState(data,"压缩文件");
						}
					})
					return false ;
				},
				autofocus: true
			},{
				value: '取消',
				callback: function () {
					return true;
				},
				autofocus: true
			},
		]
	});
	d.showModal();
}
/**
*解压文件
**/
menuCtrl.unZipFile = function () {
    var that = menuCtrl;
    var checkTag = $("#fileList [name='checkItem']:checked");
    if (checkTag.size() == 0) {
        var d = dialog({ content: "您没有选择任何文件，请先选择！" });
        d.showModal();
        setTimeout(function () { d.close().remove(); }, 2000);
        return false;
    }

    var files = [];
    var paths = [];

    $("#fileList [name='checkItem']:checked").each(function () {
        if (that.getRole($(this).data("role"), "all")) {
            // 获取解压的文件名
            files.push($.trim($(this).parents("li").find("a.files").text()));
            // 解压文件的文件ID
            paths.push($(this).data("path"));
        }
    });

    //权限判断
    if (files.length == 0) {
        var d = dialog({ content: "您选择的文件没有权限进行该操作！" });
        d.showModal();
        setTimeout(function () { d.close().remove(); }, 2000);
        return false;
    }
    var d = dialog({
        content: "您确定要解压文件:<br><div style='color:#3399FF;width:350px;overflow: hidden;line-height:20px;word-break: break-all;'>" + files.join(";&nbsp;&nbsp;&nbsp;&nbsp;") + "</div>",
        title: "解压文件",
        button: [
			 {
			     value: '确定解压',
			     callback: function () {
			         $.ajax({
			             url: "FileSpaceHandler.ashx?cmd=UnZipFile",
			             data: { "filepath": encodeURI("`" + paths.join("`")), path: encodeURI($("#H_path").val()), user: encodeURI(sessionUser) },
			             dataType: "json",
                         cache:false,
			             success: function (data) {
			                 d.close().remove();
			                 that.ajaxState(data, "解压文件");
			             }
			         })
			         return false;
			     },
			     autofocus: true
			 }, {
			     value: '取消',
			     callback: function () {
			         return true;
			     },
			     autofocus: true
			 },
		]
    });
    d.showModal();
}
/**
*提取文件
**/
menuCtrl.extractFile = function(){
	var that = menuCtrl ;
	
	//如果窗口不存在，则绘制
	if(that.iframeDialog){
		that.iframeDialog.close().remove();
	}
	var paths = [];
	var flag = false ; //是否选择文件
	var checkTag = $("#fileList [name='checkItem']:checked") ;
	
	
	checkTag.each(function(){
		if($(this).data("folder") != "1"){
			flag = true ;
			if(that.getRole($(this).data("role"),'all')){
				// 提取文件的文件ID
				paths.push($(this).data("path"));
			}
		}
	});
	//是否选择文件夹
	if(!flag ) {
		var d = dialog({content:"您没有选择任何文件，请先选择！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	//是否有权限更改
	if(paths.length == 0 ) {
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	var d = that.iframeDialog = dialog({
	    content: "<iframe src='code.aspx?user=" + encodeURI(sessionUser) + "&path=" + $("#H_path").val() + "&sharelist=" + paths.join(",") + "' frameBorder='0' style='border:none;width:650px;height:380px;'></iframe>",
		title : "提取文件" , 
		oniframeload : function(){
		}
	});
	d.showModal();

}
/**
*转发文件
**/
menuCtrl.forwardFile = function(){
	var that = menuCtrl ;
	//如果窗口不存在，则绘制
	if(that.iframeDialog){
		that.iframeDialog.close().remove();
	}
	var paths = [],ids=[];
	var flag = false ; //是否选择文件
	var checkTag = $("#fileList [name='checkItem']:checked") ;
	checkTag.each(function(){
		if($(this).data("folder") != "1"){
			flag = true ;
			if(that.getRole($(this).data("role"),'all')){
				// 提取文件的文件ID
				paths.push($(this).data("path"));
                ids.push($(this).val());
			}
		}
	});
	if(checkTag.size() == 0 ) {
		var d = dialog({content:"您没有选择任何文件，请先选择！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	//是否选择文件夹
	if(!flag ) {
		var d = dialog({content:"您没有选择任何文件，请先选择！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	//是否有权限更改
	if(paths.length == 0 ) {
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
var d = that.iframeDialog = dialog({
	    content: "<iframe src='send.aspx?user=" + encodeURI(sessionUser) + "&path=" + encodeURI($("#H_path").val()) + "&sharelist=`" + paths.join("`") + "&Ids="+ids.join(",")+"' frameBorder='0' style='border:none;width:800px;height:580px;'></iframe>",
		title : "转发文件" , 
		oniframeload : function(){
		}
	});
	d.showModal();

}
/**
*共享文件
**/
menuCtrl.sharaFile = function () {
    var that = menuCtrl;
    //如果窗口不存在，则绘制
    if (that.iframeDialog) {
        that.iframeDialog.close().remove();
    }
    var paths = [], ids = [];
    var checkTag = $("#fileList [name='checkItem']:checked");

    if (checkTag.size() == 0) {
        if (that.getRole($("#H_rootRole").val(), "all")) {
            paths.push($.trim($("#H_path").val()));
        }
    } else {
        checkTag.each(function () {
            if (that.getRole($(this).data("role"), "all")) {
                // 删除文件的文件ID
                paths.push($(this).data("path"));
                ids.push($(this).val());
            }
        });
    }
    //是否有权限更改
    if (paths.length == 0) {
        var d = dialog({ content: "您选择的文件没有权限进行该操作！" });
        d.showModal();
        setTimeout(function () { d.close().remove(); }, 2000);
        return false;
    }
    var d = that.iframeDialog = dialog({
        content: "<iframe src='share.aspx?user=" + encodeURI(sessionUser) + "&path=" + $("#H_path").val() + "&sharelist=`" + paths.join("`") + "&ids=" + ids.join(",") + "' frameBorder='0' style='border:none;width:800px;height:500px;'></iframe>",
        title: "发布或共享文件",
        oniframeload: function () {
        }
    });
    d.showModal();
}
/**
*发布文件
**/
menuCtrl.sharaOutFile = function(){
	var that = menuCtrl ;
	//如果窗口不存在，则绘制
	if(that.iframeDialog){
		that.iframeDialog.close().remove();
	}
	var paths = [];
	var checkTag = $("#fileList [name='checkItem']:checked") ;
	
	if(checkTag.size() == 0 ) {
		var d = dialog({content:"您没有选择任何文件，请先选择！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	
	checkTag.each(function(){
		if(that.getRole($(this).data("role"),"all")){
			// 删除文件的文件ID
			paths.push($(this).data("path"));
		}
	});
	//是否有权限更改
	if(paths.length == 0 ) {
		var d = dialog({content:"您选择的文件没有权限进行该操作！"});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		return false;
	}
	var d = that.iframeDialog = dialog({
	    content: "<iframe src='shareout.aspx?user=" + encodeURI(sessionUser) + "&path=" + $("#H_path").val() + "&sharelist=" + escape("`" + paths.join("`")) + "' frameBorder='0' style='border:none;width:800px;height:500px;'></iframe>",
		title : "发布或共享文件" , 
		oniframeload : function(){
		}
	});
	d.showModal();
}
/**
*点击目录进入相对于的目录
**/
menuCtrl.goFile = function(path){
	$("#H_pid").val("");
	$("#H_path").val(path);
	menuCtrl.getFile();
}
/**
*刷新
**/
menuCtrl.refresh = function(){
	var that = menuCtrl ;
	var path =  encodeURI($("#H_path").val());
	$.ajax({
		url :'FileSpaceHandler.ashx?cmd=Refresh',
		cache: false,
		data: { path: path, user: encodeURI(sessionUser) },
		success : function(data){
			getTree();
			that.getFile();
		}
	})
}
/**
**获取文件
*/
menuCtrl.getFile = function (currentPage) {
    var that = this;
    currentPage = currentPage ? currentPage : 0;
    var path = encodeURI($("#H_path").val());
    var jump =$("#jumpMenu").size() == 0 ? $("#jumpMenuSlt").val(): $("#jumpMenu").val() ; //排序 
    var pubUser = $("#H_GGUser").val(); //是否公共空间
    var tempPara = "", showType = "";
    $("#searchInput").val("");
    if ($("#H_pid").val() != "")
        tempPara = "&pid=" + $("#H_pid").val();
    var type = $("#listType").val();
    if (type == "list")
        showType = "0";
    else if (type == "thumbnails")
        showType = "1";
    function ajax(page, callback) {
		//var d = dialog();
        $.ajax({
            url: "FileSpaceMng.aspx?pubuser=" + pubUser + "&type=" + showType + tempPara,
            data: { filePath: path, pageIndex: page, sort: jump, user: encodeURI(sessionUser) },
            dataType: "html",
            cache: false,
            beforeSend: function () {
                //d.showModal();
            },
            success: function (data) {
                var data;
               // d.close().remove();
                typeof callback == "function" && (callback(data));
            }
        });
    }
    function html(html) {
        $("#fileContent").empty().append(html);
		that.ctrFile();
    }
    ajax(currentPage, function (data) {
        that.textOverflow(decodeURI(path));
        html(data);
        var maxlength = parseInt($("#H_itemtCount").val());
        $("#page").pagination(maxlength, {
            prev_text: '< 上一页',
            next_text: '下一页 >',
            items_per_page: parseInt($("#H_pagesize").val()),
            num_display_entries: 5,
            current_page: 0,
            num_edge_entries: 2,
            link_to: "javascript:void(0);",
            callback: function (page_id, panel) {
                var self = this;
                ajax(page_id, function (vdata) {
                    self.maxentries = parseInt($("#H_itemtCount").val()); ;
                    html(vdata);
                });
            }
        });
    });


}
menuCtrl.textOverflow = function(word){
		var str = word,html='';
		var strLen = 0 ;
		var overflow = 27 ;
		var reg = /[^\x00-\xff]/;
		str = str.substring(0,str.length-1);
		var arr =  str.split("/");
		var html = '';
		for(var i =arr.length-1;i>=0 ;i--){
			var name = arr[i] ;
			var len = 0 ;
			for(var n =0 ;n<name.length;n++){
				if(reg.test(name.charAt(n))){
					len ++ ;
				}else{
					len+=0.5;
				}
				if(len > 10 ){
					break;
				}
			}
			strLen +=len ;
			if(strLen>overflow){
				name = "..."+name.substring(name.length-n,name.length);
			}else if(len>10){
				name = name.substring(0,5)+"..."+name.substring(name.length-5,name.length);
			}
			html="<a onclick = 'menuCtrl.goFile(this.getAttribute(\"data-path\"))' data-path='"+word+"' title='"+arr[i]+"'>"+(arr[i]==""?'<img src="images/ico_01.png"/>':name)+'</a><img src="images/arrow.gif"/>'+html;
			word = word.substring(0,word.lastIndexOf("/")-1);
			word = word.substring(0,word.lastIndexOf("/")+1);
			if(strLen>overflow){
				break;
			}
		}
		$("#I_path").html(html.substring(0,html.length-29));
	}
/**
**选择展示分类
*/
menuCtrl.setShowType = function(){
	var that = this ;
	$("#showType>span").bind("click",function(){
		var type=$(this).data("id");
		$(this).parent().attr("class",type);
		$("#listType").val(type);
		that.getFile();
	});
	
}
//高级搜索
menuCtrl.search = function(){
	var that = this ;
	var html = '<link href="css/webdialog.css" type="text/css" rel="stylesheet">\
			<table class="wfrom-table"><tbody></tr><tr><td class="label">文件名或者目录名：</td><td>\
            <input id="tname" class="input-text" type="text" name="txtname" value="">（多个关键字用半角空格分隔）</td> </tr>\
            <tr><td class="label">指定修改时间：</td><td>\
            <input id="ttime1" class="input-text" type="text" size="15" name="txttime1" style="width:131px;">\
            到<input id="ttime2" type="text" size="15" name="txttime2" style="width:131px;" class="input-text">\
            不填为不限）</td></tr><tr><td class="label">指定文件大小：</td><td>\
            <input id="tsize1" class="input-text" type="text" size="10" style="width:131px;" name="txtsize1">—\
            <input id="tsize2" class="input-text" type="text" size="10" style="width:131px;" name="txtsize2">&nbsp;KB （不填为不限）\
			</td></tr><tr><td class="label">文件类型：</td><td>\
            <input id="ttype" class="input-text" type="text" name="txttype" placeholder="All">\
            （输入扩展名，用半角,分隔，不填为不限）</td></tr><tr><td class="label">文件注释：</td>\
            <td><input id="tnote" class="input-text" type="text" name="txtnote">（不填为不限）</td></tr></tbody></table>';
	var type = $("#listType").val();
	if (type == "list")
		showType = "0";
	else if (type == "thumbnails")
		showType = "1";
	var ajaxData = { search: "advsearch", type: showType, user: encodeURI(encodeURI(sessionUser)) }
	var d = dialog({
		title : "高级搜索",
		content : html ,
		button : [
			{
				value :"确定搜索",
				callback : function(){
					ajaxData["name"] = encodeURI($.trim($("#tname").val()));
					ajaxData["time1"] = encodeURI($.trim($("#ttime1").val()));
					ajaxData["time2"] = encodeURI($.trim($("#ttime2").val()));
					ajaxData["size1"] = encodeURI($.trim($("#tsize1").val()));
					ajaxData["size2"] = encodeURI($.trim($("#tsize2").val()));
					ajaxData["fileext"] = encodeURI($.trim($("#ttype").val()));
					ajaxData["note"] = encodeURI($.trim($("#tnote").val()));
					ajax(0,function(data){
						$("#fileContent").empty().append(data);
						that.textOverflow("/");
						var maxlength = parseInt($("#H_itemtCount").val());
						$("#page").pagination(maxlength, {
							prev_text: '< 上一页',
							next_text: '下一页 >',
							items_per_page: parseInt($("#H_pagesize").val()),
							num_display_entries: 5,
							current_page: 0,
							num_edge_entries: 2,
							link_to: "javascript:void(0);",
							callback: function (page_id, panel) {
								var self = this;
								ajax(page_id, function (vdata) {
									$("#fileContent").empty().append(vdata);
									that.textOverflow("/");
									self.maxentries = parseInt($("#H_itemtCount").val()); 
								});
							}
						});
					});
				},
				autofocus: true
			},
			{
				value :"取消",
				callback : function(){}
			}
		]
	}).showModal();
	$('#ttime1').datepick();
	$('#ttime2').datepick();
	function ajax(page,callback){
		var _d = dialog();
		ajaxData["pageIndex"] = page ;
		$.ajax({
			url:"FileSpaceMng.aspx",
			data : ajaxData,
            cache: false,
			beforeSend:function(){
				_d.showModal();
			},
			success : function(data){
				_d.close().remove();
				typeof callback == "function" && callback(data);
				that.ctrFile();
				
			}
		});
	}
}
// 搜索文件
menuCtrl.initSearch = function (){
	var that = this ;
	var tag = $("#searchInput");
	if(typeof Worker == "undefined"){
		tag.val(tag.attr("placeholder"));
		tag.bind("focus",function(){
			var value = $.trim($(this).val());
			if(value == $(this).attr("placeholder")){
				$(this).val("");
			}
		}).bind("blur",function(){
			var value = $.trim($(this).val());
			if(value == "" ){
				$(this).val($(this).attr("placeholder"));
			}
		});
	}
	
	$("#searchFile").bind("click",function(){
		var name = $.trim(tag.val());
		$("#H_pid").val("");
		$("#H_path").val("/");
		ajax(name,0,function(data){
			$("#fileContent").empty().append(data);
			that.textOverflow("/");
			var maxlength = parseInt($("#H_itemtCount").val());
			$("#page").pagination(maxlength, {
				prev_text: '< 上一页',
				next_text: '下一页 >',
				items_per_page: parseInt($("#H_pagesize").val()),
				num_display_entries: 5,
				current_page: 0,
				num_edge_entries: 2,
				link_to: "javascript:void(0);",
				callback: function (page_id, panel) {
					var self = this;
					ajax(name,page_id, function (vdata) {
						$("#fileContent").empty().append(vdata);
						that.textOverflow("/");
						self.maxentries = parseInt($("#H_itemtCount").val()); 
					});
				}
			});
			});
	});
	
	function ajax(name,page,callback){
		var type = $("#listType").val();
		if (type == "list")
			showType = "0";
		else if (type == "thumbnails")
			showType = "1";
		var d = dialog();
		$.ajax({
			url:"FileSpaceMng.aspx",
			data: { search: "search", name: encodeURI(name), type: showType, pageIndex: page, user: encodeURI(sessionUser) },
            cache: false,
			beforeSend:function(){
				d.showModal();
			},
			success : function(data){
				d.close().remove();
				typeof callback == "function" && callback(data);
				that.ctrFile();
				
			}
		});
	}
	
}
/**
**文件操作选项
*/
menuCtrl.ctrFile = function () {
    var that = this;
    // 全选和反选
    $("#checkAll").bind("click", function () {
        var checked = this.checked;
        $("#fileList [name='checkItem']").each(function () {
            this.checked = checked;
            $(this).parents("li")[checked ? "addClass" : "removeClass"]("checked");
        });
    });
    $("#fileList [name='checkItem']").bind("click", function () {
        $(this).parents("li")[this.checked ? "addClass" : "removeClass"]("checked");
        isCheckAll();
    });
    $("#fileList>li").bind("mousedown", function (evt) {
        if (evt.target.name != "checkItem") {
            if (evt.which == 1) {
                var tag = $(this).find("[name='checkItem']")[0];
                tag.checked = !tag.checked;
                $(this)[tag.checked ? "addClass" : "removeClass"]("checked");
                isCheckAll();
            } else {
                var checkTag = $("#fileList [name='checkItem']:checked");
                if (checkTag.size() < 2) {
                    checkTag.each(function () {
                        this.checked = false;
                        $(this).parents("li").removeClass("checked");
                    });
                    var tag = $(this).find("[name='checkItem']")[0];
                    tag.checked = true;
                    $(this).addClass("checked");
                }
            }
        }
    });
    /**是否全选或反选*/
    function isCheckAll() {
        var checkAll = $("#checkAll")[0];
        if ($("#fileList [name='checkItem']:checked").size() == $("#fileList [name='checkItem']").size()) {
            checkAll.checked = true;
        } else {
            checkAll.checked = false;
        }
    }
    //排序
    $("#jumpMenu,#jumpMenuSlt").bind("change", function () {
        that.getFile();
    });
    //点击文件夹进入下一级目录
    $("#fileContent .get-folder").bind("click", function () {
        $("#H_pid").val($(this).data("id"));
        $("#H_path").val($.trim($(this).parents("li").find("[name='checkItem']").data("path")))
        that.getFile();
    });
    $("#fileContent .get-fileimg").bind("click", function () {
        $(this).parent().find('.get-file')[0].click();
    });
    /*获取选取的数据**/
    function getChecked() {
        var split = "^";
        var valueArr = [];
        $("#fileList [name='checkItem']:checked").each(function () {
            valueArr.push(this.value);
        });
        return valueArr.join(split);
    }

    //删除单个文件，缩列图
    $("#fileContent .delete").bind("click", function () {
        that.removeFile($(this).parents("li").find("[name='checkItem']"));
    });
    //下载文件
    $("#fileContent .get-file").bind("click", function () {
        // 权限判断
        if (!that.getRole($(this).parents("li").find("name=['checkItem']").data("role"), "download")) {
            var d = dialog({ content: "您没有权限下载该文件!" });
            d.showModal();
            setTimeout(function () { d.close().remove(); }, 2000);
            return false;
        }
        // 下载
        if ($("#downFile").length == 0) {
            $("body").append("<a id='downFile' download></a>");
        }
        //	$("#downFile").attr("href",$(this).data("href"))[0].click();
    });
    $("#fileContent .downLoadFile").bind("click", function () {
        $(this).closest("li").find(".get-file")[0].click();
    })
}
/**
**展示ajax成功失败的提示信息
*******/
menuCtrl.ajaxState = function(data,name){
	if(data.code == 0 ){
		var d = dialog({content:data.msg});
		d.showModal();
		setTimeout(function(){d.close().remove();},2000);
		getTree();
		this.getFile();
	}else{
		dialog({
			title :"提示信息",
			content : "<div style='width:300px;'>"+name+data.msg+"</div>",
			button :[
				{
					value: '确定',
					callback: function () {
						return true;
					},
					autofocus: true
				}
			]
		}).showModal();
	}
}

menuCtrl.init();

var closeWindow = function(flag){
	menuCtrl.closeUploadFile(flag);
}