var DATA_SEPARATOR_FOR_MT="========\t\t\t=========";
var g_strCategoryId = "";
var g_strPageNum = 1;
var g_strOrderby = "time_dec"
var g_LastAjaxTime = 0;
var g_strTopicId = "";
var g_LastAutoRefreshTableTime = 0;
var g_strCgitype = "";

$(document).ready(function(){
    g_TimeoutId = setTimeout(refreshTableAuto, 500);
	if( g_isUpdating == "true")
	//if(typeof(g_isUpdating)!="undefined" )
	{	
		showRefreshing();
		QueryIsRunning();		
	}
	
		//首页显示隐藏Member信息
	$(".memberbg").each(function(){
		$(this).mouseover(function(){
			$(this).find(".Memberinfolist").css("display","block");										
	    }).mouseout(function(){
			$(this).find(".Memberinfolist").css("display","none");		
		});					 
	});
	
	if(typeof(g_strGroupId)!="undefined" )
	{
		isGroupDelete();	
	}
})

function isGroupDelete()
{
	$.ajax({
	    async: true,
		url: '/GroupSpaceaction.cgi',
		type: 'POST',
		cache: false,
		data:{
			groupId:g_strGroupId,
			action:"isGroupDelete"	
			},
		success: function(data)
		{	
			if(data == "true")
			{
				
				deletegroupdata()
			}
		    else 
			{
				
			}
        }
	});	
}
function changePageOnkey(e)
{
	var m_e = e||event;
	var key = m_e.keyCode || m_e.which || m_e.charCode; 
	if(parseInt(key)==13)
	{
		gotoInputPage();
	}
}


function getTime()
{
	var s_dtCurr = new Date();
	var s_nRand = parseInt(Math.random() * 10000 + 10000);
	var strDate = "" + s_dtCurr.getYear() + s_dtCurr.getMonth() + s_dtCurr.getDate()
		+ s_dtCurr.getHours() + s_dtCurr.getMinutes() + s_dtCurr.getSeconds() 
		+ s_dtCurr.getMilliseconds() + s_nRand;   //时间戳
	return strDate;

}


function index_order(strOrderby)
{
	g_strCgitype = "typeOrderby";
	g_strPageNum = "0";
	g_strOrderby = strOrderby;
	if(typeof(g_strGroupId)!="undefined" )
	{
		excuteAction("showdata");		
	}
	else
	{
		excutedownAction("showdata");	
	}
	
}


function browse(obj,categoryId)
{    
	//展开当前点击节点的一级子节点 //折叠非当前节点的所在的一级节点的同级节点
	g_strCgitype = "typeNavi";
	showOrHideSiblingUL(obj);	
	if(g_strCategoryId != categoryId)
	{
		g_strCategoryId = categoryId;
		g_strPageNum = 1;
	    g_strOrderby = "time_dec"
	}
	//运维活运的箭头复原 向下
	excuteAction("showdata");
	
	//导航很长时，跳页面到顶部  DTS2012042805466 
	jumpToTop();
}
function showOrHideSiblingUL(node)
{
	/*
	结构是 <li>
	         <span selected>...</span>
			 <ul>
               <li>
			     <span>...</span>
				 <ul>
				  ...
				 </ul> 
               </li>			   
			 </ul>
		   </li>
		   ...
	*/
	//传入的node是<span>
	//1. 显示 //或隐藏子节点 
	//当前选中节点展开子节点
	var $nodeParent = $(node).parent();
	var liChildrenNodes = $nodeParent.children(); 
	for(var i = 0; i < liChildrenNodes.length; i++)
	{
		var $child = $(liChildrenNodes[i]);
        		
		if($child.is("ul"))
		{			
			if($child.css("display") == "none")
			{			
				$child.css("display","");
				$nodeParent.removeClass("close");
				$nodeParent.addClass("open");
				
			}
			//  2012.6.12 add  导航可折叠
			else
			{
			    $child.css("display","none");
				$nodeParent.removeClass("open");
				$nodeParent.addClass("close");
			}
			// end 2012.6.12 add  导航可折叠
		}		
	}
	//收起当前节点的同级节点
	var parentSilblingLiNodes = $(node).parent().siblings();
	$(parentSilblingLiNodes).each(function(){
		$(this).removeClass("open");
		$(this).addClass("close");		
	    $(this).find("ul").each(function(){												 
									$(this).css("display","none");									
								});
		$(this).find("li.open").each(function(){
											  $(this).removeClass("open");
											  $(this).addClass("close");
											  });
	});	
	
	
}

