$(document).ready(function()
	{
		Init();
		ShowProgress(LogingLabel);
		
	});
function Init()
	{
		CheckBaiduToken();
		InitCloudMainView();
	}
function ShowProgress(label)
	{
		$('#progressLabel').html(label);
		$('#progress').modal();
	}
function StopProgress()
	{
		$('a.modalCloseImg').click();
	}

function GetStorageInfo()
	{
		basicUrl = 'https://pcs.baidu.com/rest/2.0/pcs/quota?';
		url = basicUrl + "&method=info" + "&access_token=" + encodeURIComponent(login_data.BaiduToken) + "&callback=GetStorageInfoCallback";

		ExecuteScript(url);
	}

function GetStorageInfoCallback(data)
	{
		total = ComputeBytes(data.quota);
		used = ComputeBytes(data.used);
		$('.Storage').html(used+'/'+total);
		percent = data.used*100/data.quota;
		console.log('Init callback:',percent,parseInt(percent.toFixed(2)));
		$(".Progress").progressbar({ value: parseInt(percent.toFixed(2)) });
	}
function ExecuteScript(url)
	{
		var script = document.createElement('script');
		script.setAttribute('src', url);
		document.getElementsByTagName('head')[0].appendChild(script); 
	}
	
function CheckBaiduToken()
	{
		basicUrl = 'https://pcs.baidu.com/rest/2.0/pcs/quota?';
		url = basicUrl + "&method=info" + "&access_token=" + encodeURIComponent(login_data.BaiduToken) + "&callback=CheckBaiduTokenCallback";
		console.log('CheckBaiduToken:',url);
		ExecuteScript(url);
	}
function CheckBaiduTokenCallback(data)
	{
		console.log('CheckBaiduTokenCallback:',data);
		if (data.hasOwnProperty('error_msg') && (data.error_msg == "Access token expired") )
		{
			RequestBaiduToken();
		}
		else if (data.hasOwnProperty('quota'))
		{
			GetStorageInfoCallback(data);
		}
	}	
function RequestBaiduToken()
	{
		var data = {};
		data.file= [];
		$.post("/ZTECloud/RequestBaiduToken",data,function(){});
		/**basicUrl = 'https://openapi.baidu.com/xcloud/1.0/authorize?';
		url = basicUrl + "response_type=token&client_id=bAGi5ceahOVMkirhACu7QMIL&redirect_uri=oob& third_access_token=" + encodeURIComponent(ZTEToken)

		url = url + "&callback=RequestBaiduTokenCallback";
		var script = document.createElement('script');
		script.setAttribute('src', url);
		document.getElementsByTagName('head')[0].appendChild(script); 
		console.log('RequestBaiduToken url:',url);**/
	}

function ComputeBytes(num)
	{
		if (num < 1024)
		{
			k = num/1024;
			return JudgeFixed(k,'KB');
		}
		else if (num < 1024*1024)
		{
			k = num/1024;
			if (k > 1000)
			{
				m = num/1024/1024;
				return JudgeFixed(m,'MB');
			}
			else
			{
			return JudgeFixed(k,'KB');
			}
		}
		else if (num < 1024*1024*1024)
		{
			m = num/1024/1024;
			if (m > 1000)
			{
				g = num/1024/1024/1024;
				return JudgeFixed(g,'GB');
			}
			else
			{
			return JudgeFixed(m,'MB');
			}
		}
		else
		{
			g= num/1024/1024/1024;
			return JudgeFixed(g,'GB');
		}
	}
function JudgeFixed(num, level)
	{
		if (parseFloat(num.toFixed(2)) == num.toFixed(2))
			{
				return num.toFixed(0)+level;
			}
			else
			{
				return num.toFixed(2)+level;
			}
	}
	
function InitCloudMainView()
	{
		InitTree();
		GetDirInfo("/\apps/\zte", dir_info, 1);
		InitToolbarState();
	}	


function InitTree()
	{
		zNodes.push({ id:1, pId:0, name:MyCloudDiskLabel, abspath:'/apps/zte', isParent:true, isdir:1, haveGetSubnodes:true, 'fs_id':0,});
		setting.expandSpeed = ($.browser.msie && parseInt($.browser.version)<=6)?"":"fast";

		zTree = $("#tree").zTree(setting, zNodes);
		var nodes = zTree.getNodes();
		zTree.selectNode(nodes[0]);
	};
