//此托盘给km的新建文件用
$(document).ready(function(){
	
	var progressId;
	
	var isTrayReady = false;
	var trayProgress;
	var wordFieldChecker;
	
	
	$.ajax({
		url: trayHost+'/ping',
		dataType: 'jsonp',
		timeout: 2000,
	   	jsonp: 'jsonpCallback',
		success:function(result){
			if(result.state == 1){
				isTrayReady = true;
				setServerHost();
			}
		},
		error:function (XMLHttpRequest, textStatus, errorThrown) {
			//测试网络连通性
			trayProgress = window.setInterval(function(){
				$.ajax({
					url: trayHost+'/ping',
					dataType: 'jsonp',
					timeout: 2000,
				   	jsonp: 'jsonpCallback',
					success:function(result){
						if(result.state == 1){
							window.clearInterval(trayProgress);
							isTrayReady = true;
							setServerHost();
						}
					},
					error:function (XMLHttpRequest, textStatus, errorThrown) {
					}
				});
			}, 4*1000);
		}
	});
	
	
	function setServerHost(){
		$.ajax({
			async:false,
			url: trayHost+'/setServerHost?host='+serverHost,
			dataType: 'jsonp',
		   	jsonp: 'jsonpCallback',
			success:function(result){
				if(result.state == 1){
					if(action == "edit"){
						$(".activity-edit").show();
					}
				}
			},
			error:function (XMLHttpRequest, textStatus, errorThrown) {
			}
		});
	}
		
	if(action == "edit"){
		$(".activity-edit").show().on("click",function(e){
			$.ajax({
				async:false,
				url : '/kms/api/kms/edit/time?fileId='+id,
				type: 'post',
				dataType : "json",
				complete : function(){
					
				}
			});

			const openType = "tray";
			if(openType=="jinge"){
				wordFieldChecker = new WordFieldChecker(curEditUserId,name)
				if(!wordFieldChecker.checkWordFieldIsEdit()){
					return;
				}
				var url = "../../../asset/preview/webofficeWord.html?path="+path+"&name="+name;
				if(parent.WebUser){
					url = url + "&username="+parent.WebUser.name+"&tempfile="+(parent.PETE_TEMPL!=undefined ? parent.PETE_TEMPL : "");
				}
				if(parent.PETE_temp_url){
					url = url + "&" + parent.PETE_temp_url;
				}
				//自身浏览器打开
				var mhtmlHeight = window.screen.availHeight; //获得窗口的垂直位置;
				var mhtmlWidth = window.screen.availWidth; //获得窗口的水平位置; 
				var iTop = 0; //获得窗口的垂直位置;
				var iLeft = 0; //获得窗口的水平位置;
				window.open(url);
				//暂时利用页签切换刷新预览
				document.addEventListener('visibilitychange', visibilitychange,false);
				function visibilitychange() {
				    if (document.hidden) {
				        document.title = '在线编辑中...';
				    } else {
						$("#progress").text("文档更新中...");
						var $container = $(".preview-body-container");
						$(".activity-edit").show();
						window.clearInterval(progressId);
						if(wordFieldChecker != null ){
							wordFieldChecker.doExixtWordField();
							wordFieldChecker = null;
						}
				        setTimeout(function() {
							$("#progress").text("文档已更新！");
							$container.find("iframe").attr("src",previewUrl);
							document.removeEventListener('visibilitychange',visibilitychange,false);
				        },2000);
				    }
				}
			}else{
				if(!isTrayReady){
					if(window.confirm('托盘程序未找到","需要下载托盘程序并安装,点击\"确定\"按钮下载')){
						//下载托盘程序
						url = encodeURI(contextPath + "/uploads/myapps_tray.exe");
						var _tmpwin = window.open(url,"_blank");
						_tmpwin.location.href = url;
					}else{
						return;
					}
				}
				
				// wordFieldChecker = new WordFieldChecker(curEditUserId,name)
				// if(!wordFieldChecker.checkWordFieldIsEdit()){
				// 	return;
				// }
				
				$.ajax({
					async:false,
					url:trayHost+'/download?path='+path+'&name='+name+"&userName="+userName+"&showTrackRevisions=false",
					dataType: 'jsonp',
					jsonp: 'jsonpCallback',
					success:function(result){
						if(result.state == 1){
							if(!result.data){
								startTrayProgress();
							}else{
								alert("抱歉，本地文档正在与服务器同步中，请稍后片刻再进行编辑操作！");
							}
						}
					},
					error:function (XMLHttpRequest, textStatus, errorThrown) {
					}
				});
			}
		});
	}
	
	
	/**
	 * 是否能够获取水印文件
	 */
	function isWaterMarkFile(waterMarkSetting,filename){
		if(openWaterMark == true && waterMarkSetting != null && waterMarkSetting != undefined && waterMarkSetting != "" && waterMarkSetting != "null"){
			var setting  = eval ("(" + waterMarkSetting + ")");
			if(setting.type != null && setting.type.indexOf("download")>-1){
				var fileType = filename.substring(filename.lastIndexOf(".")+1);
				if ("doc"== fileType || "docx"== fileType
						|| "xls"== fileType || "xlsx"== fileType
						|| "pdf"== fileType || "txt"== fileType
						|| "rtf"== fileType || "et"== fileType
						|| "ppt"== fileType || "pptx"== fileType
						|| "dps"== fileType || "pot"== fileType
						|| "pps"== fileType || "wps"== fileType
						|| "html"== fileType || "htm"== fileType) {
					return true;
				}
			}
		}
		return false ;
	}

	/**
	 * work控件检查器：(乐观锁)
	 */
	function WordFieldChecker(curEditUserId,name){
		
		this.curEditUserId = curEditUserId ;
		this.name = name ;
		
		this._wordFieldIsUpdateTimer;    //检查work控件是否已更新定时器
		this._checkWordFieldIsEditTimer; //检查work控件是否在编辑定时器
		
		function checkIsEdit (){
			var params = {
					'userId' : this.curEditUserId,
					'wordid' : this.name
			};
			var _result ;
			$.ajax({
				async:false,
				url : contextPath + '/kms/checkWordFieldIsEdit',
				data : params,
				dataType : "json",
				success : function(result){
					_result = result ;
				}
			});
			return _result;
		}
		
		/**
		 * 从wordFieldIsEdit中去除wordid
		 */
		WordFieldChecker.prototype.doExixtWordField = function(){
			var workChecker = this;
			var params = {
					'userId' : this.curEditUserId,
					'wordid' : this.name
			};
			$.ajax({
				async:false,
				url : contextPath + '/kms/doExixtWordField',
				data : params,
				dataType : "json",
				complete : function(){
					clearWordFieldTimer(workChecker) //清空定时器
				}
			});
			
		}
		
		/**
		 * 清空WordFieldTimer定时器
		 */
		function clearWordFieldTimer(WordFieldChecker){
			if(WordFieldChecker._wordFieldIsUpdateTimer != null){
				window.clearInterval(WordFieldChecker._wordFieldIsUpdateTimer);
				WordFieldChecker._wordFieldIsUpdateTimer = null ;
			}
			if(WordFieldChecker._checkWordFieldIsEditTimer != null ){
				window.clearInterval(WordFieldChecker._checkWordFieldIsEditTimer);
				WordFieldChecker._checkWordFieldIsEditTimer = null ;
			}
		}
		
		if(typeof WordFieldChecker._initialized == "undefined"){
			/**
			 * 检查word文档是否可编辑(Ajax)
			 * 功能点：① _result 返回文档是否可编辑
			 *       ② 定时器，定时更新wordFieldIsEdit容器中时间状态
			 */
			WordFieldChecker.prototype.checkWordFieldIsEdit = function(){
				var _result  = checkIsEdit();
				if(_result==undefined || (_result.state == true && this._checkWordFieldIsEditTimer == null) ){ //可编辑，则定时更新wordFieldIsEdit容器中时间状态
					this._checkWordFieldIsEditTimer =  window.setInterval(function(){
						checkIsEdit();
					}
				, 1*10000);
				}else{
					var message = _result.message + "正在编辑文档，请稍后";
			    	OBPM.message.showConfirm(message,"点击\"确定\"按钮以等待更新文档",function(result){
						if(result){//确认框--确认执行
							wordFieldIsUpdateTimer()
						}
					});
				}
				return _result.state ;
			}
			
			/**
			 * 检查word文档是否被他人编辑完成
			 */
			function wordFieldIsUpdateTimer (){
				if(this._wordFieldIsUpdateTimer == null){
					this._wordFieldIsUpdateTimer = window.setInterval(function(){
						var _result  = checkIsEdit();
						if(_result.state == true){
							var wordChecker = this;
							/*更新时因为没有清空容器里等待者的数据*/
							clearWordFieldTimer(wordChecker)//清空定时器
							$("#progress").text("文档已更新...");
							var $container = $(".preview-body-container");
							$container.find("iframe").attr("src",previewUrl);
						}else{
							var message = _result.message + "正在编辑文档...";
							$("#progress").text(message);
						}
					}, 2*1000);
				}
			}
		}
		WordFieldChecker._initialized = true ;
	}
});