﻿var bookId = 0;
$(document).ready(function() {
    try { document.execCommand("BackgroundImageCache", false, true); } catch (e) { }
    $("#menu > li").hover(
        function() {
            $(this).find("a:first").addClass("ah").next().prepend("<li class='sub'></li>").show();
        },
        function() {
            $(this).find("a:first").removeClass("ah").next().hide().find("li:first").remove();
        }
    )

    $("#visitor .sub").hover(
        function() {
            $(this).find("a:first").addClass("hover").next().show();
        },
        function() {
            $(this).find("a:first").removeClass("hover").next().hide();
        }
    )

    $("#butkey").click(function() {
        var key = $.trim($("#keyword").val());
        searchkey(key);
    })
    if ($("#newBoard").length == 1) {
        $("#Textarea1").next().click(function() {
            if (bookId != 0) {
                Remark(bookId);
                bookId = 0;
            }
        });

        $("#newBoard").click(function() {
            var shade = $("#bgGray"), notice = $("#notice"), createGather = $("#createGather"), newBoard = "";
            if (shade.length == 0) {
                $("body").append("<div id='bgGray'></div>")
            }
            if (notice.length == 0) {
                $("body").append("<div id='notice'></div>")
            }
            if (createGather.length == 0) {
                newBoard = "<div id=\"createGather\">";
                newBoard += "<div class=\"title\"><a class=\"tr\" href=\"javascript:closeBox('createGather')\"><img alt=\"关闭\" src=\"/images/close.gif\" /></a><p class=\"tl\" onmousedown=\"setPosition(event,'createGather')\">创建图集</p></div>";
                newBoard += "<div class=\"con\">";
                newBoard += "<input type=\"text\" class=\"ipt\" value=\"图集名称\" placeholder=\"图集名称\" name=\"title\" id=\"id_name\" onfocus=\"if(this.value==this.defaultValue)this.value=''\" onblur=\"if(this.value=='')this.value=defaultValue\" /><br />";
                newBoard += "<p class=\"h\">分类（必选）</p>";
                newBoard += "<div id=\"sort\"></div>";
                newBoard += "</div>";
                newBoard += "</div>";
                $.ajax({
                    url: "/controls/ajax.ashx",
                    dataType: "json",
                    data: { pinsort: new Date().getTime() },
                    success: function(obj) {
                        $.each(obj, function(n, con) {
                            $("#sort").append("<span class='rbtl sort'><input type=\"radio\" name=\"sort\" value=\"" + con.id + "\" id=\"sort_" + con.id + "\" /><label for=\"sort_" + con.id + "\">" + con.name + "</label></span>\n");
                        })
                        $("#createGather .con").append("<div class=\"tc\"><a href=\"#!\" class=\"btn_p\" onclick=\"addGather()\"><span>创建</span></a></div>");
                    }
                })
            }
            if (newBoard != "") {
                $("#bgGray").css({ height: $(".footer").outerHeight() + $(".footer").offset().top + 10 }).show().after(newBoard)
                $("#createGather").css({ left: ($(window).width() - 400) / 2, top: $(document).scrollTop() + ($(window).height() - 500) / 2 }).show()
            } else {
                $("#bgGray").show();
                $("#createGather").show();
            }
        });
    }
    if ($("#mySelect").length == 1) {
        $(document).click(function(e) {
            if (isClickIn(".select", e) == false) {
                $("#mySelect").hide()
            }
        });
        $("#selected").click(function() {
            $("#mySelect").show();
        })
        $("#creatMyS").click(function() {
            var name = $.trim($(this).prev().val());
            if (name == "") {
                $("#notice").text("名称不能为空").css({ left: ($(window).width() - $("#notice").width()) / 2, top: ($(window).scrollTop() + $(window).height() - $("#notice").height()) / 2 }).fadeIn(500).delay(3000).fadeOut(500)
            } else {
                var isExist = false;
                $("#notice").hide().stop();
                $("#mySelect ul li").each(function() {
                    if ($(this).text() == name) {
                        $("#notice").text("名称已存在，换一个试试").css({ left: ($(window).width() - $("#notice").width()) / 2, top: ($(window).scrollTop() + $(window).height() - $("#notice").height()) / 2 }).fadeIn(500).delay(3000).fadeOut(500);
                        isExist = true;
                        return false;
                    }
                })
                //alert(isExist)
                if (isExist) {
                    return false;
                }
                $.ajax({
                    dataType: "json",
                    url: "/controls/ajax.ashx",
                    data: { myPinsName: name, ran: new Date().getTime() },
                    success: function(myS) {
                    $("#selected").text(myS[0].html)
                        if (myS.length > 0) {
                            var str = "";
                            $.each(myS, function(n, con) {
                                str += "<li val='" + con.val + "'><a href='#!'>" + con.html + "</a></li>";
                            })
                            $("#mySelect ul").prepend(str).find("li").click(function() {

                                var val = $(this).attr("val");
                                var html = $(this).text();
                                $("#selected").text(html)
                                $("#hdSelect").val(html)
                                $("#mySelect").hide();
                           

                            });
                        }
                        $("#mySelect").hide();
                        $("#creatMyS").prev().val("")
                    },
                    error: function() {
                        //alert(2)
                    }
                })
            }
        });
    }
});

