﻿// JScript 文件
 $(document).ready(function(){
     $.each($('.areply'), function(i, entry1){ 
        $(this).bind("click", function(){
            GetComment($(this).attr("bid"), $(this).attr("uid")); //绑定回复事件；            
            $(this).after( $("#loading"));
        });
     });
     
     
      $.each($('.aforword'), function(i, entry1){ 
        $(this).bind("click", function(){
            if($.cookie("user_id") == null ||$.cookie("user_id").length==0){Login(); return;}
            var url = '/miniblog/uc/ForwardBlog.aspx?userid='+ $("#txtLoginUserId").val() +'&miniblogid='+$(this).attr("name");
            if($("#txtMiniBloTagId").length >0) url+="&tagid=" + $("#txtMiniBloTagId").val()
            widLogin(url,'558','480');
            
            $(this).after( $("#loading"));
        });
     });
     
     
     $.each($('.adel'), function(i, entry1)
     {
        $(this).bind("click", function(){
            Delete($(this).attr("name"), $(this).attr("name"),1, $("#txtLoginUserId").val());//绑定回复事件；
            $(this).after( $("#loading"));
        });
     }); 
     
     var maxLength = 140;
     $("#emMsg").html("还能输入<span class=\"n_f18px\">" + maxLength + "</span>个字");
     $("#Sendblog1_txtContent").bind('keyup', function(){
        checkLen("Sendblog1_txtContent", maxLength);
     });
     $("#Sendblog1_txtContent").bind('keydown', function(e){        
        var e=e||event;
        var currKey=e.keyCode||e.which||e.charCode;       
        if(($(this).val().length >maxLength) && !(currKey ==8 ||currKey ==37 ||currKey ==38 ||currKey ==39 ||currKey ==40||currKey ==46)){
            return false;
        }
     });
     $('#loading').ajaxError(function(){
        alert("提交数据出错，请稍候再试！");
     });     
});           
      
