﻿function InitRotator(isSubpage) {

    if (isSubpage) {
        $("#middle").addClass('subPage');
    }

    var imagesContainer = $('#rotatorImages');
    if (isSubpage) {
        imagesContainer.addClass("subPage");
    }

    var currentImageIndex = 0;

    imagesContainer.html('<span class="rotatorLoader"> </span>');

    if (imagesContainer.length != 0) {
        $.getJSON('/Home/Rotator/?isSubpage=' + isSubpage, null, function (data) {

            imagesContainer.empty();
            $.each(data.Categories, function (catIndex, catItem) {
                $('#categories ul').append('<li><a id="category' + catIndex + '">' + catItem.Name + '</a></li>');

                {
                    (function (idx) {
                        $('#category' + catIndex).bind("click", function () {
                            imagesContainer.cycle(idx);
                            return false;
                        });
                    })(currentImageIndex);
                }

                $.each(catItem.Items, function (index, item) {
                    imagesContainer.append('<div id="imgPreview' + catIndex + '_' + index + '" class="rotator" />');
                    var preview = $('#imgPreview' + catIndex + '_' + index);
                    var link = $('<a class="rotatorImg" href="' + item.Url + '"></a>');
                    link.append('<img src="' + item.Image + '" alt="' + item.Title + '" title="' + item.Title + '" />');
                    link.append('<div class="desc"><h3>' + item.Title + '</h3><p>' + item.Text + '</p></div>');
                    preview.append(link);
                    currentImageIndex++;
                });
            });

            if (isSubpage) {
                $("#rotatorRightBottom").show();
                $("#rotatorRightTop").show();
                $("#rotatorRightTop").addClass("subPage");
            }
            else {
                $("#rotatorLeftBottom").show();
                $("#rotatorRightBottom").show();
                $("#rotatorRightTop").show();
            }

            imagesContainer.cycle({
                fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
                prev: '#prev',
                next: '#next',
                timeout: 7000
            });

        });
    }
}

function InitTopTabs() {
    var actorsTab = $("#topActorsTab");
    var gamesTab = $("#topGamesTab");
    var topGames = $("#topGames");
    var topActors = $("#topActors");

    actorsTab.bind("click", function (e) {
        topActors.show();
        topGames.hide();

        actorsTab.parent().addClass("s1");
        actorsTab.parent().removeClass("s2");
        topActors.parent().addClass("s1");
        topActors.parent().removeClass("s2");

        gamesTab.addClass("h3s");
        gamesTab.removeClass("h3b");
        actorsTab.addClass("h3b");
        actorsTab.removeClass("h3s");
    });

    gamesTab.bind("click", function (e) {
        topActors.hide();
        topGames.show();

        gamesTab.parent().addClass("s2");
        gamesTab.parent().removeClass("s1");
        topGames.parent().addClass("s2");
        topGames.parent().removeClass("s1");

        gamesTab.addClass("h3b");
        gamesTab.removeClass("h3s");
        actorsTab.addClass("h3s");
        actorsTab.removeClass("h3b");
    });
}

function InitGameMediaTabs() {
    var actorsTab = $("#gameVideosTab");
    var gamesTab = $("#gameScreenshotsTab");
    var topGames = $("#gameScreenshots");
    var topActors = $("#gameVideos");

    actorsTab.bind("click", function (e) {
        topActors.show();
        topGames.hide();

        actorsTab.parent().addClass("s1");
        actorsTab.parent().removeClass("s2");
        topActors.parent().addClass("s1");
        topActors.parent().removeClass("s2");

        gamesTab.addClass("h3s");
        gamesTab.removeClass("h3b");
        actorsTab.addClass("h3b");
        actorsTab.removeClass("h3s");
    });

    gamesTab.bind("click", function (e) {
        topActors.hide();
        topGames.show();

        gamesTab.parent().addClass("s2");
        gamesTab.parent().removeClass("s1");
        topGames.parent().addClass("s2");
        topGames.parent().removeClass("s1");

        gamesTab.addClass("h3b");
        gamesTab.removeClass("h3s");
        actorsTab.addClass("h3s");
        actorsTab.removeClass("h3b");
    });
}

function GenerateUserDetailsAvatarHTML(userDetailsUrl, avatarFileName, userName) {
    return '<a href="' + userDetailsUrl + '"><img src="' + avatarFileName + '" alt="Avatar" title="' + userName + '" /></a>';
}

function GenerateCommentOptionsHTML(comment) {
    if (comment.Editable) {
        return '<li id="editButton' + comment.Id + '" class="cEdit"><a href="javascript://" onclick="EditComment(' + comment.Id + ', ' + comment.Type + ');">Edytuj</a></li>';
    }
    else {
        return '<li class="cEdit"><a href="javascript://" onclick="ReplyComment(\'' + comment.UserName + '\');">Odpowiedz</a></li>';
    }
}

function EditComment(id, type) {
    var commentHolder = $("#commentPH" + id);
    var text = commentHolder.text();
    commentHolder.replaceWith(CreateInlineCommentHTML(id, text));
    $("#inlineEdit" + id).data("type", type);
    $("#inlineEdit" + id).data("revert", text);
    $("#editButton" + id).hide();
}