function InitToolbarState()
{
	$('label.user').html(login_data.UserName);
	$('dt.user').attr('title',login_data.UserName);
	if (Back_Id_List.length == 0)
		{
			$('.back').addClass("disabled");
		}
	$('.download').addClass("disabled");	
	$('.delete').addClass("disabled");	
	$('.copy').addClass("disabled");	
	$('.rename').addClass("disabled");	
	$('.paste').addClass("disabled");	
}
function GetDirInfo(path, storage, id)
	{  
	    url = 'https://pcs.baidu.com/rest/2.0/pcs/file',
		get_data = {"access_token":login_data.BaiduToken,
					"path":path,
					"method":"list",
					}
		$.get(url, get_data,
		           function(data){
							GetDirInfoCallback(path, data, storage, id);
						});
	}
function GetDirInfoCallback(path, Json_text, storage, id)
	{

		var res =  jQuery.parseJSON(Json_text);
		dir_ls = res.list;
		//console.log('GetsubDir parseJSON:',dir_ls);
		for (x in dir_ls)
		{
			storage[x] = {"fs_id":0,'isdir':0, 'path':'', 'abspath':'', 'sub':{}, 'size':0};

			flag = false;//idexist(l[x].fs_id);
			//console.log('GetsubDir idexist:',flag);
			if (flag == true)
			{
				continue;
			}
				
			storage[x].fs_id = dir_ls[x].fs_id;
			storage[x].isdir = dir_ls[x].isdir;
			storage[x].abspath = dir_ls[x].path;
			co_path = dir_ls[x].path.replace(path,"");

			sp_res = co_path.split('\/');

			storage[x].path = sp_res[1];
			
		}
		ProcessDirInfo(id);
	}
function ProcessDirInfo(parent_id)
	{	
		id = 0;
		console.log('showDir dir_info:',dir_info);
		data = SortData(dir_info);
		GenerateTreeNodes(data,id,parent_id);
	}
function SortData(data)
{
	var dir_info_sorted = new Object();
	temp = new Array();
	defaultDir_list = new Array();
	dir_list = new Array();
	file_list = new Array();
	for (i in data)
	{
		if (data[i].isdir == 1)
		{
			if ((data[i].path == "我的图片")||(data[i].path == "我的文档")||(data[i].path == "我收到的文件"))
			{
				defaultDir_list.push(new String(data[i].path)._obj=data[i]);
			}
			else
			{
				dir_list.push(new String(data[i].path)._obj=data[i]);
			}
		}
		else
		{
			file_list.push(new String(data[i].path)._obj=data[i]);
		}
	}
	defaultDir_list = defaultDir_list.sort();
	dir_list = dir_list.sort();
	file_list = file_list.sort();
	console.log('defaultDir_list:',defaultDir_list);
	console.log('dir_list:',dir_list);
	console.log('file_list:',file_list);
	for (i in defaultDir_list)
	{
		temp.push(defaultDir_list[i]);
	}
	for (i in dir_list)
	{
		temp.push(dir_list[i]);
	}
	for (i in file_list)
	{
		temp.push(file_list[i]);
	}
	for (i in temp)
	{
		dir_info_sorted[i] = temp[i];
	}

	return dir_info_sorted;
}
function GenerateTreeNodes(data, self_id, para_id)
	{	
		//console.log('generateNodes data:',data);
		for (x in data)
		{
			if (data[x].fs_id == 0)
			{
				continue;
			}
			flag = IdExist(data[x].fs_id);
			if (flag == true)
			{
				continue;
			}
			else
			{
				fid_list.push(data[x].fs_id);
			}
			temp_self_id = data[x].fs_id;
			
			//console.log('generateNode zNodes:',zNodes);
			if (data[x].isdir==1)
				{
					if (para_id==0)
					{
						p_node = null;
					}
					else
					{
						t = zTree.getNodesByParam("id", para_id, null);
						p_node = t[0];
					}
					node = { id:temp_self_id, pId:para_id, name:data[x].path, abspath:data[x].abspath, isdir:data[x].isdir,fs_id:data[x].fs_id, isParent:true, haveGetSubnodes:false};
					//console.log('addNode',node);
					zTree.addNodes(p_node, node);
					GenerateTreeNodes(data[x].sub, 0, temp_self_id);
				}
			else
				{
					if (para_id==0)
					{
						p_node = null;
					}
					else
					{
						t = zTree.getNodesByParam("id", para_id, null);
						p_node = t[0];
					}
					node = { id:temp_self_id, pId:para_id, name:data[x].path, abspath:data[x].abspath, isdir:data[x].isdir, fs_id:data[x].fs_id, isParent:false,haveGetSubnodes:false};
					//console.log('addNode',node);
					zTree.addNodes(p_node, node);
				}
		}
		//console.log('generateNodes over:',zNodes);
		ShowRightPanel();
	}