function GetComment(rootId,uid)
{
     $.ajax({
        data:"rootId=" + rootId, //参数
        dataType:"json",//返回的格式
        type:"POST",
        url:"/miniblog/DataService/GetCommentList.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["MiniBlogId"];   //缩进格式处理
             if(moveId.indexOf(pkId)<0)
             {
                 if(i>0) divHtml+='</div>';
                 divHtml +='<div  id=\"p'+ entry["MiniBlogId"]+ '\" class=\"icon21\">';
                 divHtml +='<a class="name" id="'+ entry["MiniBlogId"] +'" 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){
                        divHtml += '<a id=\"aReply_'+ rootId +'_' +entry["MiniBlogId"]+'_' +entry["MiniBlogId"]+'\" name=\"1\" class="STYLE4 icon22" style=\"color: rgb(153, 153, 153);\"  href=\"javascript:void(0);\">回复</a>';
                        if(loginUserId == uid){divHtml += '<span class="migiblog_bg"><a  id="btnDel_' +entry["MiniBlogId"] + "_" + loginUserId + '" name="1" " href="javascript:void(0);">&nbsp;&nbsp;</a></span>';}
                     }else{
                        divHtml += '<span class="migiblog_bg"><a  id="btnDel_' +entry["MiniBlogId"] + "_" + 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=\"p'+ entry["MiniBlogId"] + '\" class=\"icon21\">';
                     secondHtml +='<a class=\"name\" id="'+ entry["MiniBlogId"] +'" href=\"/'+ entry["UserId"] +'\">'+ entry["UserName"] +'</a>';
                     secondHtml += entry["Content"] ;
                     secondHtml += '<span class=\"STYLE4\">' + entry["CDate"] + '</span>';
                     //alert(entry["UserName"] + "_txt:UserName" + $('#txtLoginUserName').val());
                     if(encryptUserid != null && encryptUserid.length >0) //登录
                     {
                         if(entry["UserId"] != loginUserId){
                            secondHtml += '<a id=\"aReply_'+ rootId +'_' + entry["ParentId"] +'_' +entry["MiniBlogId"] +'\" name=\"2\" class="STYLE4 icon22" style=\"color: rgb(153, 153, 153);\"  href=\"javascript:void(0);\">回复</a>';
                            if(loginUserId == uid){secondHtml += '<span class="migiblog_bg"><a id="btnDel_' +entry["MiniBlogId"]+ "_" + loginUserId + '" name="2" " href="javascript:void(0);">&nbsp;&nbsp;</a></span>';}
                         }else{
                            secondHtml += '<span class="migiblog_bg"><a id="btnDel_' +entry["MiniBlogId"]+ "_" + entry["UserId"] + '" name="2" " href="javascript:void(0);">&nbsp;&nbsp;</a></span>';
                         }
                     }
                     secondHtml +='</div>';
                     moveId += entry["MiniBlogId"] +',';
               }
             });
              if(secondHtml != ""){
                divHtml += '<div id="second'+ pkId  +'">'+ secondHtml +'</div>' ;
              }
              //divHtml += '';
             
           });  
            if(i>0) divHtml+='</div>';
           // if(loginUserName.length >0) //登录
           // {
                divHtml += '<div id="pReply'+ rootId +'" class=\"icon21\">';
                divHtml += ' <div class=\"quote_a\"></div>';
                divHtml += '<input type=\"text\" maxlength="140" id=\"txtReplyContent'+ rootId +'\" style=\"width: 300px;\"/>';
                divHtml += '<input type=\"button\" id=\"btnReply'+ rootId +'\" value=\"回 复\" class=\"button3\" name=\"Submit222\"/><br/><input class=\"syc_miniblog\"  id=\"chkReply'+ rootId +'\" type="checkbox"/><label class=\"syc_miniblog\" for=\"chkReply'+ rootId +'\">同时发一条微博</label>';
                divHtml += '</div>';
           // }
            
             var rRoot = '<div style="display:none;" id="rRootId'+ rootId +'" class=\"icon21\">';
               rRoot += '<a id="aRootId'+ rootId +'" href=\"javascript:void(0);">回复主题</a>';
               rRoot += '</div>';
            divHtml += rRoot;         
            
           $("#aReply_" + rootId).text("收起回复");
           $("#divReplyList" + rootId).show();           
           $("#aReply_" + rootId).unbind();
           $("#aReply_" + rootId).bind('click', function()
           {
              if ($("#aReply_" + rootId).text().indexOf("收起")<0){
                 $("#aReply_" + rootId).text("收起回复");
                 //$("#divReplyList" + rootId).show("slow");
                 $("#divReplyList" + rootId).fadeIn("slow");
              }else{
                 $("#aReply_" + rootId).text("回复(" + $("#labnum_" + rootId).text() + ")");
                 //$("#divReplyList" + rootId).hide("slow");
                 $("#divReplyList" + rootId).fadeOut("slow");
              }
              return false;
           }); 
          //alert(divHtml); 
            //$("#Sendblog1_txtContent").text(divHtml);
           $("#divReplyList" + rootId).html(divHtml);
           $("#txtReplyContent" + rootId).focus();
           $('#btnReply' + rootId).bind('click', function(){SetComment(rootId, rootId);$(this).after( $("#loading"));}); //第一次点回复 
           
           //"回复主题"绑定事件
            $('#rRootId' + rootId).bind('click', function(){
                $('#rRootId' + rootId).hide();
                $('#pReply'+ rootId).attr("style","");
                $("#divReplyList" + rootId).append($('#pReply'+ rootId)); //移动回复框   
                $('#btnReply' + rootId).unbind();
                $('#btnReply' + rootId).bind('click', function(){
                   SetComment(rootId,rootId, null);
                   $(this).after( $("#loading"));
                });
            }); 
           
           var cururl =top.location.href;
           //给"回复"绑定事件 
           $.each($('#divReplyList'+rootId+' a'), function(i, entry1)
           {
                var aId = $(this).attr("id"); //回复id
                var arrData = aId.split('_'); //根据a标签id 获取回复rootId和ParentId 
              
                if(!(aId.indexOf('aReply_') <0))
                {
                    $(this).bind('click', function(){ //给回复绑定事件
                        $(this).parent().after($('#pReply'+ rootId)); //移动回复框
                         var level = $(this).attr("name");
                         if(level == 1){
                            if(cururl.indexOf("space.yaolan.com/miniblog")>0){ //聚合页缩进65
                                $('#pReply'+ rootId).attr("style", "margin-left: 65px;");
                            }else{
                                $('#pReply'+ rootId).attr("style", "margin-left: 30px;");
                            }
                         }else{
                            $('#pReply'+ rootId).removeAttr("style");
                         }
                        
                        $('#btnReply' + rootId).unbind();
                        $('#btnReply' + rootId).bind('click', function(){
                           SetComment(arrData[1],arrData[2], level);
                           $(this).after( $("#loading"));
                        });
                        
                        //回复主题
                        $("#divReplyList" + rootId).append($('#rRootId' + rootId));
                        $('#rRootId' + rootId).show();
                    });
                }
                //给"删除"绑定事件                             
                 if(!(aId.indexOf('btnDel_') <0)){
                      $(this).bind('click', function(){
                        //alert("加载绑定:" + arrData[1] + "," + rootId + ","+ $(this).attr("name")+ ","+  arrData[2]);
                           Delete(arrData[1], rootId, $(this).attr("name"), arrData[2]);
                          $(this).append( $("#loading"));
                          // $(this).replaceWith( $("#loading"));
                      });
                 }
           });              
        }
    })
}
       
