﻿if (typeof WebCore == "undefined")	// this protects from when WebCore.js is loaded multiple times by the same page (shouldn't ever happen)
    WebCore = {};

if (typeof WebCore.focusFirst == "undefined")	// puts the focus on the first input field
    WebCore.focusFirst = function WebCoreFocusFirst(el) {
        var focused = false;
        el.find(":input:visible:enabled").each(function () {
            if (!focused && ($(this).val() == "" || $(this).hasClass("input-validation-error"))) {
                $(this).focus();
                focused = true;
            }
        });
    };

if (typeof WebCore.outerHtml == "undefined")	// why doesn't jQuery have outerHtml() yet?
    WebCore.outerHtml = function WebCoreOuterHtml(el) {
        return el.clone().wrap("<div></div>").parent().html();
    };

if (typeof WebCore.reloadPage == "undefined")	// when a dialog successfully posts it typically reloads the page (run from script inside the AIM iFrame)
    WebCore.reloadPage = function WebCoreReloadPage() {
        location.reload();
    };

if (typeof WebCore.AIM == "undefined")	// AIM is the way dialog forms get posted in an Ajax way (through an iFrame)
    WebCore.AIM = {
        frame: function (c) {
            var id = "f" + Math.floor(Math.random() * 99999);
            var d = $("<div><iframe style=\"display:none;\" src=\"about:blank\" id=\"" + id + "\" name=\"" + id + "\" onload=\"WebCore.AIM.loaded('" + id + "');\"></iframe></div>");
            $("body").append(d);

            var i = $("#" + id);
            if (c && typeof (c.onComplete) == "function") {
                i[0].onComplete = c.onComplete;
            }

            return id;
        },

        form: function (f, id) {
            f.attr("target", id);
        },

        submit: function (f, c) {
            WebCore.AIM.form(f, WebCore.AIM.frame(c));
            if (c && typeof (c.onStart) == "function") {
                return c.onStart();
            } else {
                return true;
            }
        },

        loaded: function (id) {
            var i = $("#" + id);
            var d;
            if (i.contentDocument) {
                d = i.contentDocument;
            } else if (i.contentWindow) {
                d = i.contentWindow.document;
            } else {
                d = window.frames[id].document;
            }
            if (d.location.href == "about:blank") {
                return;
            }

            if (typeof (i.onComplete) == "function") {
                i.onComplete(d);
            }
        }

    };

    if (typeof WebCore.dialog == "undefined")	// dialog features
        WebCore.dialog = {
            element: [],
            lastClose: null,
            click: function WebCoreDialogClick(e, el) {
                if (e != null) e.preventDefault();
                el = $(el);

                var contents = null;
                var id = el.attr("dialogContentsId");
                var href = el[0].href.replace(window.location.href, '');

                if (id == null && (href != null && href.length > 1 && href.slice(0, 1) == "#")) id = href.slice(1);

                if (id != null) {
                    WebCore.dialog.show(null, el.hasClass("layer"), id);
                    return;
                }

                if (href != null && href != "#") {
                    WebCore.dialog.getContents(href, el.hasClass("layer"));
                    return;
                }

                WebCore.dialog.show(null, el.hasClass("layer"), null, el);
            },
            dialogButtonOverrided: false,
            dialogBeforeShowUsed: false,
            getContents: function WebCoreDialogGetContents(href, layer) {
                href = href + (href.search(/\?/) == -1 ? "?" : "&") + "dialog=true";
                $.get(href, function (data, textStatus, jqXHR) {
                    if (WebCore.dialog.dialogButtonOverrided) dialogButtonOverride = undefined;
                    if (WebCore.dialog.dialogBeforeShowUsed) dialogBeforeShow = undefined;
                    if (data.search(/dialogButtonOverride/) > -1) WebCore.dialog.dialogButtonOverrided = true;
                    if (data.search(/dialogBeforeShow/) > -1) WebCore.dialog.dialogBeforeShowUsed = true;
                    WebCore.dialog.show(data, layer);
                });
            },
            keyup: function WebCoreDialogKeyup(e) {
                if (e.which == 13) $(".ui-dialog .default").click();
            },
            show: function WebCoreDialogShow(contents, layer, id, el) {
                var dlg;
                var target;
                var method;

                if ((layer == null || !layer) && WebCore.dialog.element.length > 0) {
                    dlg = WebCore.dialog.element[WebCore.dialog.element.length - 1];
                    dlg.dialog("close");
                }

                if (contents == null) {
                    if (id != null) dlg = $("#" + id);
                    if (el != null) dlg = el;
                    if (dlg != null) {
                        // jQuery UI bug fix: dialog("destory") doesn't put the element back where it was before
                        el = dlg;
                        if (el.next().length > 0) {
                            target = el.next();
                            method = "before";
                        } else if (el.prev().length > 0) {
                            target = el.prev();
                            method = "after";
                        } else {
                            target = el.parent();
                            method = "append";
                        }
                    }
                } else {
                    contents = $(contents);
                    $("body").append(contents);

                    dlg = null;

                    // almost everything below works with the first element that isn't a <link> nor <script>
                    for (var i = 0; i < contents.length; i++) {
                        if (contents[i].nodeType == 1 && contents[i].tagName != "LINK" && contents[i].tagName != "SCRIPT") {
                            dlg = $(contents[i]);
                            break;
                        }
                    }
                }

                if (dlg == null) return;

                WebCore.dialog.element.push(dlg);

                if (contents != null) {
                    dlg.find(".tabs").tabs();
                    dlg.find(".dialog").click(function (e) {
                        WebCore.dialog.click(e, this);
                    });
                }

                if (typeof $.validator != "undefined" && typeof $.validator.unobtrusive != "undefined") $.validator.unobtrusive.parse(dlg);

                var dialogButtons = dlg.attr("dialogButtons");
                if (dialogButtons == null && dlg[0].tagName != "FORM") dialogButtons = "OK";

                var dialogSubmitButtonText = dlg.attr("dialogSubmitButtonText");
                var dialogTitle = dlg.attr("dialogTitle");
                var dialogWidth = dlg.attr("dialogWidth");
                var dialogHeight = dlg.attr("dialogHeight");
                var action = dlg.attr("action");
                if (action != null && action.search(/\?.*dialog=true/) == -1) dlg.attr("action", action + (action.search(/\?/) == -1 ? "?" : "&") + "dialog=true");

                var buttons;
                switch (dialogButtons) {
                    case "Cancel":
                    case "OK":
                        buttons = [{
                            text: (dialogButtons == "Cancel" ? "Cancel" : "OK"),
                            click: function (e) {
                                if (WebCore.dialog.lastClose != null && (new Date()).getTime() - WebCore.dialog.lastClose.getTime() < 100) return;

                                dlg.dialog("close");
                            }
                        }];
                        break;
                    default:
                        buttons = [{
                            text: "Cancel",
                            click: function (e) {
                                dlg.dialog("close");
                            }
                        }, {
                            text: (dialogSubmitButtonText != null ? dialogSubmitButtonText : "Submit"),
                            click: function (e) {
                                if (WebCore.dialog.lastClose != null && (new Date()).getTime() - WebCore.dialog.lastClose.getTime() < 100) return;

                                if (dlg[0].tagName == "FORM") {
                                    if (dlg.validate() == "undefined" || dlg.validate().form() == true) {
                                        WebCore.AIM.submit(dlg, null);
                                        if (typeof dialogBeforeSubmit != "undefined") dialogBeforeSubmit(dlg);
                                        dlg.submit();
                                    }
                                } else {
                                    dlg.dialog("close");
                                }
                            },
                            "class": "default"
                        }];
                        break;
                }

                if (typeof dialogButtonOverride != "undefined") dialogButtonOverride(contents, dlg, buttons);
                if (typeof dialogBeforeShow != "undefined") dialogBeforeShow(dlg);

                dlg.dialog({
                    beforeClose: function () {
                        if (typeof dialogBeforeClose != "undefined") dialogBeforeClose(dlg);
                        return WebCore.dialog.lastClose == null || (new Date()).getTime() - WebCore.dialog.lastClose.getTime() > 100;
                    },
                    buttons: buttons,
                    close: function () {
                        if (contents != null) contents.remove();
                        else {
                            dlg.dialog("destroy");
                            // jQuery UI bug fix: dialog("destory") doesn't put the element back where it was before
                            target[method](el);
                        }
                        WebCore.dialog.element.pop();
                        WebCore.dialog.lastClose = new Date();
                    },
                    modal: true,
                    title: dialogTitle,
                    height: dialogHeight,
                    width: (dialogWidth != null ? dialogWidth : "400")
                });

                if (typeof dialogAfterShow != "undefined") dialogAfterShow(dlg);
                if (id != null && dlg.hasClass("hidden")) dlg.removeClass("hidden");

                WebCore.focusFirst(dlg);
            }
        };

