﻿$(document).ready(function() {
    var note_form = $("#note_form");
    var post_note = $("#post_note");
    var note_url = $("#note_url");
    var note_words = $("#note_words");
    var note_format = $("#note_format");
    
    var main_notes = $("#main_notes");
    var note_one = $(".note_one");
    var delnote = $(".delnote");
    var favorite = $(".favorite");
    var nofavorite = $(".nofavorite");
    var repost = $(".repost");
    var comment = $(".comment");
    var close_comment = $(".close_comment");
    
    var pagination = $("#pagination");
    
    note_url.focus();
    post_note.attr("disabled", true);
    $("abbr.timeago").timeago();

    var time;
    var limit_str = 140;
    note_url.focus(function() {
        time = window.setInterval(substring, 100);
    });
    note_url.blur(function() {
        window.clearInterval(time);
        substring();
    });
    function substring() {
        var val = note_url.val();
        var length = val.length;
        if (length > limit_str) {
            post_note.attr("disabled", true);
        } else if (length <= 0) {
            post_note.attr("disabled", true);
        } else {
            post_note.attr("disabled", false);
        }
        if (note_words.html() != (limit_str - length)) {
            //跳出循环
            note_words.html(limit_str - length);
        }
    }

    $(".operate").ajaxSend(function(e, xhr, settings){
        //alert(settings.url);
        base64user = $("#base64user").val();;
        xhr.setRequestHeader('Authorization', "Basic " + base64user);
    });
    post_note.click(function() {
        if ($.trim(note_url.val()) == "") {
            $("<span style='color:#fc0284;font-weight:700;margin-left:20px'>请输入信息<span>").appendTo(note_format).fadeOut(3000);
        } else {
            $(this).addClass("ajax");
            var url = "/ajax/insertnote";
            var params = note_form.serialize();
            $.ajax({
                url: url,
                type: 'post',
                async: false,
                data: params,
                dataType: 'json',
                //global: false,
                success: function(data) {
                    post_note.removeClass("ajax");
                    if (data.error == 'error_format') {
                        $("<span style='color:#fc0284;font-weight:700;margin-left:20px'>消息格式输入错误<span>").appendTo(note_format).fadeOut(3000);
                    } else {
                        var $note = main_notes.children('.selfnofav').clone(true).removeClass("selfnofav");
                        
                        $note.find(".head").children("img").attr("src", data.user.profile_image_url).end().end()
                        .find(".url").children("a").attr("href", data.short_url_string).attr("title", data.url_string).text(data.short_url_string).end().end()
                        .find(".uname").children("a").attr("href", data.user.username).text(data.user.username).end().end()
                        .find(".com").html(data.text).end()
                        .find(".timeago").attr("title", data.create_time).text(jQuery.timeago(data.create_time)).end()
                        .find("#noteid").attr("value", data.id).end()
                        .removeClass("hide")
                        .prependTo(main_notes);
                        note_url.val("");
                    }
                },
                error: function(error) {
                    var errorTxt = error.responseText;
                    if (errorTxt == "ERROR_FORMAT") {
                        $("<span style='color:#fc0284;font-weight:700;margin-left:20px'>消息格式输入错误<span>").appendTo(note_format).fadeOut(3000);
                    } else if (errorTxt == "ERROR_DB") {
                        $("<span style='color:#fc0284;font-weight:700;margin-left:20px'>网站繁忙,请稍后<span>").appendTo(note_format).fadeOut(3000);
                    }
                }
            });
        }

    });

    delnote.click(function() {
        $this = $(this);
        var noteid = $this.siblings("#noteid").val();
        var url = '/api/notes/destroy.json';
        var params = "id=" + noteid;
        var parent = $this.parent().parent().parent();

        $.ajax({
            url: url,
            data: params,
            async: false,
            type: 'post',
            dataType: 'json',
            beforeSend: function(req) {
                $this.parent().append("<span class='ajax' style='width:15px;height:15px;display:block'> </span>");
            },
            success: function(data, textStatue) {
                switch(textStatue) {
                    case "notmodified":
                        alert("notmodified");
                    break;
                    case "success":
                    default:
                        parent.remove();
                    break;
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                if(textStatus == "error") {
                    alert("error");
                }
                $this.siblings(".ajax").remove();
            },
            error: function(error) {
                $this.siblings(".ajax").remove();
            }
        });

    });


    favorite.live('click', function(){
        $this = $(this);
        var url = "/api/favorites/destroy.json";
        var params = "id=" + $this.siblings("#noteid").val();
        $.ajax({
            url: url,
            type: 'post',
            async: false,
            data: params,
            dataType: 'json',
            beforeSend: function(XMLHttpRequest){
                $this.parent().append("<span class='ajax' style='width:15px;height:15px;display:block'> </span>");
            },
            success: function(data, textStatus) {
                //alert(textStatus);
                switch(textStatus) {
                    case "notmodified":
                        alert("notmodified");
                    break;
                    case "success":
                    default :
                        $this.removeClass("favorite").addClass("nofavorite");
                    break;
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                if(textStatus == "error") {
                    alert("error");
                }
                $this.siblings(".ajax").remove();
            },
            error: function(error) {

            }

        });
    });

    //收藏

    nofavorite.live('click', function(){
        $this = $(this);
        var url = "/api/favorites/create.json";
        var params = "id=" + $this.siblings("#noteid").val();
        $.ajax({
            url: url,
            type: 'post',
            async: false,
            data: params,
            dataType: 'json',
            beforeSend: function(XMLHttpRequest){
                $this.parent().append("<span class='ajax' style='width:15px;height:15px;display:block'> </span>");
            },
            success: function(data, textStatus) {
                switch(textStatus) {
                    case "notmodified":
                        alert("notmodified");
                    break;
                    case "success":
                        $this.removeClass("nofavorite").addClass("favorite");
                    break;
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                if(textStatus == "error") {
                    //alert("error");
                }
                $this.siblings(".ajax").remove();
            },
            error: function(error) {
                
            }
        });

    });
    
    repost.click(function(){
        $(this).parent().siblings('.comment').toggle();
    });
    
    note_one.hover( 
        function() {
            $(this).find(".operate").css("visibility", "visible");
        },
        function() {
            $(this).find(".operate").css("visibility", "hidden");
        }
    );

    pagination.click(function() {
        $this = $(this);
        var max_id = $this.siblings("#max_id");
        var params = "max_id=" + max_id.text();
        
        var uid = note_form.children("#uid").val();
        var url = "/api/notes/home_timeline.json";
        $.ajax({
            url: url,
            type: 'get',
            async: true,
            data: params,
            dataType: 'json',
            ifModified: true,
            beforeSend : function(XMLHttpRequest) {
                $this.append("<span class='ajax' style='position : absolute;right : 10px;'>　　</span>");
            },
            success: function(data, textStatus) {
                switch(textStatus) {
                    case "notmodified":
                        $this.html("You are arrived the end of internet");
                    break;
                    case "success":
                    default :
                       for (var i = 0; i < data.length; i++) {
                           if (data[i].user.id == uid) {
                               if (data[i].favorite == 1) {
                                   var $note = main_notes.children('.selffav').clone(true).removeClass("selffav");
                               } else {
                                   var $note = main_notes.children('.selfnofav').clone(true).removeClass("selfnofav");
                               }
                           } else {
                               if (data[i].favorite == 1) {
                                   var $note = main_notes.children('.otherfav').clone(true).removeClass("otherfav");
                               } else {
                                   var $note = main_notes.children('.othernofav').clone(true).removeClass("othernofav");
                               }
                           }
                           $note.find(".head").children("img").attr("src", data[i].user.profile_image_url).end().end()
                           .find(".url").children("a").attr("href", data[i].short_url_string).attr("title", data[i].url_string).text(data[i].short_url_string).end().end()
                           .find(".uname").children("a").attr("href", data[i].user.username).text(data[i].user.username).end().end()
                           .find(".com").html(data[i].text).end()
                           .find(".timeago").attr("title", data[i].create_time).text(jQuery.timeago(data[i].create_time)).end()
                           .find("#noteid").attr("value", data[i].id).end()
                           .removeClass("hide")
                           .appendTo(main_notes);
                       }
                       max_id.html(data[data.length - 1].id);
                    break;
                    
                }
            },        
            complete: function(XMLHttpRequest, textStatus) {
                $this.children(".ajax").remove();
            },
            error: function() {
                //$this.children("span").removeClass("ajax");
            }
        });

    });

    $(".comment_do").click(function(){
        $this = $(this);
        var url = "/ajax/comment";
        var params = "noteid=" + $this.siblings("#noteid").val() + "&comment=" + $this.siblings("#note_url_repost").val();
        $.ajax({
            url: url,
            type: 'post',
            async: false,
            data: params,
            dataType: 'json',
            beforeSend: function(XMLHttpRequest){
                $this.prepend("<span class='ajax' style='width:15px;height:15px;display:block'> </span>");
            },
            success: function(data, textStatus) {
                switch(textStatus) {
                    case "notmodified":
                        alert("notmodified");
                    break;
                    case "success":
                        var commet_num = $this.parent().parent().siblings(".note_time").children(".repost");
                        commet_num.html(Number(commet_num.html())+1);
                        var newcomment = "<li style='min-height:20px;border-bottom:1px dotted;'>"
                            +"<a href=''><img src='" + data.user.profile_image_url +"' class='small_head l'/></a>"
                            +"<div style='color:#8692A2;font-size:12px;font-weight:normal;margin-left:38px;'>"
                            +"<span>" + data.user.name + ":</span>"
                            +"<span>" + data.text + "</span>"
                            +"<abbr class='font_gray timeago' title='" + data.create_time + "' style='font-size:9pt;'>" + jQuery.timeago(data.create_time) +"</abbr>"
                            +"</div>"
                            +"</li>";
                        $this.parent().siblings('ul').prepend(newcomment);
                    break;
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                if(textStatus == "error") {
                    //alert("error");
                }
                $this.siblings("#note_url_repost").val("");
                $this.siblings(".ajax").remove();
            },
            error: function(error) {
                
            }
        });
    });
    $(".foll").hover(
        function () {
            $(this).children("i").css("background-position", "-176px -32px");
        },
        function () {
            $(this).children("i").css("background-position", "");
        }
    );
    $(".foll").live("click",function(){
        $this = $(this);
        var url = "/ajax/follow";
        var params = "userid=" + $this.siblings("#userid").val();
        $.ajax({
            url:url,
            type:'post',
            async: false,
            data: params,
            //dataType:'json',
            success:function(data){
                if (data == "SUCCESS") {
                    $this.before("<span style='margin-right:20px;'><i class='is_following'></i>关注中</span>");
                    $this.children("span").html("取消");
                    $this.removeClass("foll").addClass("unfoll");
                } else {
                }
            },
            error: function(error) {
            }

        });
    });
    $(".unfoll").hover(
      function () {
          $(this).children("i").css("background-position", "-208px -32px");
      },
      function () {
          $(this).children("i").css("background-position", "");
      }
    );
    $(".unfoll").live("click",function(){
        $this = $(this);
        var url = "/ajax/unfollow";
        var params = "userid=" + $this.siblings("#userid").val();
        $.ajax({
            url:url,
            type:'post',
            async: false,
            data: params,
            //dataType:'json',
            success:function(data){
                if (data == "SUCCESS") {
                    //$this.parent().parent().hide();
                    $this.prev().hide();
                    $this.children("span").html("关注");
                    $this.removeClass("unfoll").addClass("foll");
                } else {
                }
            },
            error: function(error) {
            }

        }); 
    });

    $(".w_close").click(function(){
       $(this).parent().parent().toggle(); 
    });

    
    $(".replyto").hover(
    function(){
        var replay_content = $(this).siblings(".reply_content");
        var position = $(this).position();
        var height = $(this).height();
        var replay_content_height = position.top + height + 2;
        replay_content.css("left",position.left);
        replay_content.css("top", replay_content_height);
        replay_content.show();
    },function(){
        var replay_content = $(this).siblings(".reply_content");
        replay_content.hide();
    });
    
    $(".url a").click(function(){
        $this = $(this);
        var url_win = $this.parent().siblings(".url_window");
        url_win.show();
        url_win.children('iframe').attr("src", $this.attr('href'));
        return false;
        
    });
});
