﻿/// <reference path="../js/Jquery/jquery-1.4.1-vsdoc.js" />
/// <reference path="/js/Common/TimeFormat.js" />
/// <reference path="../Common/face.js" />
/// <reference path="../dialog/jquery.XYTipsWindow.2.7.js" />
/// <reference path="../Common/template.js" />
/*
* liuwei 
* email: liuweishow@qq.com
* 2011-5-12
*/
//#region 获取所有动态的方法
var xmlhttp;
function getDynamic(beforecall, successcall, endcall, url, dongtaidiv) {
    xmlhttp = $.ajax({
        type: "get",
        dataType: "json",
        url: url,
        beforeSend: function () {
            if (beforecall) {
                beforecall();
            } $("#page").hide();
        },
        cache: false,
        success: function (response) {
            var NoData = true;
            if (response != null) {
                if (response.item.length > 0) {
                    NoData = false;
                    $(dongtaidiv).children().html("");
                    showData(response, dongtaidiv, 200, function () {
                        $("#page").show().unbind("click").bind("click", function () {
                            dynamicPaging(url, dongtaidiv, 1);
                        }).find(".bot_more").html("查看更多");
                    });
                    if (successcall) {
                        successcall();
                    }
                }
            }
            if (NoData) {
                if (successcall) {
                    successcall();
                }
                $("#page").show().css("margin-top", "0").find(".bot_more").html("暂无数据，点击重试");
            }

        },
        complete: function (response) {
            if (endcall) {
                endcall();
            }
            setdycontent();
        },
        error: function (response) {
            $(dongtaidiv).height(100).children().append("<div align='center' style='text-align:center; margin-top:30px;'>动态加载未成功，请<a onclick='javascript:;'>重试</a></div>").find("a").click(function () {
                getDynamic(beforecall, successcall, endcall, url, dongtaidiv)
            });

        }
    });
}
//#endregion

function dynamicPaging(url, dongtaidiv, pageindex) {
    $.ajax({
        type: "get",
        dataType: "json",
        cache: false,
        url: url + "&pageindex=" + pageindex,
        beforeSend: function () {
            $("#page").unbind("click");
            $("#page .bot_more").html("正在加载中……<img class='img_loading' src='/images/css/loadings.gif' />");
        },
        success: function (response) {
            var hasData = false;
            if (response != null) {
                if (response.item.length > 0) {
                    hasData = true;
                    for (var i = 0; i < response.item.length; i++) {
                        var h = AceTemplate.format("dateitem", response.item[i]);
                        $(dongtaidiv).children().append(h);
                    }
                    $("#page .bot_more").html("查看更多");
                }
            }
            if (!hasData) {
                $("#page .bot_more").html("暂无更多动态");
            }
            $("#page").bind("click", function () {
                dynamicPaging(url, dongtaidiv, pageindex + 1);
            });


        },
        complete: function () {
            setdycontent();
        },
        error: function (response) {
        }
    });
}
function setdycontent() {
    $(".write").find("a").attr("target", "_blank");
    $(".content").find("a").attr("target", "_blank");
    if ($(".fancy_showimg").length > 0) {
        $(".fancy_showimg").fancybox({
            'transitionIn': 'elastic',
            'transitionOut': 'elastic'
        });
    }
    $(".dongtai li").removeAttr("style");
}
//#region 现在时间格式化
function getTime() {
    return new Date().toLocaleString().toString().replace("年", "/").replace("月", "/").replace("日", "");
}
//#endregion

//#region 字数限制
function getCount(txtBox) {
    var Tip = $(txtBox).prev();
    var len = getLength($(txtBox).val(), 140);
    $(Tip).html(len + "/140");
    $(Tip).css("color", "#ccc");
    if (len > 140) {
        $(Tip).html("超出" + (len - 140) + "字");
        $(Tip).css("color", "red");
        return false;
    }
    else {
        return true;
    }
}
//#endregion 

