﻿/*---------STYLING------------*/
$(document).ready(function () {
    $("ul.ForumMessages li").mouseenter(function () {
        $(this).css('background', '#eaeaea');
    }).mouseleave(function () {
        $(this).css('background', '#f5f5f5');
    });


    var InitialSearchText = $("#tbSearch").val();
    $("#tbSearch").click(function () {
        if ($(this).val() == InitialSearchText)
            $(this).val("").css("color", "black");
    }).blur(function(){
        if ($(this).val() == "")
            $(this).val(InitialSearchText).css("color", "#aaa");
    });
});
/*---------STYLING------------*/


/*-------LIVE CLOCK + SEARCH STYLING-------------------*/
var TooSmallMes = "Для пошуку необхідно набрати щонайменше 3 символи!";
$(document).ready(function () {
    ClockTick();
    $('#tbSearch').keypress(function (e) {
        if (e.which == 13) {
            if ($(this).val().length < 3) {
                window.alert(TooSmallMes);
                return false;
            }
            else {
                $(this).blur();
                $('#lbSearch').focus();
                eval($('#lbSearch')[0].href);
            }
        }
    });
    $('#lbSearch').click(function () {
        if ($('#tbSearch').val().length < 3) {
            window.alert(TooSmallMes);
            return false;
        }
    });
});
function ClockTick() {
    var ClientDate = new Date()
    var hrs = ClientDate.getHours() - hrsDif;
    var min = ClientDate.getMinutes() - minDif;
    if (min > 60) {
        min = min - 60;
        hrs = hrs + 1;
    }
    min = FixSingleDigit(min);

    $('.LiveClock span').each(function () {
        var attr = $(this).attr('id');
        var sec = ClientDate.getSeconds();
        if (attr == "|") {
            $(this).html(sec);
            return;
        }
        if (attr.indexOf('|') != -1) {
            sec = ":" + sec;
        }
        else {
            sec = "";
        }
        $(this).html(FixHours(parseInt(attr.replace('|', '')) + hrs) + ":" + min + sec);
    });

    setTimeout("ClockTick()", 1000);
}
function FixHours(x) {
    if (x > 23)
        x = x - 24;

    return FixSingleDigit(x);
}
function FixSingleDigit(x) {
    if (x <= 9) {
        return "0" + x;
    }
    return x;
}
/*-------LIVE CLOCK-------------------*/


/*-------ITEM ACTIONS-------------------*/
var Universe = {};
var uAn = '<a class="author" id="' + uID + '" href="' + ap + "/клуб/" + uID + "/" + uLn + '">' + uLn + '</a>';
var InitialCommentValue;
var InitialCommentHeight;
var tbFocused = false;
$(document).ready(function () {

    $('#ii #VoteUp').click(function () { Vote(true) });
    $('#ii #VoteDown').click(function () { Vote(false) });

    InitializeCommentsHighight();
    $("#ii #aBookmark").click(function () {
        if (!uIn) {
            alert("Щоб додавати закладки залогіньтесь!");
            return;
        }
        $.ajax({
            type: "POST",
            url: cs + "SwitchItemFav",
            data: '{ItemID: ' + iID + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (msg) { AjaxFailed(msg); }

        });
        if ($(this).is('.On')) {
            $(this).removeClass("On").attr("title", "Додати закладку");

            alert("Закладку видалено.");
        } else {
            $(this).addClass("On").attr("title", "Видалити закладку");
            alert("Закладку додано. Ви можете редагувати закладки зі сторінки Ваших налаштувань.");
        }


    });

    $("#addCmt").click(function (event) {
        event.preventDefault();
        $(this).hide(200);
        var Text = $('#tbComment').val().replace(/"/g, '\\"');
        //var test = "absdefa";
        //test = test.replace("a", "b");
        $.ajax({
            type: "POST",
            url: cs + "AddItemComment",
            data: '{ItemID: ' + iID + ', CommentText: "' + Text + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) { CommentAdded(msg.d); },
            error: function (msg) { AjaxFailed(msg); }

        })

    });

    var TranslitLoaded = false;
    $('#cmtTranslit').click(function () {
        if ($(this).is(':checked')) {
            if (!TranslitLoaded) {
                $.getScript(ap + '/App_Content/ClientScripts/Translit.js', function () {
                    Transliterator.instance = new Transliterator(document.getElementById('tbComment')).enable();
                    TranslitLoaded = true;
                });
            } else {
                if (Transliterator.instance)
                    Transliterator.instance.enable();
                else
                    Transliterator.instance = new Transliterator(document.getElementById('tbComment')).enable();
            }
        }
        else {
            Transliterator.instance.disable();
        }
        $('#tbComment').focus();
    });

    if (uIn) {
        InitialCommentValue = $('#tbComment').val();
        InitialCommentHeight = $('#tbComment').height();
        $('#tbComment').focus(function () {
            tbFocused = true;
            EnsureTbReadyToType();
        }).blur(function () {
            tbFocused = false;
        }).keyup(function () {
            if (typeof tbLimitChars === 'undefined' || !tbLimitChars) {
                limitChars('tbComment', 'comment-info', 500);
            }
            else {
                limitChars('tbComment', 'comment-info', tbLimitChars);
            }
            resizeTextarea($(this));
        });
        $('#cnlCmt').click(function (event) {
            event.preventDefault();
            EnsureTbInInitialState();
        });
    } else {
        $('#Comment').mouseenter(function () {
            $('#comment-login').fadeIn(100);
            $(this).height($(this).height() - 40);
        }).mouseleave(function () {
            $('#comment-login').fadeOut(100);
        });
    }

    $('#CommentsHolder').mouseenter(function () {
        //$('#CommentVote').fadeIn(100);
    }).mouseleave(function () {
        $('#CommentVote').fadeOut(200);
        $('ul.comments li').removeClass('CommentOver');
        $('ul.TopicComments li').removeClass('CommentOver');
    });

    $('#CommentsPager a').each(function () {
        $(this).click(function (event) {
            event.preventDefault();
            ShowCommentsPage($(this).attr('id').replace("ID", ""));
            $('#CommentsPager a').removeClass("selected");
            $('#CommentsPager #' + $(this).attr('id')).addClass("selected");

        });
    });

    if (window.location.toString().indexOf('#Відповісти') != -1) {
        EnsureTbReadyToType();
    }
});

