function Core_QuickPost_Init(context) {
    $('#quick-post-panel').hide();
    $('#quick-post-cancel-post', $('#quick-post-panel')).unbind("click").click(function(e) { Core_QuickPost_Cancel(context, this); e.preventDefault(); });
    $('#quick-post-add-post').unbind("click").click(function(e) { Core_QuickPost_Publish(context, this); e.preventDefault(); });
    $('#quick_post_link').unbind("click").click(function() {
        $('#quick-post-panel').slideToggle("normal");
    });
    $('#quick-post-title').addClass("empty").val(context.parameter.titleHelp);
    $('#quick-post-body').addClass("empty").val(context.parameter.bodyHelp);
    Core_QuickPost_Refresh(context);

    $(document).bind('customizepage', function() { $('#quick-post-toggle').hide(); });
}

function Core_QuickPost_Refresh(context) {

    var form = $('#' + context.parameter.formWrapperId);
    var groupName = $('.attribute-item.selected-group .attribute-value', form);
    var groupLabel = $('.attribute-item.selected-group .attribute-name', form);
    var appName = $('.attribute-item.selected-app .attribute-value', form);
    var appLabel = $('.attribute-item.selected-app .attribute-name', form);
    var postToLink = $('#' + context.parameter.postToLinkId, form);
    var attachLink = $('.internal-link.add-attachment', form);
    
    if (context.parameter.groupName != "") {
        groupName.text(context.parameter.groupName);
        groupName.show();
        groupLabel.show();
        postToLink.addClass("enabled");

        if (context.parameter.sectionId > 0) {
            appName.text(context.parameter.sectionName);
            switch (context.parameter.applicationType) {
                case "weblog":
                    appLabel.text(context.parameter.blogApp + ":");
                    break;
                case "media-gallery":
                    appLabel.text(context.parameter.galleryApp + ":");
                    break;
                case "forum":
                    appLabel.text(context.parameter.forumApp + ":");
                    break;
                case "wiki":
                    appLabel.text(context.parameter.wikiApp + ":");
                    break;
                default:
                    appLabel.text("");
                    break;
            }
            appLabel.show();
            appName.show();
            $('#quick-post-form > div.error.message').hide();
            var removeLink = $('.internal-link.remove-attachment');
            var attachmentLabel = $('.field-item.post-file .quick-post-attachment-name');
            
            if (context.parameter.attachmentId.length > 0) {
                attachLink.html('<span></span>' + context.parameter.changeFile);
                attachmentLabel.text(context.parameter.attachmentName).show();
                removeLink.show();
            }
            else {
                attachLink.html('<span></span>' + context.parameter.attachFile);
                removeLink.hide();
                attachmentLabel.hide();
            }
            
        }
        else {
            appLabel.hide();
            appName.hide();
            $('.field-item.post-file').hide();
        }
    }
    else {
        groupLabel.hide();
        groupName.hide();
        postToLink.removeClass("enabled");
        appLabel.hide();
        appName.hide();
        $('.field-item.post-file').hide();
    }
    
}

function Core_QuickPost_GroupList_PopulatePopup(context) {

    var popupPanel = eval(context.parameter.groupPopupId);
    content = context.parameter.wrapperHtml.replace(/{Content}/g, context.parameter.loadingHtml);
    popupPanel.SetPanelContent(content);

    var listHtml = "";  // Core_QuickPost_GroupList_LoadFromCache(context, filter);

    $.ajax({
        type: "POST",
        url: Core_QuickPost_AjaxEndpoint + "/GetFavoriteGroups",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        dataType: "json",
        success: function(response) {
            var objs = response.d;
            var itemHtml;
            if (objs && objs.length > 0) {
                listHtml = "";
                $.each(objs, function() {
                    itemHtml = context.parameter.groupItemHtml.replace(/{GroupId}/g, this.GroupId).replace(/{Name}/g, this.Name.replace("'", "&#39;"));
                    listHtml += itemHtml;
                });
                listHtml = context.parameter.groupListHtml.replace(/{ListItems}/g, listHtml);
            }
            else {
                listHtml = context.parameter.noFavoritesHtml;
            }

            popupPanel.SetPanelContent(listHtml);
            // Core_QuickPost_GroupList_AddToCache(context, filter, listHtml);

        },
        error: function(xhr, desc, ex) {
            popupPanel.SetPanelContent(context.parameter.errorWrapperHtml.replace(/{Content}/g, context.parameter.groupListError));
        }
    });
}