function IdExist(fid)
{
	for (i in fid_list)
	{	
		if (fid_list[i] == fid)
		{
			return true;
		}
	}
	return false;
}



function ShowRightPanel()
{
	StopProgress();
	
	var selectedNode = zTree.getSelectedNode();
	if (selectedNode.isParent == false)
	{
		//$('#right').html("");
		return;
	}
	if (selectedNode.hasOwnProperty("nodes") == false)
	{
		if (selectedNode.isdir == 1)
		{
			$('#right').html('');
		}
		return;
	}
	if (selectedNode.nodes.length == 0)
	{
		$('#right').html("");
		return;
	}

	var text = "";
	for (i in selectedNode.nodes)
	{
		if (selectedNode.nodes[i].isdir == true)
		{
			name = selectedNode.nodes[i].name;
			if ((name == "我的图片")||(name == "我的文档")||(name == "我收到的文件"))
			{
				folder = ' class="folder protect" ';
			}
			else
			{
				folder = ' class="folder" ';
			}
			
			text = text + "<div" + folder + "id="+selectedNode.nodes[i].fs_id+" onclick='onSingleClick(event,this)' ondblclick='onDoubleClick(event,this)'><p></p><label onclick='OnLabelClickRename(this,event)'>"+selectedNode.nodes[i].name+"</label><input type='text' onblur='inputOnBlur(this)' onkeydown='OnKeyDown(this,event)'></div>"
		}
		else
		{
			filename = selectedNode.nodes[i].name;
			extension1 = filename.substring(filename.length-3,filename.length);
			extension2 = filename.substring(filename.length-4,filename.length);
			fileMap = {
						'txt':'doc',
						'doc':'doc',
						'xls':'doc',
						'ppt':'doc',
						
						'png':'jpg',
						'jpg':'jpg',
						'jpeg':'jpg',
						'ico':'jpg',
						'gif':'jpg',
						
						'apk':'apk',
						
						'mp3':'mp3',
						'wav':'mp3',
						'mid':'mp3',
						}
			if (fileMap.hasOwnProperty(extension1))
			{
				type = fileMap[extension1];
			}
			else if (fileMap.hasOwnProperty(extension2))
			{
				type = fileMap[extension2];
			}
			else
			{
				type = 'unknown';
			}
							
			text = text + "<div class=" +"'"+ type +"'"+ "id="+selectedNode.nodes[i].fs_id+" onclick='onSingleClick(event,this)' ondblclick='onFileDoubleClick(event,this)'><p></p><label  onclick='OnLabelClickRename(this, event)'>"+selectedNode.nodes[i].name+"</label><input type='text' onblur='inputOnBlur(this)' onkeydown='OnKeyDown(this,event)'></div>"
		}
		$('#right').html(text);
	}
		
		
	span = $('#tree_1').find('span')
	for (i in span)
	{
		if ((span[i].textContent== "我的图片")||(span[i].textContent == "我的文档")||(span[i].textContent == "我收到的文件"))
		{
			p_elem = span[i].parentElement;
			$(p_elem).find('button').css('background','url(../../static/imgs/ZTECloud/folderLock_Open.gif)');
			$(p_elem).find('button').css('background','url(../../static/imgs/ZTECloud/folderLock_Open.gif)');
		}
	}
	
	GetStorageInfo();
}
function GetSelectNodeDirInfo(treeNode)
{
	if (treeNode.haveGetSubnodes == true)
		{
		return;
		}
	treeNode.haveGetSubnodes = true;
	dir_info = new Object();
	console.log('GetSelectNodeDirInfo path and id:',treeNode.abspath,treeNode.id, treeNode);
	GetDirInfo(treeNode.abspath, dir_info, treeNode.id);
}

function zTreeOnClick(event, treeId, treeNode) 
{
	GetSelectNodeDirInfo(treeNode);
	ShowRightPanel();
	if (treeNode.isdir == 1)
	{
		RemeberOper(treeNode.fs_id);
	}
}
function RemeberOper(currrent_id)
{
	
	last_id = Oper_Id_List[Oper_Id_List.length - 1];

	if (currrent_id != last_id)
	{
		$('.back').removeClass("disabled");
		Oper_Id_List.push(currrent_id);
		Back_Id_List.push(last_id);
	}
	console.log('RemeberOper', Oper_Id_List, Back_Id_List);
}