function ItemStatusSwitchSuccess(msg) {
    var color = "#ccc";
    
    if (msg == "Deleted") {
        color = "#a00";
        $("#aDeleteItem").hide();
        $("#aActivateItem").show();
    }
    else if (msg == "Suggested") {
        color = "#00a";
        $("#aDeleteItem").hide();
        $("#aActivateItem").show();
    }
    else if (msg == "Active")
    {
        $("#aDeleteItem").show();
        $("#aActivateItem").hide();
    }

    $("#ii").css("border-left", "2px solid " + color);
}

function SwitchItemStatus(Status) {
    $.ajax({
        type: "POST",
        url: cs + "SwitchItemStatus",
        data: '{ItemID: ' + iID + ', Status: "' + Status + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) { ItemStatusSwitchSuccess(msg.d); },
        error: function (msg) { AjaxFailed(msg); }

    });
}

function EnsureTbInInitialState()
{
    $('#tbComment').val(InitialCommentValue).removeClass('readyToType').css('color', '#777');
    $('#tbComment').height(InitialCommentHeight);
    $('#buttons').add('#ctrlPnl').add('#author').add('#emotions').hide(100);
}

function EnsureTbReadyToType() {

    tb = $('#tbComment');
    if (!tbFocused) {
        tb.focus();
        tbFocused = true;
    }
    tb.addClass('readyToType').css('color', 'black');
    if (tb.height() == InitialCommentHeight) {
        tb.height(150);
    }
    if (tb.val() == InitialCommentValue) {
        tb.val("");
    }

    $('#author').show(100).html(uLn + '<br /><span></span>');
    $("#buttons").add("#addCmt").add("#emotions").add("#ctrlPnl").show(100);

    scrollToTb();
}

function Vote(Up) {
    if ($("#dvContrib .MemberLink").attr("id") == uID) {
        window.alert("Рекомендувати додану вами ж річ не дозволяється.");
        return;
    }
    $.ajax({
        type: "POST",
        url: cs + "VoteItem",
        data: '{ItemID: ' + iID + ', Up: ' + Up + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) { ItemVoteSuccess(msg.d, Up); },
        error: function (msg) { AjaxFailed(msg); }
    });

}

function ItemVoteSuccess(Success, Up) {
    if (Success) {
        //alert("Голос прийнято!");

        if (Up) {
            $('#VoteUpNum').html(parseInt($("#VoteUpNum").html()) + 1);
        } else {
            $('#VoteDownNum').html(parseInt($("#VoteDownNum").html()) + 1)
        }

    }
    else {
        alert("Ви вже надавали рекомендацію!");
    }
}


function ShowWinPopup(url) {
    pw = window.open(url, null, 'height=200,width=400,status=no,toolbar=no,menubar=no,location=no,top=265,left=360');
    pw.creator = self;
}