function love( DingIid, dingFromIid){   
    ///alert($("#" + dingFromIid + " .pinbtn a:eq(1)").attr("title"))
    $.ajax({
        dataType:"json",
        url: "/controls/ajax.ashx",
        data: {DingIid: DingIid, dingFromIid: dingFromIid, ran: new Date().getTime() },
        success: function(v) {
            if (v == "请登录") {
                window.open("/user/login.html", "_top")
            }
            else if (v == "已喜欢") {
                $("#" + dingFromIid + " .pinbtn a:eq(1)").css("background-position", "-112px 0");
            }
            else if (v == "喜欢") {
                $("#" + dingFromIid + " .pinbtn a:eq(1)").css("background-position", "-112px -35px");
            }
        }
    });    
}

function book(id, pic) {
    bookId = id;
    showDiv('pinbook');
    $(".con:eq(1)").find("img").attr("src", pic);
    showMySelect('mySelect');
}
function com(id, dingIid) {
    showDiv('box');
    $("#pinId").val(id);
    $("#dingIid").val(dingIid);
}

/*gotop----*/
var lastScrollY=0;
function heartBeat(){
    sobj=document.getElementById("gotop");
    var diffY;
    if (document.documentElement && document.documentElement.scrollTop){
        diffY = document.documentElement.scrollTop;
    }else if (document.body){
        diffY = document.body.scrollTop
    }else
        {/*Netscape stuff*/}
    if(diffY>100){
        sobj.style.display="block";
    }else{
        sobj.style.display="none";
    }
    percent=.1*(diffY-lastScrollY);
    if(percent>0){
        percent=Math.ceil(percent);
    }else{
         percent=Math.floor(percent);
    }
    sobj.style.top=parseInt(sobj.style.top)+percent+"px";
    lastScrollY=lastScrollY+percent;
}

function goTop(){
    document.getElementById("gotop").style.top=document.documentElement.clientHeight-150+"px";
    setInterval("heartBeat()",1);
    $("#gotop").click(function(){
        $('html,body').animate({scrollTop:0},500);
    });    
}

function showMySelect(id){
    var obj = $("#"+id);
    obj.find("ul").empty();
    $.ajax({
        dataType: "json",
        url: "/controls/ajax.ashx",
        data: { mySelect: new Date().getTime() },
        success: function(myS) {
            if (myS.length > 0) {
                var str = "";
                $.each(myS, function(n, con) {
                    str += "<li val='" + con.val + "'><a href='#!'>" + con.html + "</a></li>";
                })
                $("#selected").text(myS[0].select);
                obj.find("ul").append(str).find("li").each(function() {
                    $(this).click(function() {
                        var val = $(this).attr("val");
                        var html = $(this).text();
                        $("#selected").text(html);
                        $("#hdSelect").val(html);
                        $("#mySelect").hide();
                        $.ajax({
                            dataType: "json",
                            url: "/controls/ajax.ashx",
                            data: { hdselect: html, ran: new Date().getTime() },
                            success: function(c) { }
                        });
                    })
                });
//                $("#selected").text(myS[0].html)
//                if ($("#hdSelect").val() != "-1") {  //默认选中之前选中的
//                    $("#selected").text($("#hdSelect").val());
//                }
            }

        },
        error: function() {
            //alert(2)
        }
    })
}

function isClickIn(d,c){
    var b=$(d);
    var c=c?c:window.event;
    var a=c.srcElement||c.target;
    if($(a).parents(d).length>0){
        return true
    }else{
        return false
    }
}


