﻿///////////////////////////////////////////////////////////

/*
    打开评分系统面板
*/
function ShowRatingPanel(nCurrVal)
{
    showDebuginfo("CFHBlog.js--ShowRatingPanel","显示打分面板，初始值"+nCurrVal);
    $("#Scores_Area").html("");
    if (typeof WebConfig.CurrentDoc.ResId=="string")
    {
        if (WebConfig.CurrentDoc.ResId!="")
        {
            var RatingUrl = "/AjaxServer/server.ashx?service=statis&method=rating&ResName="+WebConfig.CurrentDoc.ResName+"&ResId="+WebConfig.CurrentDoc.ResId;
            // alert(RatingUrl);
            if (typeof nCurrVal!="number")
                nCurrVal = 0;
            if (nCurrVal>10 || nCurrVal<0)
                nCurrVal = 0;
            
            $('#Scores_Area').rater(RatingUrl, { maxvalue:10, style: 'basic', curvalue:nCurrVal}); 
            return;
        }
    }
    ShowMsg("当前没有选定有效的文档，无法进行评估操作！"); 
}

/*
    顶一下
*/
function AddAF()
{
    if (GetUserCookie("Blog",WebConfig.CurrentDoc.ResId,"AFNG")=="Yes")
    {
        ShowMsg("您已经发表过自己的意见了。如果您想法有改变，需要在1天后才能再次发表意见！");
        return;
    }
    
    if (typeof WebConfig.CurrentDoc.ResId=="string")
    {
        if (WebConfig.CurrentDoc.ResId!="")
        {
           AddAccessLog("Blog",WebConfig.CurrentDoc.ResId,"AF");
           SetUserCookie("Blog",WebConfig.CurrentDoc.ResId,"AFNG");
           Add_AFNG_Client("AF");
           ShowMsg("您的意见已经被保存，谢谢您的参与！");
           return;
        }
    }
    ShowMsg("当前没有选定有效的文档，无法进行评估操作！");
}

/*
    踩一下
*/
function AddNG()
{
    if (GetUserCookie("Blog",WebConfig.CurrentDoc.ResId,"AFNG")=="Yes")
    {
        ShowMsg("您已经发表过自己的意见了。如果您想法有改变，需要在1天后才能再次发表意见！");
        return;
    }
        
    if (typeof WebConfig.CurrentDoc.ResId=="string")
    {
        if (WebConfig.CurrentDoc.ResId!="")
        {
           AddAccessLog("Blog",WebConfig.CurrentDoc.ResId,"NG");
           SetUserCookie("Blog",WebConfig.CurrentDoc.ResId,"AFNG");
           Add_AFNG_Client("NG");
           ShowMsg("您的意见已经被保存，谢谢您的参与！");
           return;
        }
    }
    ShowMsg("当前没有选定有效的文档，无法进行评估操作！");
}

/*
    在客户端直接修改顶踩的数据，不用从服务器取数据刷新
*/
function Add_AFNG_Client(cAFNG)
{
    if (cAFNG=="AF")
    {
        var vAF = parseInt($("#AF").text());
        $("#AF").html(vAF+1);
    }
    if (cAFNG=="NG")
    {
        var vNG = parseInt($("#NG").text());
        $("#NG").html(vNG+1);
    }    
}


/*
    添加Blog的访问计数
*/
function AddBlogAccessLog() {
    showDebuginfo("CFHBlog.js--AddBlogAccessLog", "添加Blog访问计数");
    if (typeof WebConfig.CurrentDoc.ResId=="string")
    {
        if (WebConfig.CurrentDoc.ResId!="")
           AddAccessLog("Blog",WebConfig.CurrentDoc.ResId,"PV",0); // 添加访问统计
    }
}

/*
    显示博文的用户访问统计信息
*/
function ShowBlogStatisInfo()
{
    showDebuginfo("CFHBlog.js--ShowBlogStatisInfo","显示博文访问统计信息！");
    
    if (typeof WebConfig.CurrentDoc.ResId!="string")
    {
        showDebuginfo("CFHBlog.js--ShowBlogStatisInfo","意外错误：WebConfig.CurrentDoc.ResId 不是字符串！");
        return;
    }
    if (WebConfig.CurrentDoc.ResId=="")
    {
        showDebuginfo("CFHBlog.js--ShowBlogStatisInfo","意外错误：WebConfig.CurrentDoc.ResId 为空！");
        return;
    }
    
    // PV UV IP
    $.getJSON("/AjaxServer/Server.ashx?service=statis&method=getresdata",
               {ResName:"Blog",ResId:WebConfig.CurrentDoc.ResId },
               function(data)
               {
                  showDebuginfo("CFHBlog.js--ShowBlogStatisInfo","显示博文的用户访问统计信息: 开始显示--》data.TotalAF="+data.TotalAF+" data.TotalNG="+data.TotalNG);
                  
                  // 顶踩 AF NG
                  $("#AF").html(data.TotalAF);
                  $("#NG").html(data.TotalNG);
                  // 显示打分
                  
                  var AverageVS = 0;
                  if (data.TotalVT >0 && data.TotalVS)
                      AverageVS = Math.floor(data.TotalVS/data.TotalVT);
                      
                  showDebuginfo("CFHBlog.js--ShowBlogStatisInfo","显示平均分 AverageVS="+AverageVS);
                  ShowRatingPanel(AverageVS);
               }
              );
}

