/*
 * Каперайты vas3k.ru и все дела
 * Код не пиздить! Писал в 4 часа утра, спиздишь - себе дороже
 * 
 */

$(function () {
    // Это крутая менюшечка
    $(".button_normal").bind("mouseenter", function (e) {
        $(this).stop().animate({
            opacity: 0
        }, "middle");
    }).bind("mouseleave", function (e) {
        $(this).stop().animate({
            opacity: 1
        }, "middle");
    });

    // Менюшечка more на глагне
    $("#show_more").click(function () {
        $("#more div").toggle();
        return 0;
    });

    // А эта штука якобы должна правильно все расставить на главной
    var swap_next_position = false;
    $(".timeline_block").each(function (i) {
        if (swap_next_position) {
            // надо поменять местами
            if ($(this).hasClass("left")) {
                $(this).removeClass("left").addClass("right");
            } else {
                $(this).removeClass("right").addClass("left");
            }
        }

        // если левая справа
        if ($(this).hasClass("left") && $(this).position().left > 50) {
            $(this).removeClass("left").addClass("right");
            swap_next_position = !swap_next_position;
        }

        // если правая слева
        if ($(this).hasClass("right") && $(this).position().left < 300) {
            $(this).removeClass("right").addClass("left");
            swap_next_position = !swap_next_position;
        }
    });
    $(".timeline_pointer").show();

    function sendcomment() {
          $("#comment_loader").show('fast');
          if ($.trim($("#comm_form #email").val()) == "") {
                if ($.trim($("#comm_form #comment_text").val()) != "") {
                      if ($.trim($("#comm_form  #author").val()) != "") {
                            $.ajax({
                                url: '/comments/send/ajax',
                                type: 'POST',
                                dataType: 'json',
                                data: $("#comm_form").serialize(),
                                success: function(data) {
                                    $("#comment_loader").hide('fast');
                                    if (data["error"] == 0) {
                                        $("#comm_form #comment_text").val("");
                                        getcomments($.trim($("#comm_form  input[name=module]").val()),
                                                    $.trim($("#comm_form  input[name=module_id]").val()));
                                    } else {
                                        alert("Не отправлено пушо: " + data["msg"] + ", ебана!");                                        
                                    }
                                },
                                error: function (a, err, b) {
                                    $("#comment_loader").hide('fast');
                                    alert("Что-то наебнулось: " + err + " " + b + ", блять!");
                                }
                            });
                      } else {
                            $("#comments_error").text("Вы не назвали себя").show().fadeOut(4000);
                      }
                } else {
                    $("#comments_error").text("Вы не написали свой комментарий").show().fadeOut(4000);
                }
          } else {
                $("#comments_error").text("Вы заполнили поле «Вы — бот?». Пожалуйста, оставьте его пустым!").show().fadeOut(4000);
          }
          return false;
    }


    $("#comm_form").submit(function () {
        return sendcomment();    
    });

    $("#comm_form").keypress(function (e) {
        key = e.keyCode || e.which;
        if (e.ctrlKey && (key == 13)) {
            return sendcomment();
        }
    });

    $("#comment_info_icon").click(function () {
        $("#comment_info").toggle('slow');
    });
});

// Получение комментов
function getcomments(module, id) {
    $("#comment_loader").show();
    $.ajax({
        url: "/comments/get/" + module + "/" + id,
        type: 'POST',
        dataType: "json",
        success: function(data) {
            $("#comment_loader").hide('fast');
            if (data.error != 1) {
                // Подгружаем комменты
                var sect = $("section#comments");
                sect.html("");
                var os_img = "";
                $.each(data.comments, function(i, item) {
                    if (item.useragent) {
                        if (item.useragent.indexOf("Linux") + 1) {
                            os_img = ' <img src="/images/icons/linux.png" alt="Linux" title="Прыщеблядь" />';
                        } else if (item.useragent.indexOf("Mac OS") + 1) {
                            os_img = ' <img src="/images/icons/apple.png" alt="Mac OS" title="Макоеб" />';
                        } else if (item.useragent.indexOf("Windows") + 1) {
                            os_img = ' <img src="/images/icons/windows.png" alt="Windows" title="Хомяк" />';
                        }
                    }
                    sect.append(
                    '<div class="comment" id="comment' + item.id + '">' +
                        '<div class="header">' +
                          '<div class="author"><strong onclick="nick(\'' + item.author + '\');" style="cursor: pointer;">' + item.author + '</strong> — ' + item.created_at +
                              ' <a href="/comments/ip/' + item.ip + '/"><small>[' + item.ip + ']</small></a>' + os_img + '</div>' +
                          '<div class="id"><a href="#comment' + item.id + '">#</a></div>' +
                        '</div>' +
                        '<div class="text">' +
                            item.text +
                        '</div>' +
                    '</div>'
                              );
                });
            } else {
                $("#comment_loader").hide('fast');
                alert("Что-то наебнулось: " + data.msg + ", блять!");
            }
            //$("#comments_error").text(data.msg).show().fadeOut(4000);
            //if (data.error == 0) {
            //    // reload comments
            //    $("#comm_form #comment_text").val("");
            //}
        },
        error: function (a, err, b) {
           $("#comment_loader").hide('fast');
           alert("Что-то наебнулось: " + err + " " + b + ", блять!");
        }
    });
    return false;
}

function nl2p(text) {
    text = text.replace(/(\r\n|\r)/g, "\n");
    text = text.replace(/\n{3,}/g, "\n\n");
    return text.replace(/\n\n/g, "</p><p>");
}

function nick(nick) {
    $('#comment_text').val($('#comment_text').val() + "<b>" + nick + "</b>, ");
    $('#comment_text').focus();
}
