﻿// JScript 文件
 $(document).ready(function(){
     $.each($('.sharehf'), function(i, entry1){ 
        $(this).bind("click", function(){
            GetReview($("#txtBrowserUserID").val(), $("#txtObjTypeId").val(), $(this).attr("name")); //绑定回复事件；
            $(this).after( $("#loading"));
        });
     });
     
     $.each($('.share_del'), function(i, entry1)
     {
        $(this).bind("click", function(){
            Delete($(this).attr("name"), $(this).attr("name"),0, $("#txtLoginUserId").val());//绑定回复事件；
            $(this).after( $("#loading"));
        });
     }); 
     
     $('#loading').ajaxError(function(){
        alert("提交数据出错，请稍候再试！");
     });
     
     $("#txtUrl").bind("focus",function(){
        if($("#txtUrl").val() == "http://"){
            $("#txtUrl").val("");
        }
     }).bind("blur", function(){
        if($("#txtUrl").val() == ""){
            $("#txtUrl").val("http://");
        }
     });
});            
           
function GetReview(userId,objTypeId, objId)
{
     $.ajax({
        data:"userid=" + userId + "&objtypeid=" + objTypeId + "&objId=" + objId, //参数
        dataType:"json",//返回的格式
        type:"POST",
        url:"/share/DataService/GetShareReview.ashx",//请求地址
        beforeSend :function(){
            $('#loading').show();
        },
        complete:function(){
            $('#loading').hide();
        },
        success:function(jsonData){
          var divHtml =""; 
          var pkId;
          var moveId=''; //二级评论列表
          var i=0;
          var encryptUserid = $.cookie("user_id");
          var loginUserid = $('#txtLoginUserId').val();
          var browserUserID = $('#txtBrowserUserID').val();
          $.each(jsonData, function(entryIndex, entry)
          {                    
             pkId = entry["ReviewId"];   //缩进格式处理
             if(moveId.indexOf(pkId)<0)
             {
                 if(i>0) divHtml+='</div>';
                 divHtml +='<div  id=\"div'+ entry["ReviewId"]+ '\" class=\"icon21\">';
                 divHtml +='<a id="'+ entry["ReviewId"] +'" href=\"/'+ entry["UserId"] +'\">'+ entry["UserName"] +'</a> ';
                 divHtml += entry["Content"] ;
                 divHtml += '<span class=\"STYLE4\">' + entry["CDate"] + '</span>';
                 if(encryptUserid != null && encryptUserid.length >0) //登录
                 {
                     if(entry["UserId"] != loginUserid){//回复Id：aReply_回复对象Id_父Id_当前回复Id
                        divHtml += '<a id=\"aReply_'+ objId +'_' +entry["ReviewId"]+'_' +entry["ReviewId"]+'\" name=\"1\" class="STYLE4 icon22" style=\"color: rgb(153, 153, 153);\"  href=\"javascript:void(0);\">回复</a>';
                        if(loginUserid == browserUserID){divHtml += '<span class="migiblog_bg"><a  id="btnDel_' +entry["ReviewId"] + "_" + loginUserid + '" name="1" " href="javascript:void(0);">&nbsp;&nbsp;</a></span>';}
                     }else{//删除Id：btnDel_当前回复Id_UserId
                        divHtml += '<span class="migiblog_bg"><a  id="btnDel_' +entry["ReviewId"] + "_" + entry["UserId"] + '" name="1" " href="javascript:void(0);">&nbsp;&nbsp;</a></span>';
                     } 
                 }
                 i=i+1;
             }
             var secondHtml = ""; //二级回复代码
             $.each(jsonData, function(entryIndex, entry)
             { 
                if(pkId == entry["ParentId"]){
                     secondHtml +='<div  id=\"div'+ entry["ReviewId"] + '\" class=\"icon21\">';
                     secondHtml +='<a class=\"name\" id="'+ entry["ReviewId"] +'" href=\"/'+ entry["UserId"] +'\">'+ entry["UserName"] +'</a> ';
                     secondHtml += entry["Content"] ;
                     secondHtml += '<span class=\"STYLE4\">' + entry["CDate"] + '</span>';                   
                     if(encryptUserid != null && encryptUserid.length >0) //登录
                     {
                         if(entry["UserId"] != loginUserid){
                            secondHtml += '<a id=\"aReply_'+ objId +'_' + entry["ParentId"] +'_' +entry["ReviewId"] +'\" name=\"2\" class="STYLE4 icon22" style=\"color: rgb(153, 153, 153);\"  href=\"javascript:void(0);\">回复</a>';
                            if(loginUserid == browserUserID){secondHtml += '<span class="migiblog_bg"><a id="btnDel_' +entry["ReviewId"]+ "_" + loginUserid + '" name="2" " href="javascript:void(0);">&nbsp;&nbsp;</a></span>';}
                         }else{
                            secondHtml += '<span class="migiblog_bg"><a id="btnDel_' +entry["ReviewId"]+ "_" + entry["UserId"] + '" name="2" " href="javascript:void(0);">&nbsp;&nbsp;</a></span>';
                         }
                     }
                     secondHtml +='</div>';
                     moveId += entry["ReviewId"] +',';
               }
             });
              if(secondHtml != ""){
                divHtml += '<div id="second'+ pkId  +'">'+ secondHtml +'</div>' ;
              }
           });  
            if(i>0) divHtml+='</div>';
         
            divHtml += '<div id="pReply'+ objId +'" class=\"icon21\">';
            divHtml += '<input type=\"text\" maxlength="140" id=\"txtReplyContent'+ objId +'\" style=\"width: 300px;\"/>';
            divHtml += '<input type=\"button\" id=\"btnReply'+ objId +'\" value=\"回 复\" class=\"button3\" name=\"Submit222\"/>';
            divHtml += '</div>';
          
            
             var rRoot = '<div style="display:none;" id="rRootId'+ objId +'" class=\"icon21\">';
               rRoot += '<a id="aRootId'+ objId +'" href=\"javascript:void(0);">回复主题</a>';
               rRoot += '</div>';
            divHtml += rRoot;
            //alert(divHtml);   
             
            
           $("#aReply_" + objId).text("收起回复");
           $("#aReply_" + objId).unbind();
           $("#aReply_" + objId).bind('click', function()
           {
              if($("#aReply_" + objId).text().indexOf("收起")<0){
                 $("#aReply_" + objId).text("收起回复");                 
                 $("#divReplyList" + objId).fadeIn("slow");
              }else{
                 $("#aReply_" + objId).text("回复(" + $("#labnum_" + objId).text() + ")");                
                 $("#divReplyList" + objId).fadeOut("slow");
              }
              return false;
           }); 
           
           $("#divReplyList" + objId).html(divHtml);
           $('#btnReply' + objId).bind('click', function(){SetComment(objId, 0);$(this).after( $("#loading"));}); //第一次点回复 
           
           //"回复主题"绑定事件
            $('#rRootId' + objId).bind('click', function(){
                $('#rRootId' + objId).hide();
                $('#pReply'+ objId).attr("style","");
                $("#divReplyList" + objId).append($('#pReply'+ objId)); //移动回复框   
                $('#btnReply' + objId).unbind();
                $('#btnReply' + objId).bind('click', function(){
                   SetComment(objId,0, null);
                   $(this).after( $("#loading"));
                });
            }); 
           
           
           //给"回复"绑定事件 
           $.each($('#divReplyList'+objId+' a'), function(i, entry1)
           {
                var aId = $(this).attr("id"); //回复id
                var arrData = aId.split('_'); //根据a标签id 获取回复objId和ParentId 
              
                if(!(aId.indexOf('aReply_') <0))
                {
                    $(this).bind('click', function(){ //给回复绑定事件
                        $(this).parent().after($('#pReply'+ objId)); //移动回复框
                         var level = $(this).attr("name");
                         if(level == 1){
                            $('#pReply'+ objId).attr("style", "margin-left: 15px;");
                         }else{
                            $('#pReply'+ objId).removeAttr("style");
                         }
                        
                        $('#btnReply' + objId).unbind();
                        $('#btnReply' + objId).bind('click', function(){
                           SetComment(arrData[1],arrData[2], level);
                           $(this).after( $("#loading"));
                        });
                        
                        //回复主题
                        $("#divReplyList" + objId).append($('#rRootId' + objId));
                        $('#rRootId' + objId).show();
                    });
                }
                //给"删除"绑定事件                             
                 if(!(aId.indexOf('btnDel_') <0)){
                      $(this).bind('click', function(){
                           Delete(arrData[1], objId, $(this).attr("name"), arrData[2]);
                          $(this).append( $("#loading"));
                      });
                 }
           });              
        }
    })
}
            