//跳页面到顶部 
function jumpToTop()
{      
   $('html,body').animate({scrollTop:0}, 1600);
}
function startdl(topicId)
{	
	g_strTopicId = topicId;	
	g_strCgitype = "startdl";
	excuteAction("startdl");
	
}
function pausedl(topicId)
{
	g_strTopicId = topicId;	
	g_strCgitype = "pausedl";
	excuteAction("pausedl");
}
function canceldl(topicId)
{
	g_strTopicId = topicId;	
	g_strCgitype = "canceldl";
	excuteAction("canceldl");
}

function excuteAction(strAction)
{
	g_LastAjaxTime = getTime();

	$.ajax({
	    async: true,
		url: '/GroupSpaceaction.cgi',
		type: 'POST',
		cache: false,
		data:{
			action:strAction,
			groupId:g_strGroupId,
			categoryId:g_strCategoryId,			
			pageNum:g_strPageNum,
			orderBy:g_strOrderby,
			topicId:g_strTopicId,
			timestamp:g_LastAjaxTime,
			cgiaction:g_strCgitype
			},
		success: function(data)
		{	
			if(data == "notlogin")
			{
				return;
			}
		    else if(data == "refreshing")
			{
				showRefreshing();
				QueryIsRunning();
			}
			else if(data == "gotowrongpage")
			{
				$(".errormessage_hint").html(msgph_error_message);
				$("#simplemodal-overlay,#simplemodal-container-refresh").hide();				
				$(".hdx_ts_cleft, .hdx_ts_cright, #ourSupportBanner, .gs_news, .hdx_ts_members ").hide();
				$(".backButton, .hdx_refreshPage").hide();
				$(".errorRefreshDiv").show();
				
			}
					
			else
			{
				updateTable(data);
			}
		    	
        }
	});	
}

//在线浏览文档时，做自动登录处理
function BrowseTopic(strBrowseUrl)
{
	 var strDestUrl =  "/loginSupport.cgi?action=AutoLogin&url=";
	 strDestUrl = strDestUrl + handlerSpecialCharsWithDoubleEscape(strBrowseUrl);
	 window.open(strDestUrl);
}
function OpenSupportUrl(strUrl)
{
	var strDestUrl =  "/loginSupport.cgi?action=AutoLogin&url=";
	strDestUrl = strDestUrl + handlerSpecialCharsWithDoubleEscape(strUrl);
 	window.open(strDestUrl);
}
//字符串转码，用于url的前后台传递*/
function handlerSpecialCharsWithDoubleEscape(value)
{
	value =escape(escape(value));
	value=value.replaceAll("+", "%2B");
	value=value.replaceAll("@", "%40");
	return value;
}

//字符串替换
String.prototype.replaceAll=function(pattern, replacement) {
    var result = '', source = this;
    var match;

    while (source.length > 0) {
      match = source.indexOf(pattern);
      if (match>=0) {
        result += source.slice(0, match);
        result += replacement;
        source  = source.slice(match + pattern.length);
      } else {
        result += source, source = '';
      }
    }
    return result;
}
//根据页码跳转
function gotoPage(pageNum)
{
   //取当前页码
	g_strCgitype = "page";
  	g_strPageNum = pageNum;
	if(typeof(g_strGroupId)!="undefined" )
	{
		 excuteAction("showdata");
	}
	else
	{
		excutedownAction("showdata");
	}
   
		
}