function Core_QuickPost_GetAttachmentUrl(context) {
    // GetUploadUrl

    $('.field-item.post-file').hide();
    if (context.parameter.applicationType != "wiki") {
        // TODO: Cache results

        var message = '{"sectionId":"' + context.parameter.sectionId + '","applicationType":"' + context.parameter.applicationType + '"}';

        $.ajax({
            type: "POST",
            url: Core_QuickPost_AjaxEndpoint + "/GetUploadUrl",
            contentType: "application/json; charset=utf-8",
            data: message,
            dataType: "json",
            success: function(response) {
                var url = response.d;
                if (url.length > 0) {
                    var clickTarget = "Telligent_Modal.Open('" + url + "', 640, 180, Core_QuickPost_GetAttachmentData); return false;";
                    var attachmentLink = $('.internal-link.add-attachment');
                    attachmentLink.unbind("click");
                    attachmentLink.attr("onclick", "");
                    eval("attachmentLink.click(function(e) { " + clickTarget + " e.preventDefault(); })");
                    attachmentLink.attr("href", "#");
                    $('.field-item.post-file').show();
                }

            },
            error: function(xhr, desc, ex) {
                var msg = context.parameter.publishErr;
                var err = eval("(" + xhr.responseText + ")");

                if (err && err.Message)
                    msg += " " + err.Message;

                alert(msg);
            }
        });
    }
}

function Core_QuickPost_RemoveAttachment(context) {
    context.parameter.attachmentId = "";
    context.parameter.attachmentName = "";
    Core_QuickPost_Refresh(context);
}

function Core_QuickPost_PostTo_PopulatePopup(context) {
    var popupPanel = eval(context.parameter.postToPopupId);
    content = context.parameter.wrapperHtml.replace(/{Content}/g, context.parameter.loadingHtml);
    popupPanel.SetPanelContent(content);
    
    var listHtml = "";  // Core_QuickPost_PostTo_LoadFromCache(context, filter);
    
    var message = '{"groupId":"' + context.parameter.groupId + '"}';

    $.ajax({
        type: "POST",
        url: Core_QuickPost_AjaxEndpoint + "/GetAppsForPosting",
        contentType: "application/json; charset=utf-8",
        data: message,
        dataType: "json",
        success: function(response) {
            var objs = response.d;
            var appList;
            var content = "";
            if (objs && objs.length > 0) {
                $.each(objs, function() {
                    appList = "";
                    var app = this;
                    $.each(this.Sections, function() {
                        appList += context.parameter.postToItemHtml.replace(/{ApplicationType}/g, app.ApplicationType).replace(/{Name}/g, this.Name.replace("'", "&#39;")).replace(/{SectionId}/g, this.SectionId);
                    });
                    content += context.parameter.postToListHtml.replace(/{Name}/g, this.Name.replace("'", "&#39;")).replace(/{Applications}/g, appList);
                });
            }
            else {
                content = context.parameter.noResultsHtml;
            }

            popupPanel.SetPanelContent(content);
        },
        error: function(xhr, desc, ex) {
            popupPanel.SetPanelContent(context.parameter.errorWrapperHtml.replace(/{Content}/g, context.parameter.postToListErr));
        }
    });
}

function Core_QuickPost_GroupList_ShowPopup(context)
{
    var wrapper = $('#' + context.parameter.formWrapperId);
    $('#' + context.parameter.groupLinkId).addClass('active active__group-list active__internal-link active__group-list__internal-link');
    if (!context.parameter.popupPopulated)
        Core_QuickPost_GroupList_PopulatePopup(context);
    else
        $('.browse-groups-search-textbox', wrapper).focus();
}

function Core_QuickPost_GroupList_HidePopup(context)
{
    $('#' + context.parameter.groupLinkId).removeClass('active active__group-list active__internal-link active__group-list__internal-link');
}

function Core_QuickPost_GroupList_Select(context, groupId, e) {
    if (context.parameter.groupId != groupId) {
        context.parameter.groupId = groupId;
        context.parameter.sectionId = 0;
        context.parameter.sectionName = "";
        var groupLink = $(e);
        if (groupLink.hasClass('current'))
            context.parameter.groupName = context.parameter.currentGroupName;
        else
            context.parameter.groupName = groupLink.text().replace("&amp;", "&");
        Core_QuickPost_Refresh(context);
    }
}

function Core_QuickPost_PostTo_ShowPopup(context) {
    var wrapper = $('#' + context.parameter.formWrapperId);
    $('#' + context.parameter.postToLinkId, wrapper).addClass('active active__post-to active__internal-link active__internal-link__post-to');
    if (context.parameter.groupId > 0) {
        Core_QuickPost_PostTo_PopulatePopup(context);
    }
    else {
        var popupPanel = eval(context.parameter.postToPopupId);
        popupPanel.SetPanelContent(context.parameter.errorWrapperHtml.replace(/{Content}/g, context.parameter.noGroupErr));
    }
}