function onDoubleClick(event,elem)
{
	node_name = $(elem).find('label').html();
	fs_id = parseInt(elem.id);
	var node = zTree.getNodeByParam("fs_id", fs_id );

	if (node.isdir == 0)
	{
		p_node = node.parentNode;
		zTree.selectNode(p_node);
		return;
	}
	else
	{
		zTree.expandNode(node, true, false, true);
		GetSelectNodeDirInfo(node);
		zTree.selectNode(node);
		ShowRightPanel();
		RemeberOper(fs_id);
	}

}
function onSingleClick(event,elem)
	{
		//console.log('onSingleClick:',elem);
		if (event.ctrlKey==1)
		{
			$(elem).addClass("selected");
			fs_id = elem.id;
			var node = zTree.getNodeByParam("fs_id", fs_id);
		}
		else
		{
			$("div").removeClass("selected");
			zTree.checkAllNodes(false);
			$(elem).addClass("selected");
			fs_id = elem.id;
			var node = zTree.getNodeByParam("fs_id", fs_id);
		}
		node.checked = true;
		zTree.updateNode(node, true);
		
		ChangeToolBarState();
	}
function ChangeToolBarState()
{
	var checkedNode = zTree.getCheckedNodes();
	var selectedNode = zTree.getSelectedNode();
	
	// upload, new, paste
	if (selectedNode.abspath != "")
	{
		$('.upload').removeClass("disabled");	
		$('.new').removeClass("disabled");	
		if (userHaveDoneCopyOrCut == true)
		{
			$('.paste').removeClass("disabled");	
		}
		else
		{
			$('.paste').addClass("disabled");	
		}
	}
	else
	{
		$('.upload').addClass("disabled");
		$('.new').addClass("disabled");	
		$('.paste').addClass("disabled");	
	}

	//copy, download, delete, rename
	if (checkedNode.length >= 1)
	{
		$('.copy').removeClass("disabled");	
		$('.download').removeClass("disabled");	
		$('.delete').removeClass("disabled");	
	}
	else
	{
		$('.copy').addClass("disabled");	
		$('.download').addClass("disabled");	
		$('.delete').addClass("disabled");	
	}
	for (i in checkedNode)
		{

		 if ((checkedNode[i].name == "我的图片")||(checkedNode[i].name == "我的文档")||(checkedNode[i].name == "我收到的文件"))
		 {
			$('.delete').addClass("disabled");	
			$('.rename').addClass("disabled");	
			return;
		 }
		}

	if (checkedNode.length == 1)
		{
			$('.rename').removeClass("disabled");	
		}
	else
		{
			$('.rename').addClass("disabled");	
			return;
		}
}

function OnRightPanelClick(event)
{
	targ = event.srcElement;
	tname=targ.tagName;
	if (tname == 'DIV')
	{
		$("div").removeClass("selected");
		zTree.checkAllNodes(false);
		ChangeToolBarState();
	}
}
function OnMouseHover(elem)
{
	if ( $(elem).hasClass("disabled") )
	{
		return;
	}
	$(elem).addClass("hover");
}
function OnMouseOut(elem)
{
	if ( $(elem).hasClass("disabled") )
	{
		return;
	}
	$(elem).removeClass("hover");
}

function OnBack(elem)
{
	if ( $(elem).hasClass("disabled") )
		{
			return;
		}
	
	ShowProgress('');
	
	fs_id = Back_Id_List.pop();
	Oper_Id_List.pop();
	//console.log('onback',fs_id);
	var node = zTree.getNodeByParam("fs_id", fs_id );
	zTree.expandNode(node, true, false, true);
	zTreeOnExpand(event, -1, node);
	zTree.selectNode(node);

	ShowRightPanel();
	if (Oper_Id_List.length == 1)
	{
		$(elem).addClass("disabled");
		var node = zTree.getNodeByParam("fs_id", 0 );
		
		zTree.expandNode(node, true, false, true);
		zTreeOnExpand(event, -1, node);
		zTree.selectNode(node);
		zTree.expandAll(false);
		ShowRightPanel();
	}
}
function OnRefresh()
	{
		ShowProgress(RefreshingLabel);
		var selectedNode = zTree.getSelectedNode();
		selectedNode.haveGetSubnodes = false;
		GetSelectNodeDirInfo(selectedNode);
		CheckOfflineDownloadTask();
	}