if (typeof WebCore.sorter == "undefined")
    WebCore.sorter = function WebCoreSorter(th) {
        if (!th.hasClass("active")) {
            var ath = th.siblings(".active");
            if (ath.length > 0) {
                ath.removeClass("active");
                ath.removeClass("asc");
                ath.removeClass("desc");
            }

            th.addClass("active");
        }

        var type;
        if (th.hasClass("date")) type = "date";
        else if (th.hasClass("number")) type = "number";
        else if (th.hasClass("value")) type = "value";
        else type = "text"

        var order;
        if (!th.hasClass("asc") || th.hasClass("desc")) {
            th.removeClass("desc");
            th.addClass("asc");
            order = "asc";
        } else {
            th.removeClass("asc");
            th.addClass("desc");
            order = "desc";
        }

        var thIndex = th.index();

        var tds = th.closest("table").find("td").filter(function () { return $(this).index() === thIndex; });

        tds.sort(function (a, b) {
            var aValue, bValue;
            switch (type) {
                case "date":
                    aValue = new Date($(a).text());
                    bValue = new Date($(b).text());
                    break;
                case "number":
                    aValue = new Number($(a).text().replace(/,/g, ""));
                    bValue = new Number($(b).text().replace(/,/g, ""));
                    break;
                case "text":
                    aValue = $(a).text();
                    bValue = $(b).text();
                    break;
                case "value":
                    aValue = $(a).attr("_sortValue");
                    bValue = $(b).attr("_sortValue");
                    break;
            }
            return (order == "asc" ? 1 : -1) * (aValue < bValue ? -1 : (aValue > bValue ? 1 : 0));
        });

        $.each(tds, function (idx, itm) { th.closest("table").append($(itm).parent()); });
    };

$(document).ready(function () {
    $(document).keyup(function (e) {
        WebCore.dialog.keyup(e);
    });

    $(".tabs").tabs();

    $(".dialog").live("click", function (e) {
        WebCore.dialog.click(e, this);
    });

    WebCore.focusFirst($("body"));

    $("#_CurrentOnBehalfOfUserId,#_CurrentCompanyId").change(function () {
        $(this).closest("form").submit();
    });

    $(".sorter").click(function () {
        WebCore.sorter($(this));
    });
});