function CreateInlineCommentHTML(id, text) {
    return '<textarea onkeyup = "LimitChars(\'inlineEdit' + id + '\', 1000, \'charLimitInline' + id + '\');" id="inlineEdit' + id + '" class="inlineComment">' + text + '</textarea><input id="saveBtn' + id + '" onclick="SaveInlineComment(\'' + id + '\');" type="button" value="Zapisz" class="inlineComment" /> <input id=cancelBtn' + id + ' type="button" value="Anuluj" onclick="CancelInlineComment(\'' + id + '\');" class="inlineComment" /><p id="charLimitInline' + id + '" class="inlineComment"></p>';
}

function CreateCommentParagraph(id, text) {
    return '<p id="commentPH' + id + '">' + text + '<span class="cBottom"></span></p>';
}

function CancelInlineComment(id) {
    var commentHolder = $("#inlineEdit" + id);
    commentHolder.replaceWith(CreateCommentParagraph(id, commentHolder.data('revert')));
    $("#cancelBtn" + id).remove();
    $("#saveBtn" + id).remove();
    $("#charLimitInline" + id).remove();
    $("#editButton" + id).show();
}

function SaveInlineComment(id) {
    var commentHolder = $("#inlineEdit" + id);
    var type = commentHolder.data("type");
    var text = commentHolder.val();

    $.ajax({
        type: "POST",
        url: "/Common/SaveComment",
        data: 'Text=' + encodeURIComponent(text) + '&Id=' + id + '&Type=' + type,
        dataType: "json",
        success: function (msg) {
            if (!msg.Status) {
                return alert(msg.Text);
            }
            commentHolder.replaceWith(CreateCommentParagraph(id, text));
            $("#cancelBtn" + id).remove();
            $("#saveBtn" + id).remove();
            $("#charLimitInline" + id).remove();
            $("#editButton" + id).show();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('Błąd. Nie można zapisać komentarza.');
        }
    });
}

function LoadComments(whereTo, url, loader, userDetailsUrlTemplate) {
    loader.show();
    $.getJSON(url, null, function (data) {
        loader.hide();
        if (data.length == 0) {
            $("#moreComments").hide();
        }

        $.each(data, function (index, comment) {
            var userDetailsUrl = userDetailsUrlTemplate.replace("userNamePH", comment.UserName);

            whereTo.append('<div class="comment"><div class="avatar">' +
                GenerateUserDetailsAvatarHTML(userDetailsUrl, comment.AvatarFileName, comment.UserName) +
                '<span class="avatarBorder"></span></div><div class="content"><ul class="cDetails"><li class="cAuthor"><a href="' +
                userDetailsUrl + '">' + comment.UserName + ' <small>(' + comment.Rank + ')</small></a>' +
                '</li><li class="cDate">' + comment.DateString + '</li>' + GenerateCommentOptionsHTML(comment) + '</ul>' +
                CreateCommentParagraph(comment.Id, comment.Text) + '</div></div>');
        });
        whereTo.data("startIndex", whereTo.data("startIndex") + data.length);
    });
}

function BindFavLink(favLinkElem, favResultElem, favUrl, successText) {
    favLinkElem.bind("click", function (e) {
        $.ajax({
            url: favUrl,
            success: function (res, status) {
                favResultElem.text(successText);
                favLinkElem.addClass("highlight");
                favLinkElem.unbind();
            },
            error: function (httpRequest, textStatus, errorThrown) {
                favResultElem.text("Błąd :(");
            }
        });
    });
}

function LoadCommentsAndBindMoreLink(commentsElement, loaderElement, moreCommentsTemplate, allCommentsTemplate, userDetailsUrlTemplate) {
    commentsElement.data("startIndex", 0);
    LoadComments(commentsElement, moreCommentsTemplate.replace("startIndex", commentsElement.data("startIndex")), loaderElement, userDetailsUrlTemplate);

    $("#moreCommentsLink").bind("click", function (e) {
        var moreCommentsUrl = moreCommentsTemplate.replace("startIndex", commentsElement.data("startIndex"));
        LoadComments(commentsElement, moreCommentsUrl, loaderElement, userDetailsUrlTemplate);
    })

    $("#allCommentsLink").bind("click", function (e) {
        var allCommentsUrl = allCommentsTemplate.replace("startIndex", commentsElement.data("startIndex"));
        LoadComments(commentsElement, allCommentsUrl, loaderElement, userDetailsUrlTemplate);
        $("#moreComments").hide();
    })
}

function BindVoteStars(starsElement, votingResultElement, voteUrlTemplate) {
    var voteUrl = '<%= Url.RouteUrl("Voting", new { id = Model.Id, score = scoreValue }) %>';
    starsElement.stars({
        cancelShow: false,
        oneVoteOnly: true,
        callback: function (ui, type, value) {
            var voteUrl = voteUrlTemplate.replace("scoreValue", value);
            $.ajax({
                url: voteUrl,
                success: function (res, status) {
                    votingResultElement.text("Dziękujemy za głos");
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    votingResultElement.text("Błąd :(");
                }
            });
        }
    });
}