//获取输入的页码，并根据页码跳转
function gotoInputPage()
{
	var rowPerPage;
	var num = $("#hdx_ts_goto").attr("value");
	var totalnum = $("#id_totalNum").attr("totalnum");
	if(typeof(g_strGroupId) !="undefined")
	{
		//Group Space接口变更以后，团队应用页面只显示八篇文档（每页）
		rowPerPage = 8;
	}
	else
	{
		rowPerPage = 10;
	} 
	var patrn=/^\d+$/;
	if (patrn.exec(num) != null)
	{
	    num = parseInt(num, 10);
		totalnum = parseInt(totalnum);
		var totalpagefloat = totalnum/rowPerPage;
		var totalpage = Math.floor(totalpagefloat);
		if((totalpagefloat-totalpage)>0)
		{
			totalpage = totalpage+1;
		}
		if(num > totalpage)
		{
			gotoPage(totalpage);
		}
		else
		{
			gotoPage(num);
		}
	}
	else
	{
		$("#hdx_ts_goto").attr("value", "");
	}
}
function updateTable(data)
{
	if(data != "")
	{
		var dataattr = data.split(DATA_SEPARATOR_FOR_MT);
		
		if(dataattr.length < 2)
		{
			return;
		}
		
		var attr = [];
		attr[0] = dataattr[0]+"";
		attr[1] = dataattr[1]+"";
		if(attr[0] == g_LastAjaxTime)
		{			
		    var $contentHtmlInAjax = $("<div></div>");
			$contentHtmlInAjax.html(attr[1]);
			var $sortBarInAjax = $contentHtmlInAjax.find(".hdx_ts_crtoolbar");
			var $contentInAjax = $contentHtmlInAjax.find(".hdx_ts_crcon");
			var $pageBarInAjax = $contentHtmlInAjax.find(".hdx_ts_crpagebar");
			
			var $contentHtmlContainerInHtml = $(".hdx_ts_cright");
			var $sortBarInHtml = $contentHtmlContainerInHtml.find(".hdx_ts_crtoolbar");
			var $contentInHtml = $contentHtmlContainerInHtml.find(".hdx_ts_crcon");
			var $pageBarInHtml = $contentHtmlContainerInHtml.find(".hdx_ts_crpagebar");
			
			
			if(($sortBarInAjax.attr("requestParam") == $sortBarInHtml.attr("requestParam"))
			   && ($pageBarInAjax.find("#id_totalNum").html() == $pageBarInHtml.find("#id_totalNum").html()))
			{
				var $dataRowsInHtml = $contentInHtml.find(".ts_list_unit");
				var $dataRowsInAjax = $contentInAjax.find(".ts_list_unit");
				
				for(var i = 0; i < $dataRowsInHtml.length; i++)
				{					
					var strClassInHtml = $($dataRowsInHtml[i]).find(".ts_list_r_right>div").attr("class");
					var strClassInAjax = $($dataRowsInAjax[i]).find(".ts_list_r_right>div").attr("class");				
					
					if(strClassInHtml == strClassInAjax)
					{
						if(strClassInHtml.indexOf("download_ing") > -1)
						{							
							$($dataRowsInHtml[i]).find(".pbarTxt").html($($dataRowsInAjax[i]).find(".pbarTxt").html());									
						}						
					}
					else
					{
						$($dataRowsInHtml[i]).find(".ts_list_r_right").html($($dataRowsInAjax[i]).find(".ts_list_r_right").html());					
					}					
				}
				
				
			}
			else
			{
				$contentHtmlContainerInHtml.html($contentHtmlInAjax.html());
			}
		
	
		}				
	}
}

function Setting()
{	
	g_LastAjaxTime = getTime();
	$.post("/GroupSpaceaction.cgi",{action: "setting"},function(data){	});
}

function Refresh()
{
	$.ajax({
		async: true,
		url: '/GroupSpaceaction.cgi',
		type: 'POST',
		cache: false,
		data:{
			action:"RefreshData"			
		},
		success: function(data)
		{	
			if(data == "notlogin")
			{
				return;
			}
		    showRefreshing();
			QueryIsRunning();		
		}
	});				
}


function showNewDocs()
{
	var strOpenUrl = "/GroupSpace.cgi?groupId="+g_strGroupId+"&isAutoRefresh=false"
    strOpenUrl = appendTimeToUrl(strOpenUrl);
	window.location.href=strOpenUrl;		
	
}


function queryAppRunning()
{

$.ajax({
		async: true,
		url: '/GroupSpaceaction.cgi',
		type: 'POST',
		cache: false,
		data:{
			action:"queryRefreshApp",
			groupId:g_strGroupId			
		},
		success: function(data)
		{
			if(data == "refreshing")
			{	
				$(".refreshdiv").find(".refreshhasdata").hide();	
				$(".refreshdiv").find(".refreshnormal").hide();	
				$(".refreshdiv").find(".refreshingdata").show();					
				setTimeout(queryAppRunning,500);
			}
			else if(data == "success_hasdata")
			{
			    $(".refreshdiv").find("a").hide();
				$(".refreshdiv").find(".refreshhasdata").show();
				
			
			}
			else if(data == "failed")
			{
			    $(".refreshdiv").find("a").hide();
				$(".refreshdiv").find(".refreshnormal").show();
			 			
			}
			else
			{
			    $(".refreshdiv").find("a").hide();
				$(".refreshdiv").find(".refreshnormal").show();
			}
	    }
	});		


}