function SetComment(rootId, parentId, level)
{             
    //alert($("#txtReplyContent"+ rootId).val().replace(/\s/g, "").length);
    
    if($.cookie("user_id") == null ||$.cookie("user_id").length==0){Login(); return;}
    
    if($("#txtReplyContent"+ rootId).val().replace(/\s/g, "").length ==0){
        alert("请输入回复内容！");
        return;
    }
    //alert("rootId:" + rootId + "parentId:" + parentId + "level:" + level);
    //alert( $("#txtReplyContent"+ rootId));               
    $.ajax({
        data:"rootid=" + rootId +"&parentid=" + parentId + "&flag=submit&content=" + escape($("#txtReplyContent"+ rootId).val()) + "&userid=" + $("#txtBrowserUserID").val() + "&synblog=" + $("#chkReply"+ rootId).attr("checked"), //参数
        dataType:"json",//返回的格式
        type:"POST",
        url:"/miniblog/DataService/SubmitComment.ashx",//请求地址
        beforeSend :function(){
            $('#btnReply' + rootId).attr("value","请稍后");
            $('#btnReply' + rootId).attr("disabled","true");
            $('#loading').show();
        },
        complete:function(){
            $('#btnReply' + rootId).attr("value","回 复");
            $('#btnReply' + rootId).removeAttr("disabled");
            $('#loading').hide();
        },
        success:function(jsonData){ 
           $.each(jsonData, function(entryIndex, entry)
              { 
                if(entry["IsSuccess"] == "false"){
                    alert(entry["Msg"]);
                    return;
                }
                $("#txtReplyContent"+rootId).val(''); //清空发表框
                
                //回复总数加 1 
                
               $("#labnum_" + rootId).text(parseInt($("#labnum_" + rootId).text()) + 1);
               
                var divHtml ='<div id=\"p'+ entry["MiniBlogId"] +'\" class=\"icon21\">';
                 //回复链接id
                 var $PReply = 'aReply_' + rootId + '_' + entry["MiniBlogId"]+ '_' + entry["MiniBlogId"];
                 var newParentId = entry["MiniBlogId"];
                
                if(level == 1 || level == 2){
                    $PReply = 'aReply_' + rootId + '_' + entry["ParentId"]+ '_' + entry["MiniBlogId"];
                    newParentId = entry["ParentId"];
                    divHtml ='<div  id=\"p'+ entry["MiniBlogId"]  + '\" 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["MiniBlogId"] + '_' + entry["UserId"] + '"  name="'+ ((!level)?"1": level) +'" href="javascript:void(0);">&nbsp;&nbsp;</a></span>';                           
                 divHtml +='</div>';
               //alert(divHtml);
                 if(level)
                 {
                   
                    //alert("second:" + $("#second"+ parentId).length);
                     if($("#second"+ parentId).length==0){
                        $("#p"+parentId).append($("<span id='second" + parentId + "'></span>"));
                        $("#second" +parentId ).append($("#pReply" + rootId));
                        $("#pReply" + rootId).before(divHtml);
                     }else{
                        $("#second" +parentId ).append($("#pReply" + rootId));
                        //alert(parentId+":" + $("#second" +parentId ).text());
                        $("#pReply" + rootId).before(divHtml);
                        
                     }
                      $('#pReply'+ rootId).removeAttr("style");
                 }else{
                     $("#pReply" + rootId).before(divHtml); 
                 }
                 //alert("level;" + level);
                 if(!level){level = 1;}
                 $('#'+ $PReply).bind("click", function(){
                        $(this).parent().after($('#pReply'+ rootId)); //移动回复框 
                         //$('#pReply'+ rootId).attr("style", "margin-left: 30px;");
                         $('#pReply'+ rootId).removeAttr("style");
                         
                        $('#btnReply' + rootId).unbind();
                        $('#btnReply' + rootId).bind('click', function()  //回复绑定事件
                        {
                            SetComment(rootId, newParentId, level);
                            $(this).after( $("#loading"));
                        });
                        
                         //回复主题
                        $("#divReplyList" + rootId).append($('#rRootId' + rootId));
                        $('#rRootId' + rootId).show();
                  });
                  
                  //给删除绑定事件
               
                  $('#btnDel_' +entry["MiniBlogId"] + '_' +  entry["UserId"]).bind('click', function(){
                       // alert("dddddd:" + entry["MiniBlogId"] + " " +rootId+ "" + level);
                       Delete(entry["MiniBlogId"], rootId, level, entry["UserId"]);
                       $(this).append( $("#loading"));
                  });
               
              });
        }
    })
}
            
function Delete(sMiniBlogId, sRootId, level, userid)
{ //alert($("#second" + sMiniBlogId + " > div").length);
   //alert("sMiniBlogId:" + sMiniBlogId + "_sRootId:" + sRootId+ "_level:" + level+ "_userid:" + userid);
    var msg = "确定要删除该回复吗？"
    if(sMiniBlogId==sRootId){
        msg = "确定要删除该成长微博吗？";
    }
    if(!confirm(msg)){
        return false;
    }
    
    var flag = "delcomment";
    if(sMiniBlogId == sRootId) flag = "delroot";
     $.ajax({
        data:"miniblogid=" + sMiniBlogId + "&flag=" + flag + "&rootid=" + sRootId + "&userid=" + userid + "&BrowserUserID=" + $("#txtBrowserUserID").val(), //参数
        dataType:"json",//返回的格式
        type:"POST",
        url:"/miniblog/DataService/SubmitComment.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_" + sRootId).text(parseInt($("#labnum_" + sRootId).text()) - 1);
            $("#p" + sMiniBlogId).fadeOut("slow");
            if(sMiniBlogId == sRootId)
            {
                $("#div_" + sMiniBlogId).fadeOut("slow");
            }else{
                if($("#second" + sMiniBlogId).length >0){
                    //alert($("#second" + sMiniBlogId + " > div").length);
                    //减去二级回复条数
                    $("#labnum_" + sRootId).text(parseInt($("#labnum_" + sRootId).text()) - $("#second" + sMiniBlogId + " > div").length);
                    $("#second" + sMiniBlogId).fadeOut("slow");
                }
            }
           
        }
     });
} 
            
