﻿/* Added for convenience */
function PostJson(controller, vm, resultDataType, callback) {
    if (!callback) {
        callback = function (html) { $("#window_" + vm.WindowGUID + " .widget-content").html(html); }
    }

    $.ajax({
        type: "POST",
        url: "/PortalApps/" + controller + "/" + vm.WindowGUID,
        dataType: resultDataType,
        data: $.toJSON(vm),
        contentType: "application/json; charset=utf-8",
        error: JQueryErrorHandler,
        success: callback
    });
}


function SavePortalAppSettings(windowGuid, isSubWindow) {
    $.ajax({
        type: "POST",
        url: $("#Form_" + windowGuid).attr("action"),
        data: $("#Form_" + windowGuid).serialize(),
        error: JQueryErrorHandler,
        success: function (vm) {
            if (vm) {
                if (vm.Message.Errors.length > 0) {
                    alert("Fout bij opslaan instellingen\n\n" + vm.Message.Errors.join("\n"));
                } else {
                    // Refresh settings
                    if (isSubWindow) {
                        $("#content_" + windowGuid).click();
                    } else {
                        $("#window_" + windowGuid + " .edit").trigger("click");
                        $("#window_" + windowGuid + " .edit").trigger("click");
                    }

                    // Refresh contents
                    UpdatePortalWindow({
                        windowGuid: windowGuid,
                        isSubWindow: isSubWindow,
                        contentExpiry: {
                            refreshInterval: -1
                        }
                    });
                }
            }
        }
    });
}


function DeletePortalSubWindow(subWindowGuid) {
    var parentWindow = $("#subwindow_" + subWindowGuid).parents(".widget");
    var parentWindowGuid = parentWindow.attr("id").replace("window_", "");
    var parentController = parentWindow.attr("controller");
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: "/PortalApps/" + parentController + "/" + parentWindowGuid + "/" + subWindowGuid + "/Delete",
        error: JQueryErrorHandler,
        success: function () {
            parent.UpdatePortalWindow({
                windowGuid: parentWindowGuid,
                contentExpiry: {
                    refreshInterval: -1
                }
            });
            parent.$.fn.colorbox.close();
        }
    });
}


function UpdatePortalWindow(opts) {
    if (!opts || 'object' !== typeof opts) { return false; }

    var windowGuid = opts.windowGuid;
    if (windowGuid) {
        var prefix = "";
        if (opts.isSubWindow) {
            prefix = "#subwindow_" + windowGuid;
        } else {
            prefix = "#window_" + windowGuid;
        }

        if (opts.titleUpdate) {
            var items = new Array();
            if (opts.titleUpdate.set) {
                items = opts.titleUpdate.set;
            } else {
                items.push(opts.titleUpdate);
            }

            for (var i = 0; i < items.length; i++) {
                if (!items[i].value) {
                    // Get from title field
                    items[i].value = $(prefix + " #Settings_Title").val();
                }
                if (!items[i].value) {
                    items[i].value = "";
                }

                var containsResult = false;
                if (items[i].value.toLowerCase().indexOf("[result]") >= 0) {
                    items[i].value = items[i].value.replace("[result]", "")
                    items[i].value = items[i].value.replace("[Result]", "")
                    containsResult = true;
                }

                if (items[i].value == "") {
                    $(prefix + " " + items[i].selector).html("<span>&nbsp;</span>"); // .text("") will remove icons (jQuery bug?)
                } else {
                    $(prefix + " " + items[i].selector).text(items[i].value);
                }
                if (containsResult) {
                    if ($(prefix + " " + items[i].selector).parent().find(".widget-result").length == 0) {
                        $(prefix + " " + items[i].selector).parent().append("<span class=\"widget-result\"></span>")
                    }
                } else {
                    $(prefix + " " + items[i].selector).parent().remove(".widget-result");
                }

                var editBoxIsVisible = ($(prefix).parents(".widget-content").siblings(".edit-box:visible").length == 1);

                if (items[i].filterMinimumValue && items[i].filterMinimumValue != "") {
                    if (parseInt(items[i].value, 10) < parseInt(items[i].filterMinimumValue, 10)) {
                        $(prefix).addClass("noDisplay");
                        if (editBoxIsVisible) { $(prefix).addClass("PreviouslyHidden").show(); }
                    }
                }
                if (items[i].filterMaximumValue && items[i].filterMaximumValue != "") {
                    if (parseInt(items[i].value, 10) > parseInt(items[i].filterMaximumValue, 10)) {
                        $(prefix).addClass("noDisplay");
                        if (editBoxIsVisible) { $(prefix).addClass("PreviouslyHidden").show(); }
                    }
                }
            }
        }

        if (opts.contentExpiry) {
            var controller = $(prefix).attr("controller");

            var refreshInterval = opts.contentExpiry.refreshInterval;
            if (refreshInterval >= 60 || refreshInterval == -1) {
                if (refreshInterval == -1) { refreshInterval = 0; }
                setTimeout(function () {
                    $("#content_" + windowGuid).load("/PortalApps/" + controller + "/" + windowGuid + "?rnd=" + GenerateRandomNumber());
                }, refreshInterval * 1000);
            }

            if (opts.contentExpiry.isOutOfDate) {
                ajaxManager.add({
                    success: function (html) { $("#content_" + windowGuid).html(html); },
                    url: "/PortalApps/" + controller + "/" + windowGuid + "?rnd=" + GenerateRandomNumber()
                });
            }
        }
    }
}


function GenerateRandomNumber() {
    return Math.floor(Math.random() * 100001)
}


function JQueryErrorHandler(XMLHttpRequest, textStatus, errorThrown) {
    if (textStatus != "abort") {
        alert(textStatus + ": " + XMLHttpRequest.responseText);
    }
}


function cn(s) {
    var n = parseFloat(s);
    if (isNaN(n)) { n = 0; }
    return n;
}