function SetComment(objId, parentId, level)
{
    if($.cookie("user_id") == null || $.cookie("user_id").length==0){login(); return;}
    
    if($("#txtReplyContent"+ objId).val().replace(/\s/g, "").length ==0){
        alert("请输入回复内容！");
        return;
    }    
    var _browserUserid = $("#txtBrowserUserID").val(); //浏览userid
    var _objtypeid = $("#txtObjTypeId").val();         //评论类型
    var _title = $("#aTitle" + objId).attr("title");  //标题
    var _objurl = $("#aUrl" + objId).attr("title");    //url
    //alert("bjId:" + objId + " parentId:" + parentId + " level:" +level);
    //alert(_browserUserid + _objtypeid + _title + _objurl);
    $.ajax({
        data:"objid=" + objId +"&objtypeid=" + _objtypeid + "&flag=submit&title="+ escape(_title) +"&objurl=" + escape(_objurl) +"&content=" + escape($("#txtReplyContent"+ objId).val()) + "&objuserid=" + _browserUserid + "&parentid=" + parentId, //参数
        dataType:"json",//返回的格式
        type:"POST",
        url:"/share/DataService/SubmitShareReview.ashx",//请求地址
        beforeSend :function(){
            $('#btnReply' + objId).attr("value","请稍后");
            $('#btnReply' + objId).attr("disabled","true");
            $('#loading').show();
        },
        complete:function(){
            $('#btnReply' + objId).attr("value","回 复");
            $('#btnReply' + objId).removeAttr("disabled");
            $('#loading').hide();
        },
        success:function(jsonData){ 
           $.each(jsonData, function(entryIndex, entry)
              { 
                if(entry["IsSuccess"] == "false"){
                    alert(entry["Msg"]);
                    return;
                }
                $("#txtReplyContent"+objId).val(''); //清空发表框
                
                //回复总数加 1                 
               $("#labnum_" + objId).text(parseInt($("#labnum_" + objId).text()) + 1);
               
                var divHtml ='<div id=\"div'+ entry["ReviewId"] +'\" class=\"icon21\">';
                 //回复链接id
                 var $PReply = 'aReply_' + objId + '_' + entry["ReviewId"]+ '_' + entry["ReviewId"];
                 var newParentId = entry["ReviewId"];
                
                if(level == 1 || level == 2){
                    $PReply = 'aReply_' + objId + '_' + entry["ParentId"]+ '_' + entry["ReviewId"];
                    newParentId = entry["ParentId"];
                    divHtml ='<div  id=\"div'+ entry["ReviewId"]  + '\" class=\"icon21\">';
                 }
                
                 divHtml +='<a class="name" href=\"/'+ entry["UserId"] +'\">'+ entry["UserName"] +'</a> ';
                 divHtml += entry["Content"] ;
                 divHtml += '<span class=\"STYLE4\">' + entry["CDate"] + '</span>';
                 divHtml += '<span class="migiblog_bg"><a id="btnDel_' +entry["ReviewId"] + '_' + entry["UserId"] + '"  name="'+ ((!level)?"1": level) +'" href="javascript:void(0);">&nbsp;&nbsp;</a></span>';                           
                 divHtml +='</div>';
               //alert(divHtml);
                 if(level)
                 {
                     if($("#second"+ parentId).length==0){
                        $("#div"+parentId).append($("<span id='second" + parentId + "'></span>"));
                        $("#second" +parentId ).append($("#pReply" + objId));
                        $("#pReply" + objId).before(divHtml);
                     }else{
                        $("#second" +parentId ).append($("#pReply" + objId));
                        //alert(parentId+":" + $("#second" +parentId ).text());
                        $("#pReply" + objId).before(divHtml);
                        
                     }
                      $('#pReply'+ objId).removeAttr("style");
                 }else{
                     $("#pReply" + objId).before(divHtml); 
                 }
                
                 if(!level){level = 1;}
                 $('#'+ $PReply).bind("click", function(){
                        $(this).parent().after($('#pReply'+ objId)); //移动回复框                         
                         $('#pReply'+ objId).removeAttr("style");
                         
                        $('#btnReply' + objId).unbind();
                        $('#btnReply' + objId).bind('click', function()  //回复绑定事件
                        {
                            SetComment(objId, newParentId, level);
                            $(this).after( $("#loading"));
                        });
                        
                         //回复主题
                        $("#divReplyList" + objId).append($('#rRootId' + objId));
                        $('#rRootId' + objId).show();
                  });
                  
                  //给删除绑定事件
               
                  $('#btnDel_' +entry["ReviewId"] + '_' +  entry["UserId"]).bind('click', function(){
                       // alert("dddddd:" + entry["MiniBlogId"] + " " +objId+ "" + level);
                       Delete(entry["ReviewId"], objId, level, entry["UserId"]);
                       $(this).append( $("#loading"));
                  });
               
              });
        }
    })
}
            