//再次remark   add by luozi
//dingIid 钉客的主键
function Remark(dingIid) {    
    var GatherName=$("#selected").text();
    var discription = $("#Textarea1").val();
    if(GatherName=="null"){
        $("#notice").text("请添加图集再装订").css({left:($(window).width()-$("#notice").width())/2,top:($(window).scrollTop()+$(window).height()-$("#notice").height())/2}).fadeIn(500).delay(3000).fadeOut(500);
        return false;
    }
    $.ajax({
        dataType: "json",
        url: "/controls/ajax.ashx",
        data: { dingIid: dingIid, GatherName: GatherName, discription: discription, ran: new Date().getTime()},
        success: function(v) {            
            if(v=="请添加图集再装订"){
                 $("#mySelect").show();//打开添加图集
                return false;
            }else{
                //$("#Textarea1").next().unbind("click");
                closeBox('pinbook');   
                return true;         
            }
          
        },
        error: function() {
            //alert("ajax错误");
        }

    });
}

//发布图片
function addDings() {
    $("#notice").hide().stop();
    var GatherName = $("#selectedding").text();
    var discription = $("#Textarea2").val();
    var picUrl="" ;
    if ($("#IMGSRC").val() != "") {
        picUrl = $("#IMGSRC").val();
    } else {
        picUrl = $("#uploadImg").attr("src");
    }
 
    if ($("#uploadImg").attr("src") == "/picture_library/p015.jpg") {
        $("#notice").text("上传图片后才能点哦！").css({left:($(window).width() - $("#notice").width())/2,top:($(window).scrollTop() + $(window).height() - $("#notice").height()) / 2 }).fadeIn(500).delay(3000).fadeOut(500);
        return false;
    }
    $.ajax({
        dataType: "json",
        url: "/controls/ajax.ashx",
        data: { gather_name: GatherName, discription: discription, picurl: picUrl, ran: new Date().getTime() },
        success: function(v) {
            alert(v);
            //$("#Textarea2").next().unbind("click");
            closeBox('showpins');
        },
        error: function() {
            //alert("ajax错误");
        }
    });
}
//批量发布图片
function addDingsAll() {
    $("#notice").hide().stop();
    var GatherName = $("#selectedAll").text();
    var   picUrl = $("#IMGSRC").val();

    if (picUrl == "") {
        $("#notice").text("上传图片后才能点哦！").css({ left: ($(window).width() - $("#notice").width()) / 2, top: ($(window).scrollTop() + $(window).height() - $("#notice").height()) / 2 }).fadeIn(500).delay(3000).fadeOut(500);
        return false;
    }
    $.ajax({
        dataType: "json",
        async:true,
        url: "/controls/ajax.ashx",
        data: { gather_name: GatherName, picurl: picUrl, ran: new Date().getTime() },
        success: function(v) {
            //closeBox('addAllPins')
        }
    });
}
//发布图集
function addGather() {
    $("#notice").hide().stop();
    var gather = $("#id_name");
    var sort = $("#sort").find("input:checked").val();
    var warn = "";
    if(gather.val() == gather.attr("placeholder") || gather.val() == "") {
        warn += "要填写图集名称哦.";
    }else if(sort==undefined){
        warn += "请选择一个分类."
    }
    if(warn!=""){
        $("#notice").text(warn).css({left:($(window).width() - $("#notice").outerWidth())/2,top:($(window).scrollTop() + $(window).height() - $("#notice").outerHeight())/2 }).fadeIn(500).delay(3000).fadeOut(500);
        return false;
    }
    $.ajax({
        url: "/controls/ajax.ashx",
        data: { gatherforname: gather.val(), gathercate: sort, ran: new Date().getTime() },
        success: function(v) {
            if (v == "名称已重复") {
                $("#notice").text(v).css({ left: ($(window).width() - $("#notice").outerWidth()) / 2, top: ($(window).scrollTop() + $(window).height() - $("#notice").outerHeight()) / 2 }).fadeIn(500).delay(3000).fadeOut(500);
            }
            else {
                location.href =v;
            }
        }
    });
}




