﻿var forumService = applicationPath + 'Services/ForumService.asmx/';
var topics = {};
var forumList, topicList;
function onError(e) {
    alert('Eroare la comunicarea cu serverul');
}
function deleteForumImage(post, image, index) {
    if (confirm('Confirmaţi ştergerea acestei imagini ?')) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: forumService + 'DeleteImage',
            data: "{postId:" + post + ", image:'" + image + "'}",
            dataType: "json",
            success: function(model) {
                if (!model.d)
                    alert('Eroare la stergere');
                else {
                    $('#file-' + index).remove();
                }
            },
            error: onError
        });
    }
}
function loadTopicsInternal(forumId) {
    var model = topics[forumId];

    topicList.find('option').remove();
    for (var i = 0; i < model.length; i++)
        topicList.append('<option value="' + model[i].Id + '">' + safe(model[i].Name) + '</option>');

    if (model.length == 0)
        topicList.append('<option value="">[Nu exista subiecte]</option>');
}
function loadTopics() {
    var forumId = parseInt(forumList.val());
    if (topics[forumId])
        loadTopicsInternal(forumId);
    else {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: forumService + 'GetTopics',
            data: "{forumId:" + forumId + "}",
            dataType: "json",
            success: function(model) { topics[forumId] = model.d; loadTopicsInternal(forumId); },
            error: onError
        });
    }
}
function loadReply(postId) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: forumService + 'GetPostContent',
        data: "{postId:" + postId + "}",
        dataType: "json",
        success: function(model) { showAddPost('', model.d); },
        error: onError
    })
}
function showAddPost(subject, content) {
    if (!subject) subject = '';
    if (!content) content = '';

    $('#post-subject').val(subject);
    $('#post-content').val(content);

    $('#add-post-box').show();
    window.location.href = '#add-post-box';
}

function markSubjectRead(element, topicId) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: forumService + 'MarkSubjectRead',
        data: "{topicId:" + topicId + "}",
        dataType: "json",
        success: function(model) {
            $(element).parents('tr:first').removeClass('visit').addClass('visited');
        },
        error: onError
    })
}

$(document).ready(function() {
    forumList = $('#forum-list');
    topicList = $('#topic-list');
    forumList.change(loadTopics);
});