function Delete(iReviewid, iObjId, level, iUserid)
{//(评论id，评论对象id， 级别， 评论所属作者id)
    //alert("iReviewid:" + iReviewid + "iObjId:" + iObjId+ "_level:" + level+ " reviewuserid:" + iUserid);
    var msg = "确定要删除该回复吗？"
    if(level==0){
        msg = "确定要删除该分享吗？";
    }
    if(!confirm(msg)){
        return false;
    }    
    var flag = "delcomment";
    if(level== 0) flag = "delroot";
     $.ajax({
        data:"reviewid=" + iReviewid + "&flag=" + flag + "&objid=" + iObjId + "&reviewuserid=" + iUserid , //参数
        dataType:"json",//返回的格式
        type:"POST",
        url:"/share/DataService/SubmitShareReview.ashx",//请求地址
        beforeSend :function(){
            $('#loading').show();
        },
        complete:function(){
            $('#loading').hide();
        },
        success:function(jsonData)
        {
            $.each(jsonData, function(entryIndex, entry)
            {if(entry["IsSuccess"] == "false"){
               alert(entry["Msg"]);
                   return;
                }
            });
            
            $("#labnum_" + iObjId).text(parseInt($("#labnum_" + iObjId).text()) - 1);
            
            //清楚媒体对象
            if($("#labVedio" + iObjId) != null && $("#labVedio" + iObjId).length >0 ){               
                $("#labVedio" + iObjId).html("");
            }           
            if($("#labMusic" + iObjId) != null && $("#labMusic" + iObjId).length >0 ){               
                $("#labMusic" + iObjId).html("");
            }
            
            $("#div" + iReviewid).fadeOut("slow");         
            
            if(level== 0)
            {
                $("#li_" + iReviewid).fadeOut("slow");
            }else{
                if($("#second" + iReviewid).length >0){
                    //alert($("#second" + sMiniBlogId + " > div").length);
                    //减去二级回复条数
                    $("#labnum_" + iObjId).text(parseInt($("#labnum_" + iObjId).text()) - $("#second" + iReviewid + " > div").length);
                    $("#second" + iReviewid).fadeOut("slow");
                }
            }
           
        }
     });
} 