function LimitChars(textid, limit, infodiv) {
    var text = $('#' + textid).val();
    var textlength = text.length;
    if (textlength > limit) {
        $('#' + infodiv).html('Maksymalna długość komentarza: ' + limit);
        $('#' + textid).val(text.substr(0, limit));
        return false;
    }
    else {
        $('#' + infodiv).html('Skomentuj: (Pozostało znaków: ' + (limit - textlength) + ')');
        return true;
    }
}

$(document).ready(function () {

    $("#menu-07").click(function () {
        showFeedbackForm();
    });
    $("#feedbackBackground").click(function () {
        hideFeedbackForm();
    });
    $("#cancelFeedback").click(function () {
        hideFeedbackForm();
    });
    $("#feedbackForm #submit").click(function (event) {
        event.preventDefault();
        sendFeedback();
        hideFeedbackForm();
    });
});

function showFeedbackForm() {
    $("#feedbackBackground").css({
        "opacity": "0.5"
    });
    setFeedbackFormPosition();

    $("#feedbackBackground").fadeIn("fast");
    $("#feedbackForm").fadeIn("fast");
}

function hideFeedbackForm() {
    $("#feedbackForm").fadeOut("fast");
    $("#feedbackBackground").fadeOut("fast");

    clearInputs();
}

function setFeedbackFormPosition() {
    var formWidth = $("#feedbackForm").width();
    var formHeight = $("#feedbackForm").height();
    var totalWidth = document.documentElement.clientWidth;
    var totalHeight = document.documentElement.clientHeight;

    var leftPosition = (totalWidth - formWidth) / 2;
    var topPosition = (totalHeight - formHeight) / 2;

    $("#feedbackForm").css({
        "position": "fixed",
        "left": leftPosition,
        "top": topPosition
    });
}

function sendFeedback() {
    var email = $("#feedbackForm #feedbackEmail").val();
    var message = $("#feedbackForm #feedbackMessage").val();

    $.post("/Home/SaveFeedback", { email: email, message: message });
}

function clearInputs() {
    $("#feedbackForm #feedbackEmail").attr("value", "");
    $("#feedbackForm #feedbackMessage").attr("value", "");
}

function noSpam(address, domain) {
    document.location = 'mailto:' + address + '@' + domain;
}

function ToggleSiblings(id, expanderId) {
    var siblings = $("." + id + " ~ ." + id);
    var expander = $("#" + expanderId);
    siblings.slideToggle('normal');

    if (expander.html() == '+') {
        expander.html("-");
    }
    else {
        expander.html("+");
    }
}

function ReplyComment(userName) {
    var comment = $("#comment");

    var windowPosTop = $(window).scrollTop();
    var commentPosTop = comment.offset().top;

    if (commentPosTop <= windowPosTop) {
        window.scrollTo(0, comment.offset().top);
    }

    comment.val("@" + userName + " - ").focus();
    comment.setCursorPosition(comment.val().length);
}

new function ($) {
    $.fn.setCursorPosition = function (pos) {
        if ($(this).get(0).setSelectionRange) {
            $(this).get(0).setSelectionRange(pos, pos);
        } else if ($(this).get(0).createTextRange) {
            var range = $(this).get(0).createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
} (jQuery);

function VoteContrib(contribId, vote) {
    $("#vote-icons-" + contribId).fadeOut(400, function () {
        $.post("/Contribs/VoteContrib", { id: contribId, vote: vote },
        function (data) {
            if (data.result != "OK") {
                alert(data.message);
            }
            else {
                $("#vote-container-" + contribId).html("<span class=\"no\">" + data.no + "</span><span>/</span><span class=\"yes\">" + data.yes + "</span");
            }
        });
    });
}

function SlideContribElement(caller) {
    $(caller).closest(".contrib-element").slideUp();
}

function WriteContribSuccess(caller) {
    $(caller).parent().html("OK");
}

function HandleContrib(contribId, action, caller, after) {
    var loader = $("#contribLoader" + contribId);
    loader.siblings().fadeOut(400);
    loader.show();
    $.post("/Contribs/" + action, { id: contribId },
        function (data) {
            if (data.result != "OK") {
                alert(data.message);
            }
            else {
                after(caller);
            }
            loader.hide();
        });
}

function ContribDetails(contribId) {
    $.post("/Contribs/VotersJson", { id: contribId },
        function (data) {
            if (data.result != "OK") {
                alert(data.message);
            }
            else {
                var html = "<div class=\"contrib-dialog\"><p>Liczba głosów: <span class=\"yes\">" + data.yes + "</span><span> / </span><span class=\"no\">" + data.no + "</span></p><ul>";
                $.each(data.message, function (index, value) {
                    html += "<li>" + value.VoteText + " - " + value.UserName + "</li>";
                });
                html += "</ul></div>";
                $(html).dialog(
                {
                    modal: true,
                    title: "Głosujący na wybraną kontrybucję:",
                    buttons: {
                        OK: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
        });
}