//文本框字数检查          
function checkLen(inputTxt , maxLen) 
{
    var maxLen = maxLen;
    var obj=$("#" + inputTxt) ;
    var textValue = obj.val();
    //var len=textValue.replace(/[^\x00-\xff]/g,'oo').length;
    //var len=textValue.replace(/\s/g, "").length;
    var len=textValue.length;
    var llen=maxLen-len; 
    if(len< maxLen){
        $("#emMsg").html("还能输入<span class=\"n_f18px\">" + llen + "</span>个字");
        $("#emMsg").removeClass("warning_tips");
        //$("#emMsg").addClass("pub_tips");
    }else if(len== maxLen){
        $("#emMsg").html("注意：字数已经达到上限");
       // $("#emMsg").removeClass("pub_tips");
        $("#emMsg").addClass("warning_tips");
    }else{
        $("#emMsg").html("已超过 " + Math.abs(llen) + " 个字,超过字符不会被保存！");
       // $("#emMsg").removeClass("pub_tips");
        $("#emMsg").addClass("warning_tips");
    }   
} 
	        
 function IsOk(obj)
{ 
    if($.cookie("user_id") == null ||$.cookie("user_id").length==0){Login(); return;}
    if($("#Sendblog1_txtContent").val().replace(/\s/g, "").length == 0)
    {
        if($("#msgcheck").length == 0){
            //$("#Sendblog1_txtContent").parent().prepend($("<p id='msgcheck' class='chkminiblognull'>请输入成长微博内容</p>"));
            alert("请输入成长微博内容!");
            $("#Sendblog1_txtContent").focus();
        }
        return false;
    }else{
        //$("#msgcheck").hide();
    }
    $("#Sendblog1_btnSend").attr("disabled","true");
    return true;
}            
            
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 CloseAlert(){
    $.cookie("miniblogalert","close", { expires: 30 });
    $("#Sendblog1_areaAlert").hide();
}
function UnfoldComment(rootId,uid){//aReply_591
    if($("#aReply_" + rootId).length == 0){
        alert("你回复的成长微博已删除或不在第一页！");
    }else{
        GetComment(rootId,uid);
    }
}
function SetTopic() {
    defValue = "#请在这里输入自定义话题#"
    str= "请在这里输入自定义话题"
    var input = document.getElementById('Sendblog1_txtContent'); 
    var insertText = App.TextareaUtils.getSelectedText(input);
    var isSelectText = (insertText == "" || insertText == str);
    if (isSelectText) {
        insertText = str
    } else {
        defValue = "#" + insertText + "#"
    }
    
    if (input.value.indexOf(defValue) < 0) 
    {
        if (input.value != "") //插入光标处内容
        {
            if(document.selection) {   
                input.focus();   
                var sel=document.selection.createRange();   
                document.selection.empty();   
                sel.text = defValue;        
            } else {   
                var prefix, main, suffix;
                prefix = input.value.substring(0, input.selectionStart);
                main = input.value.substring(input.selectionStart, input.selectionEnd);
                suffix = input.value.substring(input.selectionEnd);   
                input.value = prefix + defValue + suffix; 
                
            }   

        } else {
            App.TextareaUtils.unCoverInsertText(input, defValue)
        }
    }
    var cstar = input.value.split(defValue)[0].length;
    cstar = cstar == "" ? 1 : cstar + 1;
    if (isSelectText) {
        App.TextareaUtils.setCursor(input, cstar, insertText.length)
    } else {
        cstar += defValue.length - 1;
        App.TextareaUtils.setCursor(input, cstar)
    }
} 