function resizeTextarea(textarea) {
    var defaultHeight = 150;
    var lines = textarea.val().split("\n");
    var count = lines.length;
    $.each(lines, function () {
        count += parseInt(this.length / 70);
    });
    var currHeight = textarea.height();
    var rows = parseInt(currHeight / 16) - 1;

    if (count > rows && currHeight < 600) { // Increase height unless 600 or higher
        textarea.css("height", (currHeight + (defaultHeight / 3)));
        scrollToTb();
    }
    else if (((count + 7) <= rows) && (currHeight > defaultHeight) && (count > 5)) { // Decrease height
        textarea.css("height", (currHeight - (defaultHeight / 2)));
        scrollToTb();
    }
    else if ((count <= rows) && (count <= 5)) { // If less than 5 rows, use default height
        textarea.css("height", defaultHeight);
    }
}
function limitChars(textid, infodiv, tbLimitChars) {

    var text = $('#' + textid).val();
    var textlength = text.length;
    if (textlength > tbLimitChars) {
        //$('#' + infodiv).html('You cannot write more then ' + limit + ' characters!');
        window.alert("Одне повідомлення не може містити більше ніж " + tbLimitChars + "символів");
        $('#' + textid).val(text.substr(0, tbLimitChars));
        return false;
    }
    else {
        $('#' + infodiv).html('Ще можна набрати: ' + (tbLimitChars - textlength));
        return true;
    }
}
function scrollToTb() {
    $('html, body').animate({
        scrollTop: $("#Comment").offset().top
    }, 0);//opera problem 2000
}

function CommentAdded(FormattedMessage) {
    $("#Comment").hide(100);
    EnsureTbInInitialState();
    $(".TopicComment #Comment").show(300);
    $(".commentsTitle").css("border", "none").css("margin-bottom", "-25px");
    var cmtCount = parseInt($('#CommentsNum').html()) + 1;
    $("#CommentsCount").html(cmtCount);
    $("#CommentsNum").html(cmtCount);
    var cmt = '<li><div class="metadata">'+ uAn + '<span class="date">Щойно</span></div><div class="votes"></div><div class="text">' + FormattedMessage + '</div><div style="clear:both"></div></li>';
    if (cmtCount == 1) {
        $("ul.comments").html(cmt);
    }
    else {
        $("ul.comments li").first().before(cmt);
    }

    $("ul.TopicComments li").last().after('<li><div class="header"><div class="date">' + $('.TopicComment .LiveClock').html() + '</div></div><div class="metadata">' + uAn + '<div class="registrationDate">З нами від:' + uAD + '</div></div><div class="votes"></div><div class="text">' + FormattedMessage + '</div><div style="clear:both"></div></li>');
    InitializeCommentsHighight();
}

function InitializeCommentsHighight() {
    $(".VotedUp").add(".VotedDown").each(function () {
        if ($(this).html() == "0")
            $(this).hide();
    });

    $("ul.comments li").add("ul.TopicComments li").mouseenter(function () {

        if (Universe.previousItem) {
            Universe.previousItem.removeClass('CommentOver');
            Universe.previousItem = null;
        }
        $(this).addClass('CommentOver');
        Universe.previousItem = $(this);
        Universe.currentID = $(this).attr('id');

        var p = $(this).position();
        if (uID == 0 || uID != $(this).find("a.author").attr('id') || uRl == "A") {
            $('#CommentVote').css('left', p.left + $(this).width() - $('#CommentVote').width()).css('top', p.top+10).show();
        }
        else {
            $('#CommentVote').hide();
        }
    });
}
function AjaxFailed(msg) {
    alert(msg.d);
}