/*
    显示当前博文的用户反馈信息
*/
function ShowUserFeedbackInfo()
{
    showDebuginfo("CFHBlog.js--ShowUserFeedbackInfo","显示用户反馈信息！");
    ShowBlogStatisInfo(); // 访问统计信息  
    ListComments("Cmt_List");  // 评论列表；显示评论数量
}

/*
	系统事件:
	指定的频道被激活后的事件(一般情况下是频道分类被点击了)
*/
function ActivateCategory(cId)
{
	ShowDocListByCateId(cId);
}

/*
	文档编辑按钮栏的状态
*/
function InitDocMenu() {
    //alert(WebConfig.Visitor.Username + "==Master:" + WebConfig.Master.Username);
	if (WebConfig.Visitor.Username==WebConfig.Master.Username)
	{
		$("#ArticleMenu").show();
	}
	else
		$("#ArticleMenu").hide();
}

/*
	显示指定博客频道内的文档列表
*/
function ShowDocListByCateId(cId)
{
	$("#DocListTitle").text(GetCateName(cId)+"类别下所有文章");
	
	$(".DocListItemRow").hide();
	$(".DocListItemRow[doc_cate='"+cId+"']").show();
	ShowDocList();
}

/*
	显示所有的文章标题列表（去掉过滤）
*/
function ShowDocListAll()
{
	$(".DocListItemRow").show();
	ShowDocList();
	$("#DocListTitle").text("所有文章");
}


/*
加载最后一篇博文
// 如果 cDocId 无值, 就直接取最后一篇更新的文档
// 如果文档已经在全局变量当中，就直接取得，不用远程请求
*/
function LoadDoc(cDocId)
{
showDebuginfo("CFHBlog.js--LoadDoc","开始加载博客文章！id="+cDocId)

if (typeof cDocId=="undefined")
{
    LoadLastBlog();
    return true;
}

if (typeof cDocId=="string")
{
    if (cDocId=="last")
    {
        LoadLastBlog();
        return true;
    }       
}

if (DocIsLoaded(cDocId))
{
    showDebuginfo("CFHBlog.js--LoadDoc","从缓存当中加载文档！id="+cDocId)
    var doc = GetLoadedDoc(cDocId);
    LoadDocContent("Panel_Doc",doc);
    ShowUserFeedbackInfo();
    return;
}

showDebuginfo("CFHBlog.js--LoadDoc","开始Ajax加载文章！id="+cDocId)

 $.ajax({
   type: "POST",
   url: "/AjaxServer/server.ashx?service=article&method=get",
   data: "id="+cDocId,
   dataType: "json",
   success: function(data)
   {
      LoadDocObject(data);
   },
   error: function() { MsgBox("服务异常，无法取得文档信息！请您稍后再试。"); }  
 });

}

function LoadLastBlog()
{
    showDebuginfo("CFHBlog.js--LoadLastBlog", "加载最后一篇博文！")
    $.getJSON("/AjaxServer/server.ashx?service=article&method=getlast&AppEntryId=" + WebConfig.AppEntryId+"&rand="+Math.random(),
        function(data) {
            LoadDocObject(data);
        }
    );
}

/*
    处理服务器返回的文档信息（文档、JSONMsg对象等）
*/
function LoadDocObject(data)
{
    showDebuginfo("CFHBlog.js--LoadDoc","得到结果，正在分析");
    if (IsJSONMsg(data))
    {
        MsgBox(data.message);
        return;
    }
    if (!IsDocObject(data))
    {
        MsgBox("对象类型不是JSON文档，服务出错！");
        WebConfig.CurrentDoc.ResId  = "";
        return false;
    }
    
    AddBlogAccessLog();
    LoadDoc2WebConfig(data);
    LoadDocContent("Panel_Doc",data);
    
    ShowUserFeedbackInfo();
}


/*
    判断文档是否已经加载到 WebConfig 当中
*/
function DocIsLoaded(cDocId)
{
    if (typeof WebConfig.BlogDocs=="undefined")
    {
        showDebuginfo("CFHBlog.js--DocIsLoaded","WebConfig.BlogDocs 还没有定义！");
        return false;
    }
    if (typeof $(WebConfig.BlogDocs).data(cDocId)=="undefined")
    {
        showDebuginfo("CFHBlog.js--DocIsLoaded","文章"+cDocId+"没有被缓存！");
        return false;
    }
    else
        return true;
}