function Core_QuickPost_PostTo_HidePopup(context) {
    var wrapper = $('#' + context.parameter.formWrapperId);
    $('#' + context.parameter.postToLinkId, wrapper).removeClass('active active__post-to active__internal-link active__internal-link__post-to');
}

function Core_QuickPost_PostTo_Select(context, sectionId, applicationType, e) {
    context.parameter.sectionId = sectionId;
    context.parameter.sectionName = e.innerHTML.replace("&amp;", "&");
    context.parameter.applicationType = applicationType;

    Core_QuickPost_Refresh(context);
    Core_QuickPost_GetAttachmentUrl(context);
}

function Core_QuickPost_Cancel(context, e) {
    var form = $('#' + context.parameter.formWrapperId);
    form.slideUp("normal");
    $('#' + context.parameter.formTitleId).val("");
    $('#' + context.parameter.formBodyId).val("");
    $('#quick-post-form > div.error.message').hide();
    $('.field-item-validation').hide();
}

function Core_QuickPost_Publish(context, e) {
    var popupPanel = eval(context.parameter.postToPopupId);
    var subject = $.trim($('#' + context.parameter.formTitleId).val());
    var body = $.trim($('#' + context.parameter.formBodyId).val());
    var form = $('#' + context.parameter.formWrapperId);

    var fileName = "";
    if (context.parameter.attachmentName.length > 0)
        fileName = encodeURIComponent(context.parameter.attachmentName);

    $('#quick-post-form > div.error.message').hide();
    $('.field-item-validation').hide();

    var err = false;

    if (subject.length == 0 || subject == context.parameter.titleHelp) {
        $('.field-item.post-title .field-item-validation').css('display', 'block');
        err = true;
    }

    if (body.length == 0 || body == context.parameter.bodyHelp) {
        $('.field-item.post-body .field-item-validation').css('display', 'block');
        err = true;
    }

    if (context.parameter.sectionId <= 0) {
        $('#quick-post-form > div.error.message').text('* ' + context.parameter.noGroupAppErr).show();
        err = true;
    }

    if (context.parameter.applicationType == "media-gallery" && context.parameter.attachmentId == "") {
        $('.field-item.post-file .field-item-validation').show();
        err = true;
    }
    
    if (err)
        return;

    subject = encodeURIComponent(subject);
    body = encodeURIComponent(body);

    var pbutton = $(e);
    pbutton.unbind("click").click(function() { return false; });
    pbutton.html('<span></span>' + context.parameter.publishing);

    var message = '{"sectionId":"' + context.parameter.sectionId + '","applicationType":"' + context.parameter.applicationType + '","attachmentId":"' + context.parameter.attachmentId + '","attachmentFileName":"' + fileName + '","subject":"' + subject + '","body":"' + body + '"}';

    $.ajax({
        type: "POST",
        url: Core_QuickPost_AjaxEndpoint + "/Publish",
        contentType: "application/json; charset=utf-8",
        data: message,
        dataType: "json",
        success: function(response) {
            var url = response.d;
            if (url.length > 0)
                window.location = url;
            else {
                alert(context.parameter.postSaved);
                pbutton.html('<span></span>' + context.parameter.publish);
                $('#quick-post-add-post').unbind("click").click(function(e) { Core_QuickPost_Publish(context, this); e.preventDefault(); });
            }
        },
        error: function(xhr, desc, ex) {
            var msg = context.parameter.publishErr;
            var err = eval("(" + xhr.responseText + ")");

            if (err && err.Message)
                msg += " " + err.Message;

            alert(msg);

            pbutton.html('<span></span>' + context.parameter.publish);
            $('#quick-post-add-post').unbind("click").click(function(e) { Core_QuickPost_Publish(context, this); e.preventDefault(); });
        }
    });
}

function Core_QuickPost_TitleOnFocus(context, e) {
    var t = $(e);
    if (t.val() == context.parameter.titleHelp) {
        t.val("");
        t.removeClass("empty");
    }
}

function Core_QuickPost_TitleOnBlur(context, e) {
    var t = $(e);
    if ($.trim(t.val()) == "") {
        t.addClass("empty");
        t.val(context.parameter.titleHelp);
    }
}

function Core_QuickPost_BodyOnFocus(context, e) {
    var t = $(e);
    if (t.val() == context.parameter.bodyHelp) {
        t.val("");
        t.removeClass("empty");
    }
}

function Core_QuickPost_BodyOnBlur(context, e) {
    var t = $(e);
    if ($.trim(t.val()) == "") {
        t.addClass("empty");
        t.val(context.parameter.bodyHelp);
    }
}