function ajaxComment() {
    $("#notice").hide().stop();
    var pinId = $("#pinId").val();
    var dingIid = $("#dingIid").val();
    var _obj = $("#" + pinId);
    var h = _obj.outerHeight();
    var x = _obj.attr("name")
    var comment = escapeHTML($("#comment").val());

    if (comment == "") {
        $("#notice").text("好歹也写点东西啊！").css({ left: ($(window).width() - $("#notice").width()) / 2, top: ($(window).scrollTop() + $(window).height() - $("#notice").height()) / 2 }).fadeIn(500).delay(3000).fadeOut(500);
        return false;
    }
  
    $.ajax({
        url: "/controls/ajax.ashx",
        dataType: "json",
        data: { ran: new Date().getTime(), dingIid: dingIid, pinId: pinId, comment: comment },
        success: function(obj) {
            if (obj.length == 1) {
                closeBox('box');
                var str = "<div class='comment'>";
                str += "<a href='" + obj[0].mhref + "' class='avatar'><img src='" + obj[0].avatar + "' /></a><p><a href='" + obj[0].mhref + "'>" + obj[0].userName + "</a> " + obj[0].comment + "</p>";
                str += "</div>";
                if (_obj.find(".comments").length > 0) {
                    _obj.find(".comments").append(str)//.find(".comment:last").show(300);
                }
                else {
                    _obj.find(".pinOrigin").append("<div class='comments'></div>");
                    _obj.find(".comments").append(str)//.find(".comment:last").show(300);
                }
                h = _obj.outerHeight() - h;
                var hh = 0;
                _obj.nextAll().each(function() {
                    if ($(this).attr("name") == x){
                        $(this).animate({ top: $(this).position().top + h }, 200);
                    }
                })
                $(".pin[name='"+x+"']").each(function(){
                    hh += $(this).outerHeight()+16
                })
                if(_obj.parent().outerHeight()<hh){
                    _obj.parent().height(hh)
                }
            }
        }
    })
}


function escapeHTML(htmlstr) {
    if (typeof (htmlstr) == 'string') {
        return htmlstr.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    } else {
        return htmlstr;
    }
}


//给人添加关注 add by luozi
function AddUserAttention(attentionUserIid) {     
    $.ajax({
        dataType:"json",
        url:"/controls/ajax.ashx",
        data:{attentionUserIid:attentionUserIid ,dotype:"addUserAttention",ran:new Date().getTime()},
        success:function (v) {             
         var vArr=v.split("|");
         if(vArr[0]=="取消关注"){
            $("#attentionType").html("<a href='javascript: DelUserAttention("+vArr[1]+")' class='btnAttention btn'>取消关注</a>");
                    
            $(".pins").find(".tc").each(function () {//each
                  $(this).html( "<a onclick='return DelGatherAttention("+$(this).attr("id")+")' class='btnAttention btn' href='#'>取消关注</a>");
               
            })
           
         }
                        
        },
        error:function () {
            //alert("ajax错误");
        }
    
    });  
    
}

//取消人的关注 add by luozi
function DelUserAttention(attentionUserIid) {
        $.ajax({
        dataType:"json",
        url:"/controls/ajax.ashx",
        data: { attentionUserIid: attentionUserIid, dotype: "delUserAttention", ran: new Date().getTime() },
        success:function (v) {  
         var vArr=v.split("|");
         if(vArr[0]=="关注"){
            $("#attentionType").html("<a href='javascript: AddUserAttention("+vArr[1]+")' class='btnAttention btn'>关注</a>");
             $(".pins").find(".tc").each(function () {//each
                  $(this).html( "<a onclick='return AddGatherAttention("+$(this).attr("id")+")' class='btnAttention btn' href='#'>添加关注</a>");
               
            })
         }
                       
        },
        error:function () {
            //alert("ajax错误");
        }
    
    }); 
}
//非空验证
function checkEmpty(id,txt) {
    var obj=$("#"+id);
    if(obj.val()==""){
        obj.focus();
        obj.next("span").text(txt); 
        return false;   
    }else{
         obj.next("span").text("");    
         return true;
    }
}

function searchkey(key) {
    location.href = "/search/pins/?q=" + key;
    
}


//从别人网站上得到图片  add by luozi
//dingIid 钉客的主键
function AddDingFormYou() {  
    var GatherName=$("#selected").text();
    var discription = $("#Textarea1").val();
    var locationUrl = window.location.toString();//当前网址
    var urlForm = locationUrl.substring(locationUrl.indexOf("url=")+4).split("&")[0];
    var imgSrc=$("#pinbook img").attr("src");//当前图片的路径	
	if(imgSrc==""||typeof(imgSrc)=="undefined"){
	this.window.close();
	alert("对不起！此图片无法装订");
	return false;
   }
    if(GatherName=="null"){
        $("#notice").text("请添加图集再装订").css({left:($(window).width()-$("#notice").width())/2,top:($(window).scrollTop()+$(window).height()-$("#notice").height())/2}).fadeIn(500).delay(3000).fadeOut(500);
        return false;
    }
    $.ajax({
        type:"get",
        url:"/user/outPin.aspx",
        data:"GatherName="+escape(GatherName)+"&discription="+escape(discription)+"&src="+imgSrc+"&url="+urlForm+"&ran="+Math.random(),
        success:function (result){
            var vArr=result.split("|");
            if(vArr[0]=="添加成功"){
                 window.location = "/user/success.aspx?src="+imgSrc+"&dingFormIid="+vArr[1];
            }
           
        }
    });
}