/*
    将 json 格式的文档加载到WebConfig当中
*/
function LoadDoc2WebConfig(jsonDoc)
{
    showDebuginfo("CFHBlog.js--LoadDoc2WebConfig","加载文章到缓存！");
    if (typeof WebConfig.BlogDocs=="undefined")
    {
        WebConfig.BlogDocs = {};
    }
    $(WebConfig.BlogDocs).data(jsonDoc.Id,jsonDoc);
}
/*
    加载已经缓存的文档
*/
function GetLoadedDoc(cDocId)
{
    showDebuginfo("CFHBlog.js--GetLoadedDoc","加载已经缓存的文档！");
    return $(WebConfig.BlogDocs).data(cDocId);
}
/*
    判断博客列表是否已经加载
    
    // 去掉的原因是觉得博客列表没有必要缓冲；缓冲可能会造成刷新不及时，刚刚发表的文章刷新也看不到等弊端
*/
/*
function BlogListIsLoaded()
{
    //return false;
    
    
    showDebuginfo("CFHBlog.js--BlogListIsLoaded","准备判断博客列表是否加载 ！")
    if (typeof WebConfig.BlogList=="object")
    {
        if (typeof WebConfig.BlogList.length!="number")
            return false;
            
        if (WebConfig.BlogList.length>0)
        {
            showDebuginfo("CFHBlog.js--BlogListIsLoaded","博客数量大于 0 ！")
            return true;
        }
    }
    
    showDebuginfo("CFHBlog.js--BlogListIsLoaded","博客数量小于 0 或者没有结果 ！")
    return false;
}
*/

function LoadDocList(cEntryId)
{
    $("#DocList").html(""); // 首先将当前的博客文章列表显示清空

    //if (!BlogListIsLoaded())  去掉了检查博客列表是否已经下载的功能
    showDebuginfo("CFHBlog.js--LoadDocList", "开始加载博客列表数据！Entry=" + cEntryId);
    // 去掉参数 &category=ed312299-a256-428a-9b4c-ac9e74c7f873
    var url = "/AjaxServer/server.ashx?service=article&method=getlist&appname=Blog&appentryid=" + cEntryId + "&rand=" + Math.random();

    $.getJSON(url, 
            function(data)
            {
                if (IsJSONMsg(data))
                {
                    MsgBox(data.message);
                    return false;
                }
                
                WebConfig.BlogList = data;
                FillDocList();      
            });
}

function FillDocList()
{
    if (WebConfig.BlogList.length<1)
	{
	    showDebuginfo("CFHBlog.js","博客列表数据项小于 1 ，列表无法显示！")
	    return false;
	}
	
	
	var docListHtml = '<div id="DocListTitleArea">';
	docListHtml += '<span id="DocListTitle">文章列表</span>';
	docListHtml += '<span id="DocListTable_ShowAllBtn" onclick="ShowDocListAll();">显示全部</span>';
	docListHtml += '</div>';
	
	// 表格正式开始
	docListHtml += '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="DocListTable" >';
	docListHtml += '<tr id="DocListTableHeaderRow">';
	docListHtml += '<td width="30"></td>';
	docListHtml += '<td><div style="text-align:left">标题</div></td>';
	docListHtml += '<td width="150">日期</td>';
	/*
	docListHtml += '<td width="60">评论</td>';
	docListHtml += '<td width="60">访问</td>';
	*/
	docListHtml += '</tr>';
	
	
	$.each(WebConfig.BlogList,function(i,jDoc) {
		docListHtml += '<tr class="DocListItemRow" doc_cate="'+jDoc.CategoryId+'" doc_date="'+ GetDateLocaleStandardString(jDoc.UpdateTime) +'">';
		docListHtml += '<td><div style="text-align:left">';
		docListHtml += '<img src="/Style/Default/App.gif" alt="';
		docListHtml += GetCateName(jDoc.CategoryId);
		docListHtml += '" onclick="ShowDocListByCateId(\'';
		docListHtml += jDoc.CategoryId;
		docListHtml += '\');" style="cursor:pointer;" /></div></td>';
		docListHtml += '<td><div class="doclist_title" id="';
		docListHtml += jDoc.Id;
		docListHtml += '">';
		docListHtml += jDoc.Title;
		docListHtml += '</div></td>';
		docListHtml += '<td>';
		docListHtml += GetDateTimeLocaleStandardString(jDoc.UpdateTime);
		docListHtml += '</td>';
		/*
		docListHtml += '<td>';
		docListHtml += '0';
		docListHtml += '</td>';
		docListHtml += '<td>';
		docListHtml += '0';
		docListHtml += '</td>';
		*/
		docListHtml += '</tr>';  
     });
     
	docListHtml += '</table>';
	
	$("#DocList").html(docListHtml);

	/*
	定义文档列表点击函数
	*/
	$(".doclist_title").click(
	function()
	{
		ShowDoc($(this).attr("id"));
	});
}