function appendTimeToUrl(strOpenUrl)
{
	var iTimePosStart = strOpenUrl.indexOf("&time=");
	if(iTimePosStart > 0)
	{
		iTimeEnd = strOpenUrl.indexOf("&",iTimePosStart+1);
		if(iTimeEnd >0)
		{
			strOpenUrl = strOpenUrl.substring(0,iTimePosStart) + strOpenUrl.substring(iTimeEnd);					
		}
		else
		{
			strOpenUrl = strOpenUrl.substring(0,iTimePosStart);					
		}
	}


	strOpenUrl += "&time="+getTime();
	return strOpenUrl;
}
function QueryIsRunning()
{
    var arrDataParam = {action:"queryRefresh"}
    if(typeof(g_bIsIncrementRefresh) !="undefined" )
	{
	   arrDataParam = {
	       action:"queryRefresh",
		   groupId:g_strGroupId,
		   bIsIncrementRefresh:g_bIsIncrementRefresh
	   }
	}
    
	$.ajax({
		async: true,
		url: '/GroupSpaceaction.cgi',
		type: 'POST',
		cache: false,
		data:arrDataParam,
		success: function(data)
		{
			if(data == "refreshing")
			{				
				setTimeout(QueryIsRunning,500);
			}
			else if(data == "success")
			{
				$("#simplemodal-overlay").fadeOut();
				$("#simplemodal-container-refresh").fadeOut();
				//excuteAction("showdata");
				
			
				var strOpenUrl = window.location.href+"";
				
				if(typeof(g_bIsIncrementRefresh) !="undefined")
				{
					strOpenUrl = "/GroupSpace.cgi?groupId="+g_strGroupId+"&topicId=" + g_strTopicId +"&isAutoRefresh=false"
		
				}
				
				strOpenUrl = appendTimeToUrl(strOpenUrl)
				
				window.location.href=strOpenUrl;		
				
			
			}
			else  if(data == "failed")
			{
				$("#simplemodal-overlay,#simplemodal-container-refresh").hide();				
				$(".hdx_ts_cleft, .hdx_ts_cright, #ourSupportBanner, .gs_news, .hdx_ts_members").hide();
				$(".errorRefreshDiv").show();
			}
	    }
	});		
	
}
function Back()
{
	$(".errorRefreshDiv").hide();
	$(".hdx_ts_cleft, .hdx_ts_cright, #ourSupportBanner, .gs_news, .hdx_ts_members").show();
	excuteAction("showdata");
}
function isRunningTaskExist()
{
	var bFlag = false;

	if(($(".download_ing").length>0)
		 ||($(".download_wait").length>0))
	{
		bFlag = true;	
	}
    return bFlag;
	

}

function refreshTableAuto()
{

	if(g_LastAutoRefreshTableTime != g_LastAjaxTime)
	{	
		g_LastAutoRefreshTableTime = g_LastAjaxTime;		
		g_TimeoutId = setTimeout(refreshTableAuto, 500);
	}
	else
	{
		var bIsNeedRefresh = false;
		//有正在下载的或强制刷新一次
		if(isRunningTaskExist())//table等于0，说明table由于异常被刷没了
		{
			bIsNeedRefresh = true;	
		}
	
		if(bIsNeedRefresh == true)
		{
			g_LastAjaxTime = getTime();	
			
			$.ajax({
				async: true,
				url: '/GroupSpaceaction.cgi',
				type: 'POST',
				cache: false,
				data:{
					action:"showdata",
					groupId:g_strGroupId,
					categoryId:g_strCategoryId,			
					pageNum:g_strPageNum,
					orderBy:g_strOrderby,
					topicId:g_strTopicId,
					timestamp:g_LastAjaxTime
					},
				success: function(data)
				{			
					updateTable(data);
					g_LastAutoRefreshTableTime = g_LastAjaxTime;					
					g_TimeoutId = setTimeout(refreshTableAuto, 500);
					
			   }
			});				
		}
		else
		{
			g_TimeoutId = setTimeout(refreshTableAuto, 500);
		}
		
	}
}