var App = {}
App.TextareaUtils = (function() {
    var it = {},
    ds = document.selection;
    it.selectionStart = function(oElement) {
        if (!ds) {
            return oElement.selectionStart
        }
        var er = ds.createRange(),
        value,
        len,
        s = 0;
        var er1 = document.body.createTextRange();
        er1.moveToElementText(oElement);
        for (s; er1.compareEndPoints("StartToStart", er) < 0; s++) {
            er1.moveStart("character", 1)
        }
        return s
    };
    it.selectionBefore = function(oElement) {
        return oElement.value.slice(0, it.selectionStart(oElement))
    };
    it.selectText = function(oElement, nStart, nEnd) {
        oElement.focus();
        if (!ds) {
            oElement.setSelectionRange(nStart, nEnd);
            return
        }
        var c = oElement.createTextRange();
        c.collapse(1);
        c.moveStart("character", nStart);
        c.moveEnd("character", nEnd - nStart);
        c.select()
    };
    it.insertText = function(oElement, sInsertText, nStart, nLen) {
        oElement.focus();
        nLen = nLen || 0;
        if (!ds) {
            var text = oElement.value,
            start = nStart - nLen,
            end = start + sInsertText.length;
            oElement.value = text.slice(0, start) + sInsertText + text.slice(nStart, text.length);
            it.selectText(oElement, end, end);
            return
        }
        var c = ds.createRange();
        c.moveStart("character", -nLen);
        c.text = sInsertText
    };
    it.getCursorPos = function(obj) {
        var CaretPos = 0;
        if ($IE) {
            obj.focus();
            var range = null;
            range = ds.createRange();
            var stored_range = range.duplicate();
            stored_range.moveToElementText(obj);
            stored_range.setEndPoint("EndToEnd", range);
            obj.selectionStart = stored_range.text.length - range.text.length;
            obj.selectionEnd = obj.selectionStart + range.text.length;
            CaretPos = obj.selectionStart
        } else {
            if (obj.selectionStart || obj.selectionStart == "0") {
                CaretPos = obj.selectionStart
            }
        }
        return CaretPos
    };
    it.getSelectedText = function(obj) {
        var selectedText = "";
        var getSelection = function(e) {
            if (e.selectionStart != undefined && e.selectionEnd != undefined) {
                return e.value.substring(e.selectionStart, e.selectionEnd)
            } else {
                return ""
            }
        };
        if (window.getSelection) {
            selectedText = getSelection(obj)
        } else {
            selectedText = ds.createRange().text
        }
        return selectedText
    };
    it.setCursor = function(obj, pos, coverlen) {
        pos = pos == null ? obj.value.length: pos;
        coverlen = coverlen == null ? 0 : coverlen;
        obj.focus();
        if (obj.createTextRange) {
            var range = obj.createTextRange();
            range.move("character", pos);
            range.moveEnd("character", coverlen);
            range.select()
        } else {
            obj.setSelectionRange(pos, pos + coverlen)
        }
    };
    it.unCoverInsertText = function(obj, str, pars) {
        pars = (pars == null) ? {}: pars;
        pars.rcs = pars.rcs == null ? obj.value.length: pars.rcs * 1;
        pars.rccl = pars.rccl == null ? 0 : pars.rccl * 1;
        var text = obj.value,
        fstr = text.slice(0, pars.rcs),
        lstr = text.slice(pars.rcs + pars.rccl, text == "" ? 0 : text.length);
        obj.value = fstr + str + lstr;
        this.setCursor(obj, pars.rcs + (str == null ? 0 : str.length))
    };
    return it
})(); 
//上传图片
function UploadPic()
{    
    //检查图片
    if(CheckImgData()==false)
    {
        return;
    }
    //显示等待div
    $("#divDoing").show();
    $("#divFile").hide();
    $.ajaxFileUpload(
    {
        url:'/miniblog/DataService/uploadpic.aspx?flag=uploadpic&userid='+ $("#txtLoginUserId").val(),            //需要链接到服务器地址
        secureuri:false,
        fileElementId:'filePic',                        //文件选择框的id属性
        dataType: 'json',                                     //服务器返回的格式，可以是json
        success: function (data, status)            //相当于java中try语句块的用法
        {
            if(data.IsSuccess=="true")
            {               
                document.getElementById('Sendblog1_txtPic').value=data.message;
                ShowExpressPic('pic');
            }
            else
            {
                alert(data.message);
                $("#divFile").show();
                $("#divDoing").hide();            
            }
        },
        error: function (data, status, e)            //相当于java中catch语句块的用法
        {
            alert(e.message);
            alert('发生意外错误！');
        }
    });
}


