﻿function InitRotator(isSubpage) {

    if (isSubpage) {
        $("#middle").addClass('subPage');
    }

    var imagesContainer = $('#rotatorImages');
    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);
                    preview.append('<img src="' + item.Image + '" alt="' + item.Title + '" title="' + item.Title + '" />');
                    preview.append('<div class="desc"><h3><a href="' + item.Url + '">' + item.Title + '</a></h3><p>' + item.Text + '</p></div>');
                    currentImageIndex++;
                });

            });

            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 GenerateUserEditCommentHTML(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 '';
    }
}

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=' + 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) {
            $("#moreCommentsLink").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>' + GenerateUserEditCommentHTML(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, 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);
    })
}

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("+");
    }
}