//#region 发表处理
//仅发表视频+图片                                               
function getImageAndVideo(id, imgsrc, vedioimage, vediotitle, vediourl, url) {
    var imageAndVideo = $("#showImageAndVedio").children().clone(true);
    imageAndVideo.find(".img_small").attr("src", imgDomain + imgsrc).attr("id", "img_smal" + id);
    imageAndVideo.find(".imgicon").attr("src", vedioimage);
    imageAndVideo.find(".vedioclick").click(function () {
        miniblogApp.showVideo($(this), vediourl, vediotitle, url);
    });
    return imageAndVideo;
}
//仅发布图片
function getImage(id, src) {
    var image = $("#SingleImg").children().clone(true);
    image.find(".img_small").attr("src",  imgDomain + src).attr("id", "img_smal" + id);
    return image;
}
//仅发布视频
function getVideo(vedioimage, vediotitle, vediourl, url) {
    var video = $("#PlayVedio").children().clone(true);
    video.find(".imgicon").attr("src", vedioimage);
    video.find(".vedioclick").click(function () {
        miniblogApp.showVideo($(this), vediourl, vediotitle, url);
    });
    return video;
}
//#endregion

//#region 动态回复
function replyFirend(id, obj, userid, parentId, objectId, type) {
    if (!checkLogin()) { return; }
    var content_obj = $(obj).parents(".comment_html").find("textarea");
    if (!getCount(content_obj)) {
        $.XYTipsLoading("你的评论字数过多，请删减字数再进行回复。", 1500, false, null, "");
        return;
    }
    var chk = $(obj).parents(".comment_html").find("#chk_transmit");
    var iftransimit = chk.attr("checked") && chk.is(":visible");
    //如果该微博是转发的话
    if (iftransimit) {
        if ($(obj).find(".square_out_border").length > 0) {
            objectId = $(obj).parents(".Contentright").find("#transmit_data").val().split("|")[0];
        }
    }
    if ($.trim(content_obj.val()).length > 0) {
        $.ajax({
            type: "POST", //访问WebService使用Post方式请求     
            contentType: "application/json;charset=utf-8", //WebService 
            url: "/WebService/dynamicService.asmx/Replyfriend", //调用WebService   
            data: "{replyUserId:" + userid + ",objectId:'" + objectId + "',parentId:'" + parentId + "',content:'" + content_obj.val().replace(/\"/g, "\\\"") + "',type:'" + type + "',iftransimit:" + iftransimit + "}",    //参数     
            dataType: 'json',
            beforeSend: function (x) {
                x.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                $(obj).attr("disabled", "disabled");
                $.XYTipsLoading("正在提交回复内容，请稍候!", 15000, false, null, "2");
            },
            error: function (x, e) {
                $.XYTipsLoading("发送失败，请稍候再试!", 1000, false, null, "");
            },
            success: function (response) { //回调函数，result，返回值  
                response = eval("(" + response.d + ")")[0];
                if (response.id < 0) {
                    $.XYTipsLoading("服务器无法相应,请稍候再试", 1000, false, null, "");
                }
                else {
                    content_obj.val("");
                    var reply = new Object();
                    $.XYTipsLoading("回复成功!", 1000, false, null, "1");
                    reply.userDomain = $userinfo.userDomain;
                    reply.ub_name = $userinfo.ub_name;
                    reply.headPath = $userinfo.headPath;
                    reply.userId = $userinfo.userid;
                    reply.reply_content = response.value;
                    reply.id = response.id;
                    reply.time = response.time;
                    var replyfirst = AceTemplate.format("reply_item", reply);

                    var reply_parent = $(obj).parents(".Contentright").find(".reply_append");

                    if (reply_parent.find("ul").length < 1) { reply_parent.append(" <ul></ul>") }
                    //回复后显示到最前边
                    reply_parent.children().prepend(replyfirst);
                }
                //回复框默认
                $(obj).removeAttr("disabled", "disabled");
                //cancelReply(id, obj, type, userid, objectId, parentId);
            }
        });
    }
    else {
        $.XYTipsLoading("请填写回复内容!", 1000, false, null, "");
    }
}
//#endregion