function OnUpload(elem)
	{
		if ( $(elem).hasClass("disabled") )
		{
			return;
		}
		var selectedNode = zTree.getSelectedNode();
		var data = {};
		data.path= selectedNode.abspath;
		$.post("/ZTECloud/Upload",data,function(){});
	}
function OnDownload(elem)
	{
		if ( $(elem).hasClass("disabled") )
		{
			return;
		}
		var selectedNode = zTree.getCheckedNodes();
		for (i in selectedNode)
			{
			 if ((selectedNode[i].isdir == 1))
				 {
					alert('请选择单个文件下载');
					return;
				 }
			}

		
		if (selectedNode.length == 1)
			{
				path = selectedNode[0].abspath;
				name = selectedNode[0].name;
				//console.log('OnDownload :',path);
			}
		else
			{
				alert('目前暂时仅支持单文件下载');
				return;
			}
		

		get_data = {"access_token":login_data.BaiduToken,
						"path":path,
						"method":"download",
						}

		url = 'https://pcs.baidu.com/rest/2.0/pcs/file?method=download&access_token='+login_data.BaiduToken+'&path='+path;
		var data = {'url':url,'name':name};

		$.post("/ZTECloud/DownloadFile",data,function(){});
		//location.href = url;
		//$.get(url, get_data,
		//function(data){
		//	onDownloadCallBack(data);

		//});
	}

function OnOfflineDownload(elem)
{
	if ( $(elem).hasClass("disabled") )
	{
		return;
	}
	$("#dialog").dialog( "open" );
}
function OnOfflineDownloadOKClick()
{
	
	var url = document.getElementById("offlineURL").value;
	if (url!=null && url!="")
	{
		$("#dialog").dialog( "close" );
		var selectedNode = zTree.getSelectedNode()

		basicUrl = 'https://pcs.baidu.com/rest/2.0/pcs/services/cloud_dl?';
		save_path = selectedNode.abspath;
		get_data = {"access_token":login_data.BaiduToken,
					"save_path":selectedNode.abspath,
					"source_url":url,
					"method":"add_task",
					}
		$.get(basicUrl, get_data,
		           function(data){
							OfflineDownloadCallback(data, save_path);
						});
	}
	else
	{
		return;
	}
}
function OfflineDownloadCallback(data,save_path)
{
	test2 = data;
	if (data.hasOwnProperty('task_id'))
	{
		ts_id = data.task_id;
		temp = {}
		temp[ts_id] = save_path;
		OfflineDownload_List.push(temp);
		alert(OfflineDownloadHasAdded);
	}
}

function CheckOfflineDownloadTask()
{
	if (OfflineDownload_List.length == 0)
	{
		return;
	}
	id_ls = ''
	for (i in OfflineDownload_List)
	{
		for (item in OfflineDownload_List[i])
		{
			task_id = item;
			save_path = OfflineDownload_List[i][item];
		}
		id_ls = id_ls + task_id + ','
	}
	basicUrl = 'https://pcs.baidu.com/rest/2.0/pcs/services/cloud_dl?';

	get_data = {"access_token":login_data.BaiduToken,
				"task_ids":id_ls,
				"method":"query_task",
				}
	$.get(basicUrl, get_data,
			   function(data){
						CheckOfflineDownloadTaskCallback(data);
					});
}
function CheckOfflineDownloadTaskCallback(data)
{
	console.log('11111111111111111111',data);
	if (data.hasOwnProperty('task_info'))
	{
		task_info = data.task_info;
		for (id in task_info)
		{
			if (task_info[id].result == 0)
			{
				if (task_info[id].status == 0)
				{
					for (i in OfflineDownload_List)
					{
						if (OfflineDownload_List[i].hasOwnProperty(id))
						{
							path = OfflineDownload_List[i][id];
							console.log('11111111111111111111',path);
							var node = zTree.getNodeByParam("abspath", path );
							GetSelectNodeDirInfo(node);
						}
					}
					
				}
				else
				{
					//not complete
				}
			}
			else
			{
				//query fail
			}
		}
	}
}



















	
	
function MakeDir(path)
	{
		basicUrl = 'https://pcs.baidu.com/rest/2.0/pcs/file?';
		url = basicUrl + "&method=mkdir" + "&path=" +encodeURIComponent(path) + "&access_token=" +encodeURIComponent(login_data.BaiduToken)
		url = url + "&callback=MakeDirCallback";
		
		var script = document.createElement('script');
		script.setAttribute('src', url);
		document.getElementsByTagName('head')[0].appendChild(script); 
	}