function UnfoldComment(userId,objTypeId, objId){//aReply_591
    if($("#li_" + objId).length == 0){
        alert("你查看的分享不存在！");
    }else{
        GetReview(userId,objTypeId, objId)
    }
}

function playVedio(src, pkid){
    var _playVedio ='<div style="position:relative"><label id="labVedio' + pkid +'"><object height="396"  align="middle" width="480" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">'
        + '<param value="' + src + '" name="movie"/>'
        + '<param value="true" name="allowFullScreen"/><param value="always" name="allowScriptAccess"/>'
        + '<param value="high" name="quality"/><param value="transparent" name="wmode"/>'
        + '<param   name="PLAY"   value="true">'
        + '<embed height="396" width="480" src="' + src  +'"'
        +' type="application/x-shockwave-flash" allowfullscreen="true" wmode="transparent" allowscriptaccess="always"/></object></label>'
        + '<img alt="缩小" id="hideView'+ pkid +'" src="http://si.yaolanimage.cn/images/share_minimize.png" class="share_hide" onclick="javascript:hidePlay('+ pkid +')"></div>'
        $("#Vedio" + pkid).html(_playVedio); 
        $("#imgVedio" + pkid).hide();
        $("#playvideo" + pkid).hide();
}
function hidePlay(pkid){
    $("#imgVedio" + pkid).show();
    $("#playvideo" + pkid).show();
    //$("#Vedio" + pkid).html("");
    $("#hideView" + pkid).hide();
    $("#labVedio" + pkid).html("");
}

