﻿//
// Emulate C# String.Format(string, params object[])
//
String.format = function () {
    if (arguments.length == 0) {
        return null;
    }

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(exp, arguments[i]);
    }
    return str;
};

//
// Array extension methods
//
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            return i;
        }
    }
    return -1;
}

Array.prototype.contains = function (val) {
    var index = this.indexOf(val);
    return index >= 0;
}

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    return this.slice(0, index).concat(this.slice(index + 1));
};

Array.prototype.add = function (val) {
    return this.push(val);
}

//
// JQuery Extensions
//

//
// Causes an element to snap to the position of the mouse.
//
jQuery.fn.snapToMouse = function (e) {
    $(this).css({
        "top": e.screenY - window.screenTop + $(document).scrollTop(),
        "left": e.screenX - window.screenLeft + $(document).scrollLeft(),
        "position": "absolute"
    });
};

//
// Custom global functions
//

//
// Displays an error message to the user.
//
function showError(message, request, text) {
    var formattedMessage = "";
    if (request == null) {
        formattedMessage = message;
    } else if (request != null && text == null) {
        formattedMessage = String.format('{0}\r\nHTTP/{1}: {2}'
            , message
            , request.status
            , request.statusText);
    } else {
        formattedMessage = String.format('{0}\r\nHTTP/{1}: {2}\r\n{3}'
            , message
            , request.status
            , request.statusText
            , text);
    }

    $("#errorMessageDialog").dialog("open");
    $("#errorMessageDialog").text(formattedMessage)
}

//
// Gets a JSON result from an MVC action
// parameters = {
//      url, // the url to access
//      data, // the data object to send in the post body
//      success, // a function to execute when successful
// }
function getJson(options) {
    return $.ajax({
        type: "POST",
        dataType: "json",
        cache: false,
        url: options.url,
        data: options.data,
        success: options.success,
        error: function (request, text, err) {
            showError("Failed to retreive data from server.", request, text);
        }
    });
}

//
//
//
function getHtml(options) {
    $.extend({
        method: "POST"
    }, options);

    return $.ajax({
        type: options.method,
        dataType: "html",
        cache: false,
        url: options.url,
        data: options.data,
        success: options.success,
        error: function (request, text, err) {
            showError("Failed to retreive data from server.", request, text);
        }
    });
}

//
//
//
function formatCommentSpans(commentIds, afterbound) {
    $(function () {
        $("span").each(function () {
            // Check the ID to see if it matches the format.
            var id = $(this).attr("id");
            if (id.indexOf("comment:") < 0) {
                return;
            }

            // Remove the comment css class
            $(this).removeClass("documentComment");
            $(this).unbind("mouseenter");

            // Get the comment's id and check to see if it is
            // in the reference array
            var commentId = parseInt(id.split(":")[1]);
            if (!commentIds.contains(commentId)) {
                return;
            }

            // Add the comment css class
            $(this).addClass("documentComment");
            
            // Execute custom actions
            afterbound($(this), commentId);
        });
    });
}

//
//
//
function validateEmail(email) {
    emailPattern = new RegExp(".+@.+\..+");
    return email.match(emailPattern);
}

//
// Fills a dialog with the requested partial view, then
// opens it for the user.
//
function dialogLink(dialogId, url) {
    $(function () {
        var dialog = $("#" + dialogId);
        getHtml({
            url: url
            , method: "GET"
            , data: {}
            , success: function (html) {
                dialog.html(html);
                dialog.dialog("open");
            }
        });
    });
}

//
//
//
function showWaitDialog() {
    $("#pleaseWaitDialog").dialog("open");
}
function hideWaitDialog() {
    $("#pleaseWaitDialog").dialog("close");
}

//
//
//
function displayMessages(url, failure, success) {

    getJson({
        url: url
        , data: {}
        , success: function (json) {
            if (json.errors.length > 0) {
                $("#errorMessageDialog")
                    .html(json.errors.join("<br />"))
                    .dialog("option", "buttons", {
                            "OK": function () {
                                $(this).dialog("close");
                                if (failure != null) {
                                    failure($(this));
                                }
                            }
                        })
                    .dialog("open");
                $("#errorMessageDialog")
                    .html(json.errors.join("<br />"))
                    .dialog("open");
                return;
            }

            if (json.successes.length > 0) {
                $("#successMessageDialog")
                    .html(json.successes.join("<br />"))
                    .dialog("option", "buttons", {
                            "OK": function () {
                                $(this).dialog("close");
                                if (success != null) {
                                    success($(this));
                                }
                            }
                        })
                    .dialog("open");
            }
        }
    });
}