function MakeDirCallback(data)
	{
		//console.log('MakeDirCallback callback:',data);
		if ( data.hasOwnProperty('error_msg') )
		{
			alert(data.error_msg);
		}
		else
		{
			ls = data.path.split('/')
			ls.pop(ls.length);
			path = ''
			for (x in ls)
			{
				if (ls[x]!='')
				{
				path = path+"/"+ls[x];
				}
			}
			//console.log('MakeDirCallback path:',path);
			var node = zTree.getNodeByParam("abspath", path );
			//console.log('MakeDirCallback node:',node);
			dir_info = new Object();
			for (i in node.nodes)
			{
				//fs_id = node.nodes[i].fs_id;
				//del_node = zTree.getNodeByParam("fs_id", fs_id );
				//zTree.removeNode(del_node);
			}

			GetDirInfo(node.abspath, dir_info, node.id);
		}
	}




	



function zTreeOnExpand(event, treeId, treeNode) 
{
	return;
}
	



function zTreeOnChange(event, treeId, treeNode) 
{
	ChangeToolBarState();
}
function onFileDoubleClick(event,elem)
{
	return;
}



		
function onDownloadCallBack(fileData)
{
	test = fileData;
	//console.log('onDownloadCallBack :',fileData);
	var data = {};
	data.file= fileData;
	$.post("/ZTECloud/DownloadSucc",data,function(){});
}

function OnNew(elem, event)
	{
		
		if ( $(elem).hasClass("disabled") )
		{
			return;
		}
		
		$('#progressLabel').html(RefreshingLabel);
		$('#progress').modal();
		
		
		var selectedNode = zTree.getSelectedNode();
		var path = '';
		selectedNode.haveGetSubnodes = false;
		//console.log('on new :',selectedNode);
		if (selectedNode.isdir == 1)
		{
			temp_node = selectedNode;
			path = selectedNode.abspath;
		}
		else
		{
			temp_node = selectedNode.parentNode;
			path = selectedNode.parentNode.abspath;
		}
		
		folder_name = CheckRename(NewFolderLabel,temp_node, 0)
		path = path + '/' + folder_name;
		MakeDir(path);
	}
function CheckRename(ref_name, node, num)
	{
		if (num>0)
			{
			test_name = ref_name+ num;
			}
		else
		{
			test_name = ref_name;
		}
		//console.log('on CheckRename :',ref_name, test_name);
		flag = name_exist(test_name, node)
		if (flag==true)
		{
			num = num+1
			return CheckRename(ref_name, node, num)
		}
		else
		{
		if (num > 0)
			{
			return ref_name + num;
			}
		else
		{
			return ref_name;
		}
		}
	}
function name_exist(name, node)
	{
		//console.log('on name_exist :',name, node);
		for(x in node.nodes)
		{
			if (node.nodes[x].name == name)
			{
			return true;
			}
		}
		return false;
	}
function OnLabelClickRename(elem, event)
{
	//console.log('label click',elem);
	test2 = elem;
	p_elem = elem.parentElement;
	$(p_elem).addClass("selected");
	label = $(p_elem).find('label');
	text=label.html();
	if ((text == "我的图片")||(text == "我的文档")||(text == "我收到的文件"))
		{
			return;
		}
	label.removeClass("show");
	label.addClass("hide");
	input = $('#right').find('.selected').find('input');
	input.removeClass("hide");
	input.addClass("show");
	test = input;
	$(input).val(text);
	$(input).select();
}
function OnRename(event)
	{
		label = $('#right').find('.selected').find('label');
		text=label.html();
		if ((text == "我的图片")||(text == "我的文档")||(text == "我收到的文件"))
			{
				return;
			}
		label.removeClass("show");
		label.addClass("hide");
		input = $('#right').find('.selected').find('input');
		input.removeClass("hide");
		input.addClass("show");
		test = input;
		$(input).val(text);
		$(input).select();
	}
function  inputOnBlur(elem)
	{
		//console.log('blur',elem);
		text = elem.value;
		DoRename(text);
	}
function OnKeyDown(elem,event)
	{
		if(event.keyCode == 13)
		{
			//console.log('enter',elem);
			text = elem.value;
			DoRename(text);
		}
	}
