﻿$(document).ready(function () {
    //dialog for blog seker
    var dialogSeker = $("#divAddSeker").dialog({
        title: 'סקר הבלוג',
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 500
    });

    //define click event to open the dialog
    $("[id$='btnShowAddSeker']").click(function () {
        //append the dialog to the ASP.NET form (by default, it is seperated)
        $("#divAddSeker").parent().appendTo($("form:first"));
        $('#divAddSeker').dialog('open');

    });

    //dialog for blog freebox
    var dialogFreebox = $("#divAddFreebox").dialog({
        title: 'קוביה חופשית',
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 900
    });

    //define click event to open the dialog
    $("[id$='btnShowAddFreebox']").click(function () {
        //append the dialog to the ASP.NET form (by default, it is seperated)
        $("#divAddFreebox").parent().appendTo($("form:last"));
        $('#divAddFreebox').dialog('open');

        SwitchEditor();
        SwitchEditor();
    });

    //dialog for blog freebox
    var dialogSignature = $("#divSignature").dialog(
    {
        title: 'חתימה לפורומים',
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 700
    });

    //define click event to open the dialog
    $("[id$='btnSignature']").click(function () {
        $('#divSignature').dialog('open');
    });

    /* Blog Settings of user
    ---------------*/

    //dialog for blog settings
    $("#divBlogsSettingsDialog").dialog(
    {
        title: 'הגדרות צפייה בעדכונים',
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 300
    });

    //define click event to open the dialog
    $("#btnBlogsSettingsDialog").click(function () {
        $('#divBlogsSettingsDialog').dialog('open');

        //preset the values
        if ($("[id$='hdnUpdatesOrder']").val() != "") {
            $("#ddlUpdatesOrder").val($("[id$='hdnUpdatesOrder']").val());
        }
        if ($("[id$='hdnShowUpdatesTitle']").val() != "") {
            $("#ddlShowUpdatesTitle").val($("[id$='hdnShowUpdatesTitle']").val());
        }
    });

    //when the user update the blogs settings
    $("#btnUpdateBlogsSettings").click(function () {
        var order = $("#ddlUpdatesOrder").val();
        var showUpdates = $("#ddlShowUpdatesTitle").val();

        //Invoke AJAX method to update the blog settings
        AjaxWebService.UpdateBlogsSettings(divUpdate.LoginUser, order, showUpdates, UpdateBlogsSettings_Success);
    });

    function UpdateBlogsSettings_Success() {
        $('#divBlogsSettingsDialog').html("ההגדרות שלך עודכנו בהצלחה.");
        //close the dialog
        window.setTimeout(function () {
            $('#divBlogsSettingsDialog').dialog('close');
            window.location = 'Blog.aspx?id=' + divUpdate.BlogId;
        }, 3000);
    }

    /*------------------*/

    $(".deleteUpdate").click(function () {
        if (confirm("האם אתה בטוח שברצונך למחוק?")) {
            var blogId = divUpdate.BlogId;
            var updateId = $(this).attr("updateId");
            AjaxWebService.DeleteBlogUpdate(blogId, updateId, DeleteBlogUpdate_Success);
        }
    });

    function DeleteBlogUpdate_Success() {
        var blogId = divUpdate.BlogId;
        window.location = 'Blog.aspx?id=' + blogId;
    }

    $(".editUpdate").click(function () {
        var blogId = divUpdate.BlogId;
        var updateId = $(this).attr("updateId");
        window.location = "Add_Update.aspx?blog=" + blogId + "&edit=" + updateId;
    });

    var blogId;
    var updateId;

    //when the user select to show specific Update
    $("div[id*='divUpdateText']").click(function () {
        showUpdate($(this));
        window.location = "#updates";
    });

    //show the first update
    showUpdate($("div[id*='divUpdateText']:first"));

    function showUpdate(selectedUpdate) {
        blogId = divUpdate.BlogId;
        updateId = selectedUpdate.data("update-id");

        if (blogId) {
            //hide the main update div and show loading image
            $('#divUpdate').hide();
            $('#divUpdateLoading').show();

            SelectedUpdateDiv = selectedUpdate[0];

            //using AJAX show the update text and redirect to the location of the box
            hightlightUpdateItem();

            AjaxWebService.GetUpdateOfBlog(blogId, updateId, showUpdate_Success, ajaxError, selectedUpdate);
        }
    }

    function showUpdate_Success(result, button) {
        //hide the loading image and return the main update div
        $('#divUpdate').show();
        $('#divUpdateLoading').hide();

        $('#divUpdate').html(result);

        AjaxWebService.GetAllUpdateComments(blogId, updateId, showComments_Success, ajaxError);
    }

    function showComments_Success(result) {
        //hide the loading image and return the table div
        document.getElementById('divUpdateComments').style.display = '';
        document.getElementById('divUpdateCommentsLoading').style.display = 'none';

        var commentsTable = document.getElementById('divUpdateComments');
        var userId = document.getElementById('divUpdateComments').userId;

        //clear all the div in the comments div
        $("#divUpdateComments").empty();

        //loop through all the comments that returned in AJAX
        for (var i = 0; i < result.length; i++) {
            //add new div for each comment
            var commentDiv = $("<div class='commentDiv'>");

            var commentNumber = result[i][9];
            var commentNumberDiv = $("<div class='commentNumberDiv'>");
            commentNumberDiv.html(commentNumber);

            //if the user that wrote this comment is Admin - add class
            if (result[i][8] == true) {
                commentNumberDiv.addClass('commentNumberDiv_admin');
                commentNumberDiv.attr('title', 'תגובה של מנהל באתר');
            }
            //if the user that wrote this comment is the user that added this item - add class
            if (result[i][5] == currentUser) {
                commentNumberDiv.addClass('commentNumberDiv_creator');
                commentNumberDiv.attr('title', 'תגובה של המשתמש שהוסיף');
            }

            var commentDetailsDiv = $("<div class='commentDetailsDiv'>");

            var shortenTextDiv = $("<div class='commentDiv_shortText'>");
            shortenTextDiv.attr('commentNumber', commentNumber);

            //get the comment text
            var commentShortText = result[i][4];

            //check if the commentText is too long
            if (commentShortText.length > 76) {
                //cut the string to a short one and add a click event
                commentShortText = commentShortText.substring(0, 76) + '...';
                shortenTextDiv.addClass('commentDiv_shortText_clickable');

                shortenTextDiv.click(function () {
                    var commentNumber = $(this).attr('commentNumber');

                    $(".commentDiv_longText[commentNumber='" + commentNumber + "']").show();
                    $(this).hide();
                    $(this).parent().parent().find(".commentArrow").hide();

                    $(this).parent().parent().addClass('commentDivHighlight');
                });

                //add a long text div (with the full comment)
                var longTextDiv = $("<div class='commentDiv_longText'>");
                longTextDiv.attr('commentNumber', commentNumber);
                longTextDiv.html(result[i][10]);

                longTextDiv.click(function () {
                    var commentNumber = $(this).attr('commentNumber');

                    $(".commentDiv_shortText[commentNumber='" + commentNumber + "']").show();
                    $(this).hide();
                    $(this).parent().parent().find(".commentArrow").show();

                    $(this).parent().parent().removeClass('commentDivHighlight');
                });

                commentDetailsDiv.append(longTextDiv);
            }

            shortenTextDiv.html(commentShortText);

            var usernameDiv = $("<div class='commentDiv_username'>");
            usernameDiv.html('<a href="User.aspx?id=' + result[i][5] + '">' + result[i][7] + '</a>');

            var commentDateDiv = $("<div class='commentDiv_date'>");
            commentDateDiv.html(result[i][6]);

            commentDetailsDiv.append(shortenTextDiv);

            if (commentShortText.length > 76) {
                commentDetailsDiv.append("<div class='commentArrow'>");
            }

            commentDetailsDiv.append(usernameDiv);
            commentDetailsDiv.append(commentDateDiv);

            //add delete button for this comment
            if (enableDeleteButton == true) {
                var deleteButton = $("<div class='commentDelete'>");
                deleteButton.attr('commentId', result[i][1]);
                deleteButton.html('מחק');

                deleteButton.click(function () {
                    if (window.confirm('האם אתה בטוח?')) {
                        var commentId = $(this).attr('commentId');
                        AjaxWebService.DeleteUpdateComment(blogId, updateId, commentId, deleteUpdateComment_Success);
                    }
                });

                commentDetailsDiv.append(deleteButton);
            }

            commentDiv.append(commentNumberDiv);
            commentDiv.append(commentDetailsDiv);
            commentDiv.append($("<div class='clear'>"));

            $("#divUpdateComments").append(commentDiv);
            $("#divUpdateComments").append($("<div class='commentSeperator'>"));
        }

        //if there are no comments
        if (result.length == 0) {
            $("#divUpdateComments").append("<div style='text-align:center;padding-bottom:5px;'>לא קיימות תגובות. אתה מוזמן להוסיף את הראשונה.</div>");
        }
        else {
            $("#divCommentsTitle").html("תגובות (" + result.length + ")");
        }
    }

    function deleteUpdateComment_Success(result) {
        AjaxWebService.GetAllUpdateComments(blogId, updateId, showComments_Success, ajaxError);
    }

    $("#btnAddUpdateComment").click(function () {
        if (divUpdate.LoginUser == "0") {
            alert("יש להתחבר לאתר");
            return false;
        }

        //hide the main comment div and show loading image
        $('#divUpdateAddComment').hide();
        $('#divUpdateCommentsLoading').show();

        var text = $("textarea[id*='txtUpdateComment']").val();
        AjaxWebService.AddUpdateComment(blogId, updateId, text, divUpdate.LoginUser, false, addUpdateComment_Success);
    });

    function addUpdateComment_Success(result) {
        //hide the loading image and return the main comment div
        $('#divUpdateAddComment').show();
        $('#divUpdateCommentsLoading').hide();

        //clear the comment text
        $("textarea[id*='txtUpdateComment']").val("");

        AjaxWebService.GetAllUpdateComments(blogId, updateId, showComments_Success, ajaxError);
    }
});