function CheckImgData()
{
    var imgSelect = document.getElementById ( "filePic" );
    if ( imgSelect.value == '' )
    {
	    alert('请选择图片然后上传！');
		return false;
    }
    else
    {
	    var imgType = /\.jpg$|\.gif$|\.png$|\.bmp$/i;
	    if ( !imgType.test ( imgSelect.value ) )
	    {
            alert('只允许上传图片文件！');
            return false;
	    }
    }
    return true;
}
function ExpressPicClose(closeType)
{
    if(closeType=="express")
    {
        $('#divExpress').hide();
    }
    else
    {
        $('#divPic').hide();
    }    
}
function ExpressClick(strExpress)
{
    var contentObj = $('#ctl00_cphContent_txtContent')[0];
    contentObj.value = contentObj.value+strExpress;
}
function ShowExpressPic(showType)
{
    if($.cookie("user_id") == null ||$.cookie("user_id").length==0){Login(); return;}
    document.getElementById ( "filePic" ).value="";
    if(showType=="express")
    {
        $('#divPic').hide();
        $('#divExpress').show();    
    }
    else
    {
        $('#divExpress').hide();
        $('#divPic').show();
        //判断显示上传还是图片
        var txtPicUrl=$('#Sendblog1_txtPic').val();       
        if(txtPicUrl=="")
        {
            $('#divPic_show').hide();
            $('#divPic_upload').show();
            $('#divFile').show();
            $('#divDoing').hide();
        }
        else
        {
            $('#divPic_upload').hide();
            $('#divPic_show').show();
            document.getElementById("imgPic").src=txtPicUrl.replace("[model]","l");
        }
    }    
    return false;
}
//删除图片
function DeletePic()
{
    $('#Sendblog1_txtPic').val("");
    ShowExpressPic('pic');
}