function DoRename(text)
	{
		
		label = $('#right').find('.selected').find('label');
		label.removeClass("hide");
		label.addClass("show");
		label.html(text);
		input = $('#right').find('.selected').find('input');
		label.removeClass("show");
		input.addClass("hide");
		
		var selectedNode = zTree.getCheckedNodes();
		from = selectedNode[0].abspath;
		temp = from.split('/');
		temp.pop();
		temp.push(text);
		//console.log('zzzzz',temp);
		to = '';
		
		for (i in temp)
		{
			if (temp[i] != "")
			{
				to = to + '/' + temp[i];
			}
		}
		if (from == to)
		{
			return;
		}
		var node = zTree.getNodeByParam("abspath", from );
		node.abspath = to;
		temp = to.split('/');
		node.name = temp.pop();
		zTree.updateNode(node, true);
	
		url = 'https://pcs.baidu.com/rest/2.0/pcs/file',
		get_data = {"access_token":login_data.BaiduToken,
					"from":from,
					"to":to,
					"method":"move",
					}
		$.get(url, get_data,
		  function(data){
							OnMoveCallback(data, from, to);
						});
		
	}
function OnMoveCallback(data, prePath, lastPath)
{
	console.log('OnMoveCallback',data);


	
	//pNode = node.parentNode;
	//pNode.haveGetSubnodes = false;
	//GetSelectNodeDirInfo(pNode);

		
}
function OnDelete(elem)
	{
		if ( $(elem).hasClass("disabled") )
		{
			return;
		}
		var selectedNode = zTree.getCheckedNodes();
		
		for (i in selectedNode)
		{
		 if ((selectedNode[i].name == "我的图片")||(selectedNode[i].name == "我的文档")||(selectedNode[i].name == "我收到的文件"))
		 {
			alert("默认目录不能删除");
			return;
		 }
		}
		
		$('#progressLabel').html(RefreshingLabel);
		$('#progress').modal();
		
		if (selectedNode.length == 1)
		{
			get_data = {"access_token":login_data.BaiduToken,
						"path":selectedNode[0].abspath,
						"method":"delete",
						}
		}
		else
		{
			ls = new Array();
			for (i in selectedNode)
			{
				ls[i] = {'path':selectedNode[i].abspath};
			}
			
			param = {'list':ls};
			test = param;
			//console.log('OnDelete param',param);
			get_data = {"access_token":login_data.BaiduToken,
						"param":JSON.stringify(param),
						"method":"delete",
						}
		}

		url = 'https://pcs.baidu.com/rest/2.0/pcs/file',
		//console.log('OnDelete',get_data);
		$.get(url, get_data,
		  function(data){
			onDeleteCallBack(data, selectedNode);

	  });
	}
function onDeleteCallBack(data, selectedNode)
	{
	//console.log('ondeletecallback',data);
	if (selectedNode.length == 1)
		{
		zTree.removeNode(selectedNode[0]);
		}
	else
		{
			for (i in selectedNode)
			{
				zTree.removeNode(selectedNode[i]);
			}
		}
	zTree.checkAllNodes(false);
	GetStorageInfo();
	ShowRightPanel();
	}
function OnCopy(elem)
	{
		if ( $(elem).hasClass("disabled") )
		{
			return;
		}
		
		userHaveDoneCopyOrCut = true;
		var checkedNode = zTree.getCheckedNodes();
		path_list = new Array();
		copyOrCutList = new Array();
		for (i in checkedNode)
		{
			path_list.push(checkedNode[i].abspath);
		}
		console.log('oncopy',path_list);
		GetParentPath(path_list);
		

	}