function ShowDocList()
{
    $("#Panel_DocList").show();
}

function HideDocList()
{
    $("#Panel_DocList").hide();
}

/*
加载指定日期的文档列表
*/
function LoadDocListByDate(cDate)
{
	$(".DocListItemRow").hide();
	$(".DocListItemRow[doc_date='"+cDate+"']").show();
	ShowDocList();
	$("#DocListTitle").text(cDate+"更新的所有文章");
}

/*
加载指定文档
*/
function ShowDoc(docId)
{
	LoadDoc(docId);
	HideDocList();
}

/*
    创建新文档
*/
function StartNewArticle()
{
    getGUIDFromServer(PrepareNewDoc,CannotCreateNewDoc);
}

function PrepareNewDoc(cDocId)
{
    if (IsNotEmptyString(cDocId)) {
        //alert("取得新的Blog ID:"+cDocId);
        ClearContent();
        SetDocId(cDocId);
        EditDoc();
    }
    else
    {
        MsgBox("没有取得有效的文档ID，服务不可用。请您稍后再试！");
    }
    
    return true;
}

function CannotCreateNewDoc()
{
    MsgBox("新建文档服务不可用：服务目前不可用，无法创建新文档！");
}

/*
    删除当前文档
*/
function DeleteDoc(cId)
{
    $.getJSON("/AjaxServer/server.ashx?service=article&method=delete",
        { Id:cId },
        function(data)
        {
            if (IsJSONMsg(data))
            {
                ShowMsg(data.message);
                return;
            }
        }
    );
}

/*
    删除当前打开的文档
*/
function DeleteCurrentDoc()
{
    var cId =$("#Id").val();
    if (typeof cId=="string")
    {
       DeleteDoc(cId);
       return;
    }
    alert("当前没有指定文档，没有删除任何资料！");
}

// 提交内容
function SaveDoc(doc)
{
    $.post("/AjaxServer/server.ashx?service=article&method=post",
		   doc,
		   function(jsonMsg) {
		       try {
		           var data = eval("(" + jsonMsg + ")");
		           if (IsJSONMsg(data)) {
		               ShowMsg(data.message);
		               if (data.status == "ok") {
		                   location.reload(true);
		                   /*
		                   showDebuginfo("CFHBlog.js SaveDoc", "博客发表成功！现在加载到内存当中");
		                   var editedDoc = GetDocFromEditor();
		                   LoadDoc2WebConfig(editedDoc); // 保存当前已经编辑的对象
		                   ViewDoc();
		                   LoadDocList(doc.Appentryid);
		                   return true;
		                   */
		               }
		           }
		       }
		       catch (oException) {
		           ShowMsg("服务返回异常错误！");
		       }
		       return false;
		   }
		   );
}

/*
    显示文档菜单
*/
function ShowArticleMenu(subMenuId)
{
	$(".ArticleMenu").hide();
	$("#"+subMenuId).show();
	$("#ArticleMenu").slideDown("slow"); 
}
/*
    隐藏文档菜单
*/
function HideArticleMenu()
{
	$("#ArticleMenu").slideUp("slow"); 
}
/*
    添加新分类
*/
function AddNewCategory()
{
    var cCateName = $("#NewCategoryName").val();
    if (!IsNotEmptyString(cCateName))
    {
        MsgBox("请先填写分类的名称！");
        return;
    }  

    // 检查本地分类缓存，重名则不允许添加
    if (Exists(cCateName))
    {
        MsgBox("分类名称已经存在！ ");
        return;
    }
    // 提交新分类
    $.getJSON("/AjaxServer/Server.ashx?service=appsetting&method=addcategory4blog&rand="+Math.random(),
        { EntryId:WebConfig.AppEntryId,NewCategoryName:cCateName },
        function(json)
        {
            if (json.type=="jsonmsg")
            {
                MsgBox(json.message);
            }
            else
            {
                WebConfig.CategoryList[WebConfig.CategoryList.length] = json;
                ShowBlogCategory(); 
            }
        }
        );   
}

function Exists(cCateName)
{
    for(var i=0; i<WebConfig.CategoryList.length; i++)
    {
        if (WebConfig.CategoryList[i].Name==cCateName)
            return true;
    }
}

/*
    显示帮助
*/
function ShowHelp()
{
    alert("显示博客帮助！");
}

// 重新显示博客的分类
function ShowBlogCategory()
{
    SetCategory(WebConfig);    
}