//微博图片
(function($){
	$.fn.artZoom = function(){
		$(this).live('click', function(){
			var maxImg = $(this).attr('href'),
			viewImg = $(this).attr('rel').length === '0' ? $(this).attr('rel') : maxImg; // 如果连接含有rel属性，则新窗口打开的原图地址为此rel里面的地址
			
			if ($(this).find('.loading').length == 0) $(this).append('<span class="loading" title="加载中..">加载中..</span>');
			imgTool($(this), maxImg, viewImg);
			return false;
		});
		
		// 图片预先加载
		var loadImg = function (url, fn){
			var img = new Image();
			img.src = url;
			if (img.complete){
				fn.call(img);
			}else{
				img.onload = function(){
					fn.call(img);
				};
			};
		};
		
		// 图片工具条
		var imgTool = function(on, maxImg, viewImg) {
		    var width = 0,
			height = 0,
			tool = function(){
				on.find('.loading').remove();
				on.hide();
				
				if (on.next('.artZoomBox').length != 0){
					return on.next('.artZoomBox').show();
				};
				
				// 等比例限制宽度
				var maxWidth = on.parent().innerWidth() - 42; // 获取父级元素宽度	
				
				if (width > maxWidth) {
					height = maxWidth / width * height;
					width = maxWidth;
				};
				
				var html = '<div class="artZoomBox"><div class="tool"><a class="hideImg" href="#" title="收起">收起</a><a class="imgLeft" href="#" title="向左转">向左转</a><a class="imgRight" href="#" title="向右转">向右转</a><a class="viewImg" href="' + viewImg + '" title="查看原图">查看原图</a></div><a href="' + viewImg + '" class="maxImgLink"> <img class="maxImg" width="' + width + '" height="' + height + '" src="' + maxImg + '" /></a></div>';
				on.after(html);
				var box = on.next('.artZoomBox');
				box.hover(function(){
					box.addClass('js_hover');
				}, function(){
					box.removeClass('js_hover');
				});
				box.find('a').bind('click', function(){
					// 收起
					if($(this).hasClass('hideImg') || $(this).hasClass('maxImgLink')) {
						box.hide();
						box.prev().show();
					};
					// 左旋转
					if($(this).hasClass('imgLeft')) {
						box.find('.maxImg').rotate('left')
					};
					// 右旋转
					if($(this).hasClass('imgRight')) {
						box.find('.maxImg').rotate('right')
					};
					// 新窗口打开
					if($(this).hasClass('viewImg')) window.open(viewImg);
					
					return false;
				});
				
			};
			
			loadImg(maxImg, function(){
			    
				width = this.width;
				height= this.height;
				tool();
			});
			
			// 图片旋转
			// 方案修改自：http://byzuo.com/
			$.fn.rotate = function(p){

				var img = $(this)[0],
					n = img.getAttribute('step');

				// 保存图片大小数据
				if (!this.data('width') && !$(this).data('height')) {
					this.data('width', img.width);
					this.data('height', img.height);
				};

				if(n == null) n = 0;
				if(p == 'left'){
					(n == 3) ? n = 0 : n++;
				}else if(p == 'right'){
					(n == 0)? n = 3 : n--;
				};
				img.setAttribute('step', n);

				// IE浏览器使用滤镜旋转
				if(document.all) {
					img.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ n +')';
					// IE8高度设置
					if ($.browser.version == 8) {
						switch(n){
							case 0:
								this.parent().height('');
								//this.height(this.data('height'));
								break;
							case 1:
								this.parent().height(this.data('width') + 10);
								//this.height(this.data('width'));
								break;
							case 2:
								this.parent().height('');
								//this.height(this.data('height'));
								break;
							case 3:
								this.parent().height(this.data('width') + 10);
								//this.height(this.data('width'));
								break;
						};
					};
				// 对现代浏览器写入HTML5的元素进行旋转： canvas
				}else{
					var c = this.next('canvas')[0];
					if(this.next('canvas').length == 0){
						this.css({'visibility': 'hidden', 'position': 'absolute'});
						c = document.createElement('canvas');
						c.setAttribute('class', 'maxImg canvas');
						img.parentNode.appendChild(c);
					}
					var canvasContext = c.getContext('2d');
					switch(n) {
						default :
						case 0 :
							c.setAttribute('width', img.width);
							c.setAttribute('height', img.height);
							canvasContext.rotate(0 * Math.PI / 180);
							canvasContext.drawImage(img, 0, 0);
							break;
						case 1 :
							c.setAttribute('width', img.height);
							c.setAttribute('height', img.width);
							canvasContext.rotate(90 * Math.PI / 180);
							canvasContext.drawImage(img, 0, -img.height);
							break;
						case 2 :
							c.setAttribute('width', img.width);
							c.setAttribute('height', img.height);
							canvasContext.rotate(180 * Math.PI / 180);
							canvasContext.drawImage(img, -img.width, -img.height);
							break;
						case 3 :
							c.setAttribute('width', img.height);
							c.setAttribute('height', img.width);
							canvasContext.rotate(270 * Math.PI / 180);
							canvasContext.drawImage(img, -img.width, 0);
							break;
					};
				};
			};
			
		};
	};
	
	// 给所有含'artZoom'类的链接绑定本效果
	$('a.artZoom').artZoom();

})(jQuery);