function SwitchCommentDeleteStatus(CommentID) {
    //window.alert(CommentID);
    $.ajax({
        type: "POST",
        url: cs + "SwitchCommentDeleteStatus",
        data: '{CommentID: ' + CommentID + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) { SwitchCommentDeleteStatusSuccess(msg.d, CommentID); },
        error: function (msg) { AjaxFailed(msg); }
    });
}
function SwitchCommentDeleteStatusSuccess(restored, CommentID) {
    //window.alert(CommentID);
    if (restored)
        $("li#" + CommentID).css("border", "1px solid #ccc");
    else
        $("li#" + CommentID).css("border", "1px solid #a00");
}
function VoteForComment(CommentID, Up) {
    if (!uIn) {
        alert("Щоб голосувати залогіньтесь!");
        return;
    }
    $.ajax({
        type: "POST",
        url: cs + "VoteComment",
        data: '{CommentID: ' + CommentID + ', Up: ' + Up + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) { VoteSuccess(msg.d, CommentID, Up); },
        error: function (msg) { AjaxFailed(msg); }
    });
}
function VoteSuccess(Success, CommentID, Up) {
    if (Success) {
        var scls = "";
        if (Up) {
            scls = "VotedUp";
        }
        else {
            scls = "VotedDown";
        }
        var vote = $("li#" + CommentID + " span." + scls);
        var num = parseInt(vote.html());
        vote.html(num + 1);
        vote.show(600);
    }
    else {
        alert("Ви вже голосували за цей коментар!");
    }
}
function ShowCommentsPage(pageNum) {
    $.ajax({
        type: "POST",
        url: cs + "GetItemComments",
        data: '{ItemID: ' + parseInt(iID) + ', PageNum: ' + pageNum + ', PageSize: 15}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (msg) { AjaxFailed(msg); },
        success: function (msg) {
            RenderComments(msg.d);
        }

    });
}
function RenderComments(msg) {
    var NewElements = "";
    for (var cmnt in msg) {

        NewElements = NewElements + '<li id="' + msg[cmnt].ID + '"><div class="metadata"><a class="author" id="' + msg[cmnt].AuthorID + '" href="' + ap + '/клуб/' + msg[cmnt].AuthorID + "/" + msg[cmnt].AuthorName + '">' + msg[cmnt].AuthorName + '</a><span class="date">' + msg[cmnt].FriendlyDate + '</span></div><div class="votes"><span class="VotedUp">' + msg[cmnt].VoteUp + '</span><span class="VotedDown">' + msg[cmnt].VoteDown + '</span></div><div class="text">' + msg[cmnt].Text + '</div><div style="clear:both"></div></li>';
    }
    $("ul.comments").html(NewElements);
    InitializeCommentsHighight();
}
function emn(tag) {
    EnsureTbReadyToType();
    $("#tbComment").insertAtCaret(tag);
    scrollToTb();
}
function txtw(tag) {
    EnsureTbReadyToType();
    $("#tbComment").insertRoundCaret(tag);
    scrollToTb();
}
$.fn.insertAtCaret = function (tagName) {
    return this.each(function () {
        if (document.selection) {
            //IE support
            this.focus();
            sel = document.selection.createRange();
            sel.text = tagName;
            this.focus();
        } else if (this.selectionStart || this.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = this.selectionStart;
            endPos = this.selectionEnd;
            scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + tagName + this.value.substring(endPos, this.value.length);
            this.focus();
            this.selectionStart = startPos + tagName.length;
            this.selectionEnd = startPos + tagName.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += tagName;
            this.focus();
        }
    });
};
$.fn.insertRoundCaret = function (tagName) {
    return this.each(function () {
        strStart = '[' + tagName + ']';
        strEnd = '[/' + tagName + ']';
        if (document.selection) {
            //IE support
            stringBefore = this.value;
            this.focus();
            sel = document.selection.createRange();
            insertstring = sel.text;
            fullinsertstring = strStart + sel.text + strEnd;
            sel.text = fullinsertstring;
            document.selection.empty();
            this.focus();
            stringAfter = this.value;
            i = stringAfter.lastIndexOf(fullinsertstring);
            range = this.createTextRange();
            numlines = stringBefore.substring(0, i).split("\n").length;
            i = i + 3 - numlines + tagName.length;
            j = insertstring.length;
            range.move("character", i);
            range.moveEnd("character", j);
            range.select();
        } else if (this.selectionStart || this.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = this.selectionStart;
            endPos = this.selectionEnd;
            scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + strStart + this.value.substring(startPos, endPos) + strEnd + this.value.substring(endPos, this.value.length);
            this.focus();
            this.selectionStart = startPos + strStart.length;
            this.selectionEnd = endPos + strStart.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += strStart + strEnd;
            this.focus();
        }
    });
};
$(document).keydown(function (e) {
    if (e.keyCode == 37 && $('.previous').length > 0 && $('.previous')[0].href != undefined && !tbFocused) {
        if (($("#tbComment").val() != InitialCommentValue) && !confirm("Ви почали набирати текст повідомлення. Якщо ви перейдете на іншу сторінку текст втратиться. Продовжити?"))
            return;
        window.location.replace($('.previous')[0].href);
    }
    if (e.keyCode == 39 && $('.next').length > 0 && $('.next')[0].href != undefined && !tbFocused) {
        window.location.replace($('.next')[0].href);
    }
});
/*-------ITEM ACTIONS-------------------*/