function GetParentPath(path_list)
{
	for (i in path_list)
	{
		flag = IsSubPath(path_list[i], path_list);

		if ( flag != true )
		{
			copyOrCutList.push(flag);
		}
	}
	console.log('GetParentPath res',copyOrCutList);
	
	$('.paste').removeClass("disabled");	
	var data = {};
	data.file= SelectedFileHasCopyed;
	$.post("/ZTECloud/ShowMessageBox",data,function(){});

}
function IsSubPath(element,list)
{
	exist_flag = false;
	for (i in list)
	{	
		
		if (element == list[i])
		{
			continue;
		}
		match_flag = element.match(list[i]);
		//console.log(element, list[i], match_flag)
		if ( match_flag != null)
		{
			exist_flag = true;
			break;
		}
		else
		{
			exist_flag = false;
		}
	}
	
	if (exist_flag == true)
	{
		return true;
	}
	else
	{
		return element;
	}
}
function OnPaste(elem)
	{
		if ( $(elem).hasClass("disabled") )
		{
			return;
		}
		if ( copyOrCutList.length == 0)
		{
			return;
		}
		ShowProgress(Cloud_PasteingLabel);
		var selectedNode =  zTree.getSelectedNode();
		
		if (copyOrCutList.length == 1)
		{
			from = copyOrCutList[0];
			temp = from.split('/');
			name = temp.pop();
			var node = zTree.getNodeByParam("abspath", from );
			re_name = PasteCheckRename(name,selectedNode, node.isdir);
			to = selectedNode.abspath+'/'+re_name;
			
			get_data = {"access_token":login_data.BaiduToken,
						"from":from,
						'to':to,
						"method":"copy",
						}
			
		}
		else
		{
			
			param = new Object();
			list = new Array();
			for (i in copyOrCutList)
			{
				from = copyOrCutList[i];
				temp = from.split('/');
				name = temp.pop();
				var node = zTree.getNodeByParam("abspath", from );
				re_name = PasteCheckRename(name,selectedNode, node.isdir);
				to = selectedNode.abspath+'/'+re_name;
				list.push({'from':from,'to':to});
			}
			param = {'list':list};
			get_data = {"access_token":login_data.BaiduToken,
						"param":JSON.stringify(param),
						"method":"copy",
						}
			
		}
		
		url = 'https://pcs.baidu.com/rest/2.0/pcs/file',

		$.get(url, get_data,
		  function(data){
			OnPasteCallBack(data, selectedNode);

		});
		
	}
function PasteCheckRename(name,selectedNode, type)
{
	if (type == 1)
	{
		return PasteGetFolderRename(name, selectedNode, 0);
	}
	else
	{
		return PasteGetFileRename(name, selectedNode, 0);
	}
}

function PasteGetFileRename(elem, node, num)
	{
		if (num > 0)
		{
			ref_name = GetFileCopyName(elem, num);
		}
		else
		{
			ref_name = elem;
		}
		flag = name_exist(ref_name, node)
		if (flag == true)
		{
			num = num + 1;
			return PasteGetFileRename(elem, node, num)
		}
		else
		{
			if (num > 0)
			{
				return GetFileCopyName(elem, num);
			}
			else
			{
				return elem;
			}
		}
	}
function GetFileCopyName(elem, num)
	{
		temp = elem.split('.');
		len = temp.length;
		temp[len-2] = temp[len-2] + ' 副本' + num;
		name = temp[0];
		for (i in temp)
		{
			if (i == 0)
			{
				continue;
			}
			name = name +  '.' + temp[i];
		}
		return name
	}

function PasteGetFolderRename(ref_name, node, num)
	{
		if (num>0)
			{
			test_name = ref_name+ num;
			}
		else
		{
			test_name = ref_name;
		}
		//console.log('on CheckRename :',ref_name, test_name);
		flag = name_exist(test_name, node)
		if (flag==true)
		{
			num = num+1
			return CheckRename(ref_name, node, num)
		}
		else
		{
		if (num > 0)
			{
			return ref_name + ' ' + CopyLabel + num;
			}
		else
		{
			return ref_name;
		}
		}
	}
function OnPasteCallBack(data, node)
{
	OnRefresh();
	console.log('OnPasteCallBack',data);
	test2 = data;
	list = (jQuery.parseJSON(data))['extra']['list']
	for (i in list)
	{
		from = list[i]['from'];
		var node = zTree.getNodeByParam("abspath", from );
		if (node.isdir == 1)
		{
			to = list[i]['to'];
			selectedNode = zTree.getNodeByParam("abspath", to );
			GetSelectNodeDirInfo(selectedNode);
		}
	}
	
	
}
function OnExit()
	{
		var data = {};
		data.code = '';
		$.post("/ZTECloud/CloudExit", data);
		$('#UserOperate').css('display','none');
	}
function OnUserNameClick()
{
	elem = $('#UserOperate')
	if (elem[0].style.display=='block')
	{
		$('#UserOperate').css('display','none');
	}
	else
	{
		$('#UserOperate').css('display','block');
	}
}
function ModifyUserInfo()
{
	var data = {};
	data.code = '';
	$.post("/ZTECloud/ManageUserInfo", data);
	$('#UserOperate').css('display','none');
}

function OnMouseHover1(elem)
{
	$(elem).css("background-color",'#DDD');
}
function OnMouseOut1(elem)
{
	$(elem).css("background-color",'#EEE');
}