//#region 转发微博
function transmit_weibo(obj) {
    var val = $(obj).parents(".upbox").find(".miniblog_content").val();
    info = $(obj).data("t_data");
    var id = info.id;
    var type = info.type;
    var userid = info.userid;
    var content = val == "顺便说点什么吧……" ? "" : val;
    var ifreply = $(obj).parents(".upbox").find(".transmit_check").attr("checked");
    $.ajax({
        type: "post",
        data: {
            id: id,
            userid: userid,
            type: type,
            content: content,
            ifreply: ifreply
        },
        url: "/ashx/miniblog/miniblog.ashx?type=1",
        beforeSend: function () {
            $.XYTipsWindow.removeBox();
            $.XYTipsLoading("正在转发,请稍候", 10000, false, null, 2);
        },
        success: function () {
            $.XYTipsLoading("转发成功", 1500, false, null, 1);
        },
        error: function (x, y) {
            $.XYTipsLoading("服务器没有响应，转发失败，请稍候再试！", 1500, false, null, 2);
        }
    });

}
//#endregion

function getReplyAll(type, objectId, id) {
    var obj = $("#getall_reply_" + id);
    $.ajax({
        type: "get",
        dataType: "json",
        cache:false,
        url: "/ashx/miniblog/miniblog.ashx?type=13&objectid=" + objectId + "&typeid=" + type,
        beforeSend: function () { $(obj).html("") },
        success: function (response) {
            if (response != null) {
                var reply = response.item;
                var replyRemain = $("<ul></ul>");
                for (var i = 0; i < reply.length - 1; i++) {
                    var replydata_obj = AceTemplate.format("reply_item", reply[i]);
                    replyRemain.append(replydata_obj);
                }
                replyRemain.children().insertAfter(obj.parent());
                obj.parent().remove();
            }
        }
    });
}
//点击回复，加载回复框 动态id    出发事件的对象    动态的类型    回复人的id    动态的某种类型的唯一ID    父级id
function replys(id, obj, type, userid, objectid, parentId) {
    if ($userinfo == "0") {
        checkLogin("/profile/index.aspx");
        return;
    }
    var parentNode = $(obj).parent();
    var comment = $("#ajaxComment").children().clone(true).hide();
    comment.find("#reply").click(function () {
        replyFirend(id, $(this), userid, "", objectid, type);
    });
    comment.find("#cancelreply").click(function () {
        cancelReply(id, $(this), type, userid, objectid, parentId);
    });
    parentNode.prepend(comment);
    $(obj).remove();
    ($(parentNode).find(".comment_html")).animate({
        height: 'show', opacity: 'show'
    }, "fast", function () {
        var t = $(this).find("textarea").focus();
        var txtRange = document.selection.createRange();
        txtRange.moveStart("character", t.val().length);
        txtRange.moveEnd("character", 0);
        txtRange.select();
        if (type == 140001 || (type > 190007 && type < 200001)) {
            comment.find(".sametime").css("display", "block");
        }
    });
}
//取消回复
function cancelReply(id, obj, type, userid, objectid, parentId) {
    if (parentId == "" || parentId == 0) {
        parentId = null;
    }
    var p = $(obj).parents(".comment_html").parent();
    p.html(" <input type='text' class='preReply' value='回复……' onclick='replys(" + id + ",$(this)," + type + "," + userid + "," + objectid + "," + parentId + ");" + "' />");
}