function opendowntopic(topicId)
{
	
	g_strTopicId = topicId;
	excutedownAction("opendowntopic");
}

function openTopic(topicId)
{
	g_strTopicId = topicId;
	excuteAction("opentopic");
}
function openDir(topicId)
{
	g_strTopicId = topicId;
	excuteAction("opendir");
}
function deletetopic(topicId)
{
	var sure=confirm(msgph_del_file);  //DTS2012011002162 增加删除时提示
	if(sure==false)
	{
		return;
	}
	g_strTopicId = topicId;
	excutedownAction("deletetopic");
}
function deletegroupdata()
{
	var sure=confirm(msgph_del_group);  //DTS2012011002162 增加删除时提示
	if(sure==false)
	{
		excuteAction("canceldeletegroupdata");
		return;
	}
	
	excuteAction("deletegroupdata");
}
/*function ConfirmDleteGroupData(groupid)
{
	var sure=confirm("是否删除该团队数据");  //DTS2012011002162 增加删除时提示
	if(sure==false)
	{
		return;
	}
	
	excuteAction("deletegroup");
	
}*/
function updateDownTable(data)
{
	if(data != "")
	{
		var dataattr = data.split(DATA_SEPARATOR_FOR_MT);
		if(dataattr.length < 2)
		{
			return;
		}
		
		var attr = [];
		attr[0] = dataattr[0]+"";
		attr[1] = dataattr[1]+"";
		if(attr[0] == g_LastAjaxTime)
		{					
			$(".hdx_mydl_cright").html(attr[1]);
		}				
	}
}
function excutedownAction(strAction)
{
	g_LastAjaxTime = getTime();

	$.ajax({
	    async: true,
		url: '/GroupSpacedownaction.cgi',
		type: 'POST',
		cache: false,
		data:{
			action:strAction,	
			pageNum:g_strPageNum,
			orderBy:g_strOrderby,
			topicId:g_strTopicId,
			timestamp:g_LastAjaxTime,
			cgiaction:g_strCgitype
			},
		success: function(data)
		{	
			updateDownTable(data);
        }
	});	
}



var iTest = 1;
function showRefreshing()
{  

    //出现浮动层页面，阻止进一步操作
	var $modal = $("#basicModalContent");
	$modal.modal({containerId: 'simplemodal-container-refresh'});  
	if($("#simplemodal-overlay").length >= 1)
	{
		var el = $(window);
	
		// fix a jQuery/Opera bug with determining the window height
		var h = $.browser.opera && $.browser.version > '9.5' && $.fn.jquery <= '1.2.6' ? document.documentElement['clientHeight'] :
			$.browser.opera && $.browser.version < '9.5' && $.fn.jquery > '1.2.6' ? window.innerHeight :
			el.height();

		if(h < $("body").height())
		{
			h = $("body").height();
		}
	
		$("#simplemodal-overlay").height(h);
	}
	
	$("#simplemodal-overlay").show();
	$("#simplemodal-container-refresh").show();
}


function select_allFiles(node){
	var checked = node.checked;
	
	var $checks = $(".single_sel_chk").find("input");
	
	jQuery.each( $checks, function( _, node ){
		node.checked = checked;	
	} );
	
}

function downloadMutilTask(){
	var tasks = $(".single_sel_chk").find("input");
	tasks = tasks.filter( function(){
		return this.checked;
	} );
	
	if( tasks.length ){	
		jQuery.each(tasks, function( _, node ){
			var $parent = $(node).parent(),
				$next = $parent.next().next(),
			  $button = $($next.find("div")[0]).find("button").eq(0),
			  statesDiv = $next.get(0).firstChild,
			  strTaskId = $(statesDiv).attr("taskId");
		   
		   if( $(statesDiv).hasClass("download_error") 
		   || $(statesDiv).hasClass("download_pause")
		   || $(statesDiv).hasClass("download_init")){
			startdl( strTaskId ); 
		   }
		    
		});
		
	}
	else
	{
		alert(msgph_dwonload_select_zero);
		
	}
}

function checkSelectAll(){
		var $checks = $(".single_sel_chk").find("input");
		var bchecked = true;
		
		jQuery.each($checks, function( _, node ){
			if( !node.checked ){
				bchecked = false;
				return false;
			}
		});
		
		var elem = document.getElementById("input_sel_all");
		
		if( elem && bchecked !== elem.checked ){
			elem.checked = bchecked;
		}
}