function playMusic(src, pkid){
    var _playVedio ='<label id="labMusic' + pkid +'"><object height="68" border="0" align="baseline" width="355" id="wmaPlayer"'
        + ' classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715" '
        + 'standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject">'
        + '<param name="invokeURLs" value="0"/><param name="FileName" value="'
        + src
        + '"/><param name="ShowControls" value="1"/>'
        + '<param name="ShowPositionControls" value="0"/>'
        + '<param name="ShowAudioControls" value="1"/>'
        + '<param name="ShowTracker" value="1"/>'
        + '<param name="ShowDisplay" value="0"/><param name="ShowStatusBar" value="1"/>'
        + '<param name="AutoSize" value="0"/><param name="ShowGotoBar" value="0"/>'
        + '<param name="ShowCaptioning" value="0"/><param name="AutoStart" value="1"/>'
        + '<param name="PlayCount" value="0"/><param name="AnimationAtStart" value="0"/>'
        + '<param name="TransparentAtStart" value="0"/><param name="AllowScan" value="0"/>'
        + '<param name="EnableContextMenu" value="1"/><param name="ClickToPlay" value="0"/>'
        + '<param name="DefaultFrame" value="datawindow"/>'
        + '<embed height="68" border="0" align="baseline" width="355" '
        + ' src="'+ src +'" type="application/x-mplayer2"'
        + ' pluginspage="http://www.microsoft.com/isapi/redir.dll?prd=windows&amp;sbp=mediaplayer&amp;ar=media&amp;sba=plugin&amp;"'
        + ' name="MediaPlayer" showcontrols="1" '
        + ' showpositioncontrols="0" showaudiocontrols="1" showtracker="1" showdisplay="0" showstatusbar="1" '
        + ' autosize="0" showgotobar="0" showcaptioning="0" autostart="1" autorewind="0" animationatstart="0" '
        + ' transparentatstart="0" allowscan="1" enablecontextmenu="1" clicktoplay="0" defaultframe="datawindow" '
        + ' invokeurls="0"/>'
        + ' </object></label>'
        //alert("#imgMusic" + pkid);
        $("#playMusic" + pkid).html(_playVedio);
        $("#imgMusic" + pkid).hide();
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function checkKey(e, bindButton)
{			
	var key = window.event ? e.keyCode : e.which;
	if (key.toString() == "13") {
		if (window.event) {
			e.returnValue = false;
			e.cancelBubble = true;
		}
		else {
			e.stopPropagation();
			e.preventDefault();
		}	
	    bindButton.click();	   	 
	    return false;
    }
}