var getLength = (function () {
    var trim = function (h) {
        try {
            return h.replace(/^\s+|\s+$/g, "")
        } catch (j) {
            return h
        }
    }
    var byteLength = function (b) {
        if (typeof b == "undefined") {
            return 0
        }
        var a = b.match(/[^\x00-\x80]/g);
        return (b.length + (!a ? 0 : a.length))
    };

    return function (q, g) {
        g = g || {};
        g.max = g.max || 140;
        g.min = g.min || 41;
        g.surl = g.surl || 20;
        var p = trim(q).length;
        if (p > 0) {
            var j = g.min,
                    s = g.max,
                    b = g.surl,
                    n = q;
            //输入字符串
            var r = q.match(/(http|https):\/\/[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+([-A-Z0-9a-z\$\.\+\!\_\*\(\)\/\,\:;@&=\?~#%]*)*/gi) || [];
            var h = 0;
            return Math.ceil((h + byteLength(n)) / 2)
        } else {
            return 0
        }
    }
})();

function transilen(obj) {
    var len = getLength($(obj).val(), 140);
    if (len > 140) {
        $("#btn_miniblog_transmit").attr("disabled", "disabled");
        $(".upbox_text_tip").html("超出");
        $(".upbox_text_length").html(-140 + len).css("color", "red");
    }
    else {
        $("#btn_miniblog_transmit").removeAttr("disabled");
        $(".upbox_text_tip").html("还可以输入");
        $(".upbox_text_length").css("color", "black");
        $(".upbox_text_length").html(140 - len);
    }
}
function showface(obj) {
    $(obj).selectFace('$(this).parents(".comment_html").find("textarea")');
}
//#region 页面加载
$(document).ready(function () {
    $("#comment_html_face").selectFace('$(".upbox").find("textarea")');

    $(".upbox").find("textarea").keyup(function () {
        transilen($(this));
    }).mouseup(function () {
        transilen($(this));
    }).mouseover(function () {
        transilen($(this));
    }).mousemove(function () {
        transilen($(this));
    });
    //转发框
    $(".transmit").live("click", function () {
        var obj = $(this);
        var p = obj.parents(".Contentright");
        var atcontent = "顺便说点什么吧……";
        var user = p.find(".name");
        var info = user.attr("rel").split("|");
        var ub_name = user.find("a:first").html();
        var atName = (info[0] == null || info[0] == "") ? ub_name : info[0];
        var weibo = "<a href=/" + userid + " target='_blank'>@" + atName + "</a> :" + p.find(".content:eq(0)").html();
        var userid = info[1];
        var objectiid = p.parent().find("#showObjectId").val();
        var type = p.parent().find("#showtype").val()
        //如果该微博是转发的话
        if (p.find(".square_out_border").length > 0) {
            var reTag = /<(?:.|\s)*?>/g;
            weibo = p.find(".content:eq(1)").html();
            atcontent = "//@" + atName + " :" + p.find(".content:eq(0)").html().replace(reTag, "");
            var trans = p.find("#transmit_data").val().split('|');
            objectiid = trans[0];
            userid = trans[1];
        }
        var t = $("#btn_miniblog_transmit");
        var t_data = { id: objectiid, userid: userid, content: content, type: type };
        t.data("t_data", t_data);
        $(".upbox").find("#t_id").val(objectiid).next("#t_uid").val(userid);
        $(".upbox").find("#content").html(weibo);
        $(".upbox").find(".miniblog_content").val(atcontent);
        $(".upbox").find(".comment").find("label").html("同时评论给:&nbsp;&nbsp;" + ub_name);

        $.XYTipsWindow({
            ___content: "id:mblog_transmit_box",
            ___showbg: true,
            ___title: "转发微博",
            ___drag: "___boxTitle",
            ___width: $("#mblog_transmit_box").width(),
            ___height: $("#mblog_transmit_box").height(),
            ___fns: function () { transilen($(".upbox").find(".miniblog_content")); }
        });

    });
    $(".miniblog_content").focus(function () {
        if ($(this).val() == "顺便说点什么吧……") {
            $(this).val("");
        }
        var txtRange = document.selection.createRange();
        txtRange.moveStart("character", 0);
        txtRange.moveEnd("character", 0);
    });
    $(".dongtai").find("#comment").live("click", function () {
        var parent = $(this).parents(".Contentright").parent();
        var reply = parent.find(".reply_append");
        var type = parent.find("#showtype").val();
        var objectid = parent.find("#showObjectId").val();
        var style = $(this).attr("s");
        var c = $(this).attr("c");
        reply.css("display", style).next().css("display", style);
        if (style == "block") {
            $(this).attr("s", "none");
            $.ajax({
                url: "/ashx/common/reply.ashx?pageSize=5&type=5&Uniqueid=" + objectid + "&sortid=" + type + "&t=" + new Date(),
                cache: false,
                dataType: "json",
                beforeSend: function () {
                    reply.html("<ul><li>正在加载中，请稍候<img src='/images/css/loading_s.gif' valign='absmiddle' /></li></ul>");
                },
                error: function (response) {
                    alert(response);
                },

                success: function (data) {
                    if (data.item.length > 0) {
                        var h = "";
                        for (var i = 0; i < data.item.length; i++) {
                            h += AceTemplate.format("reply_item", data.item[i]);
                        }
                        if (c > 5) {
                            h += "<li style='text-align:center;' align='center'><a target='_blank' href=" + parent.find("#link").val() + ">查看全部评论</a></li>";
                        }
                        reply.children().html(h);
                    }
                    else {
                        reply.html("<ul></ul>");
                    }
                }
            });


            //            $.getJSON("/ashx/common/reply.ashx?pageSize=5&type=5&Uniqueid=" + objectid + "&sortid=" + type + "&t=" + new Date(), function (data, txtStatus) {
            //               
            //            });

        }
        else {
            $(this).attr("s", "block");
        }

    });
    $(".dongtai").find("#atfriend").live("click", function () {
        var parents = $(this).parents(".Contentright");
        var change_reply = parents.find(".comment_html");
        var type = parents.parent().find("#showtype").val();
        var objectId = parents.parent().find("#showObjectId").val();
        var id = parents.parent().find("#dyid").val();
        var atName = $(this).attr("atName");
        var userId = $(this).attr("uid");
        //判断编辑框是否存在，如果存在提示 回复好友变为当前选择的好友
        if (change_reply.length < 1) {
            replys(id, $(this).parents(".Contentright").find(".preReply"), type, userId, objectId);
        }
        $(this).parents(".Contentright").find("textarea").val("回复@" + atName + " :").focus();
    });
});
//#endregion

//#region 微博
var miniblogApp = new Object();
miniblogApp.showVideo = function (obj, src, title, url) {
    var html = $("#PlayingVedio").children().clone(true);
    html.find("#Vediosrc").html(miniblogApp.playing(src));
    html.find("#VideoURL").attr("href", url).html(title);
    $(obj).parents(".smalView").hide().next().html("").append(html).show();
}
miniblogApp.playing = function (src) {
    var swfhtml = '<object  codebase=" http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="500" height="500">' +
                        '<param name="movie" value="' + src + '" />' +
                        '<param name="quality" value="high" />' +
                        '<param name="wmode" value="transparent">' +
                        '<param name="wmode" value="Opaque">' +
                        '<param name="wmode" value="Window">' +
                        '<embed src="' + src + '" quality="high" pluginspage=" http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="500" height="500"></embed>' +
                        '</object>'
    return swfhtml;
}
miniblogApp.hideVideo = function (obj) {
    $(obj).parents(".BigView").html("").prev().show();
}
miniblogApp.showImage = function (obj, id) {
    var bigimg = $("#showBigImage").children().clone(true);
    var img = bigimg.find(".imgSmall");
    bigimg.find("#bigsrc").attr("href", $(obj).attr("src").replace("_s.", "."));
    src = $(obj).attr("src").replace("_s.", "_l.");
    id = $(obj).attr("id").replace("img_smal", "");
    img.attr({ "src": src, "id": "img_" + id });
    $(obj).parents(".smalView").hide().next().html("").append(bigimg).show();

    var maxWidth = 440;
    var width = 0, height = 0;
    miniblogApp.loadImg(src, function () {
        height = this.height,
       width = this.width;
        if (width > maxWidth) {
            height = maxWidth / width * height;
            width = maxWidth;
        };
        img.attr("raw_height", height);
        img.attr("raw_width", width);
    });
}
miniblogApp.hideImage = function (obj) {
    $(obj).parents(".BigView").html("").prev().show();
}
miniblogApp.Roll = function (obj, name) {
    var img = $(obj).parents(".blogPicOri").find(".imgSmall");
    img.rotate(name, 440);
}
miniblogApp.loadImg = function (url, fn) {
    var img = new Image();
    img.src = url;
    if (img.complete) {
        fn.call(img);
    } else {
        img.onload = function () {
            fn.call(img);
        };
    };
}
//***************************/
$.fn.rotate = function (name, maxWidth) {
    var img = $(this)[0],
			step = img.getAttribute('step');
    if (!this.data('width') && !$(this).data('height')) {
        this.data('width', img.width);
        this.data('height', img.height);
    };
    if (step == null) step = 0;
    if (name === 'left') {
        (step == 3) ? step = 0 : step++;
    } else if (name === 'right') {
        (step == 0) ? step = 3 : step--;
    };
    img.setAttribute('step', step);
    var show_width = this.data('width'),
			show_height = this.data('height');
    if ((step == 1 || step == 3) && this.data('width') < this.data('height') && this.data('height') > maxWidth) {
        show_height = maxWidth;
        show_width = this.data('width') * maxWidth / this.data('height');
    }
    // IE浏览器使用滤镜旋转
    if (document.all) {
        img.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + step + ')';
        img.width = show_width;
        img.height = show_height;
        // IE8高度设置
        if ($.browser.version == 8) {
            switch (step) {
                case 0:
                    this.parent().height('');
                    break;
                case 1:
                    this.parent().height(this.data('width') + 10);
                    break;
                case 2:
                    this.parent().height('');
                    break;
                case 3:
                    this.parent().height(this.data('width') + 10);
                    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');
            c.setAttribute("onclick", "miniblogApp.hideImage(this);");
            //  c.setAttribute("onclick", miniblogApp.hideImage(this));
            img.parentNode.appendChild(c);
        }
        var canvasContext = c.getContext('2d');
        var resizefactor = 1;
        show_height = img.raw_height = $(img).attr('raw_height'); //图片原始高度
        show_width = img.raw_width = $(img).attr('raw_width'); 		//原始宽度
        if ((step == 1 || step == 3) && img.raw_height > maxWidth) {
            resizefactor = maxWidth / img.raw_height;
            show_height = maxWidth;
            show_width = resizefactor * img.raw_width;
        }
        if ((step == 0 || step == 2) && img.raw_width > maxWidth) {
            resizefactor = maxWidth / img.raw_width;
            show_height = resizefactor * img.raw_height;
            show_width = maxWidth;
        }
        switch (step) {
            default:
            case 0:
                c.setAttribute('width', show_width);
                c.setAttribute('height', show_height);
                canvasContext.rotate(0 * Math.PI / 180);
                canvasContext.scale(resizefactor, resizefactor);
                canvasContext.drawImage(img, 0, 0);
                break;
            case 1:
                c.setAttribute('width', show_height);
                c.setAttribute('height', show_width);
                canvasContext.rotate(90 * Math.PI / 180);
                canvasContext.scale(resizefactor, resizefactor);
                canvasContext.drawImage(img, 0, -img.raw_height);
                break;
            case 2:
                c.setAttribute('width', show_width);
                c.setAttribute('height', show_height);
                canvasContext.rotate(180 * Math.PI / 180);
                canvasContext.scale(resizefactor, resizefactor);
                canvasContext.drawImage(img, -img.raw_width, -img.raw_height);
                break;
            case 3:
                c.setAttribute('width', show_height);
                c.setAttribute('height', show_width);
                canvasContext.rotate(270 * Math.PI / 180);
                canvasContext.scale(resizefactor, resizefactor);
                canvasContext.drawImage(img, -img.raw_width, 0);
                break;
        };
    };
}
//#endregion

function showData(response, dongtaidiv, timeout, call) {
    var i = 0;
    var s = setInterval(function () {
        var h = "";
        if (i < response.item.length) {
            h += AceTemplate.format("dateitem", response.item[i]);
            i++;
        }
        else {
            if (call) {
                call();
            }
            clearInterval(s);
            setdycontent();
        }
        $(dongtaidiv).children().append($(h).fadeIn());
        setdycontent();
        $(".dongtai").find("li").removeAttr("style");
    }, timeout);
}


