﻿// debug helper
function inspect(e, wnd) {
    var str = "";
    for (var a in e) {
        str += "obj." + a + "=" + e[a] + "\n";
    };

    if (wnd && wnd != null) {
        var wnd = window.open();
        wnd.document.write("<pre>" + str.replace("\n", "<br>") + "</pre>")
    } else {
        window.alert(str)
    }
};

// simple templates (we don't need anything fancy)
String.prototype.template = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

// common functions
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}



/*returns datetime string from date object in format from parameter*/
Date.prototype.ToString = function(format) {
    function addZero(v) { return (v + '').length == 1 ? '0' + v : v };
    var result = format;
    result = result.replace("YYYY", this.getFullYear());
    result = result.replace("MM", addZero(this.getMonth() + 1));
    result = result.replace("dd", addZero(this.getDate()));
    result = result.replace("HH", addZero(this.getHours()));
    result = result.replace("mm", addZero(this.getMinutes()));
    result = result.replace("LOCALDATE", this.toLocaleDateString());
    return result;
}

Date.prototype.SetTimeFromDate = function(date, max) {
    this.setHours(date.getHours());
    this.setMinutes(date.getMinutes());
    this.setSeconds(max ? 59 : 0);
    this.setMilliseconds(max ? 999 : 1);
}

Date.prototype.CompareDays = function(date) {
    return (this.getFullYear() == date.getFullYear()) &&
           (this.getMonth() == date.getMonth()) &&
           (this.getDate() == date.getDate())
}

function ShowWaitWindow(text) {
    return $("<div><img src='/Resources/Images/ajax-loader.gif' style='vertical-align:middle'>&nbsp;&nbsp;{text}</div>".template({ text: text })).dialog({
        bgiframe: true, resizable: false, modal: true, width: 350, height: 80,
        position: ['center', 'center'],
        buttons: {}, dialogClass: 'wait-window'
    });
}

// on page init
$(function() {
    // make rounded corners
    $("#content-wrapper").corner("bottom");
    $("#footer").corner("top");

    // create main menu
    $(".menu-tab-styled li").each(function() {
        var html = "<span class=\"tab-menu-out\"><span class=\"tab-menu-in\"><span class=\"tab-menu-text\">{text}</span></span></span>";
        var item = $(this), a = item.find("a");

        if (item.hasClass("active")) {
            item.removeClass("active");
            a.addClass("active");
        }

        a.html(html.template({ text: a.html() }));
    });

    // show, hide expand/shrink tip
    $(".bug-item-content").hover(
        function() { var height = $(this)[0].scrollHeight; if (height > 60) { $(this).find("span.more").css("visibility", "visible"); } },
        function() { $(this).find("span.more").css("visibility", "hidden"); }
    );

    $(".bug-item-title a").hover(
        function() { $(this).animate({ backgroundColor: "#00709D", color: "#ffff9f" }, 500); },
        function() { $(this).animate({ backgroundColor: "#fff", color: "#00709D" }, 500); }
    );

    // expand bug in bug list
    $(".bug-item-content").click(function() { //, .creator-comment-item-content
        var item = $(this), minHight = item.hasClass("creator-comment-item-content") ? "52px" : "30px", height, text;
        height = item.css("height") == "100%" ? minHight : "100%";
        text = item.css("height") == "100%" ? Localization.Expand : Localization.Shrink;
        $(this).css({ "height": height, "minHeight": minHight }).find(".more").html(text);
        return false;
    });

    // button state
    $('.menu-button').hover(
        function() { $(this).removeClass('ui-state-default').addClass('ui-state-focus'); },
        function() { $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }
    );

    // menu buttons (drop downs)
    $('.menu-button').each(function() {
        var item = $(this);
        var list = item.next("div.hidden");
        if (list.length > 0 && list.html()) {
            item.menu({
                content: list.html(),
                maxHeight: 250,
                positionOpts: { posX: 'left', posY: 'bottom', offsetX: 0, offsetY: 0, directionH: 'right', directionV: 'down', detectH: true, detectV: false, linkToFront: false }
            });
        } else {
            item.find(".ui-icon").remove();
        }
    });

    // delete elements (regular view replacement with modal dialog)
    $(".delete-action").each(function() {
        var that = $(this), a = that.find("a"), form = $("#delete_form_" + a.attr("id").replace("delete_source_element_", ""));
        var buttons = {};
        buttons[Localization.Cancel] = function() { window.parent.$(this).dialog('close') };
        buttons[Localization.Delete] = function() { form.submit() };

        a.bind("click", function() {
            $("<div>{message}</div>".template({ message: DeleteMessage })).dialog({
                bgiframe: true,
                resizable: false,
                title: Localization.Delete,
                modal: true,
                buttons: buttons
            });
            return false;
        });
    });

    $(".delete-action2").each(function() {
        var that = $(this), a = that.find("a"), form = $("#delete_form_" + a.attr("id").replace("delete_source_element_", ""));
        var buttons = {};
        buttons[Localization.Cancel] = function() { window.parent.$(this).dialog('close') };
        buttons[Localization.Delete] = function() {
            $(".form-delete-type").val($("input[name=delete]:checked").val());
            form.submit()
        };

        $('.delete-dialog').dialog({
            bgiframe: true,
            resizable: false,
            title: Localization.Delete,
            modal: true,
            autoOpen: false,
            buttons: buttons
        });

        a.bind("click", function() {
            $('.delete-dialog').dialog('open');
            return false;
        });
    });

    try {
        // change look of the submit field
        if (SI != 'undefined' && SI.Files) SI.Files.stylizeAll();
    } catch (e) { }

    try {
        // add option for multiupload
        $('.file').MultiFile({
            list: '#fileAttachmentWrapper',
            namePattern: '$name_$i'
        });
    } catch (e) { }

    // comment form
    $("#SelectedCloseReason").attr("disabled", !$('#IsClosed:checked').length);
    $("#LabelSelectedCloseReason").attr("disabled", !$('#IsClosed:checked').length);
    if (!$('#IsClosed:checked').length) $("#comment_corrective_actions").hide();

    $('#IsClosed').click(function() {
        var val = !$('#IsClosed:checked').length;
        $("#LabelSelectedCloseReason").attr("disabled", val);
        $('#SelectedCloseReason').attr('disabled', val);

        if ($("#comment_corrective_actions tr").length == 0) {
            $("#comment_corrective_actions").hide();
            return;
        }

        if (val) {
            $("#comment_corrective_actions").hide();
        } else {
            $("#comment_corrective_actions").show()
        }
    });

    // create rating controls
    //$("#comment_corrective_actions td.stars-holder").stars({ inputType: 'select', cancelShow: true }).find("select").hide();

    // scroll to form if error
    if ($(".validation-summary").length > 0) {
        var v = $($(".validation-summary")[0]);
        $.scrollTo(v.offset().top - 40, 500);
    } else {
        // let's check if there is a link anchor in url
        var target = location.hash && $(location.hash);
        if (target.length > 0) $.scrollTo(target.offset().top, 500);
    }

    // show message if files are uploaded
    if ($(".MultiFile").length > 0) {
        var dialogTemplate = "$('<div>' + Localization.SubmittingMessage + '</div>').dialog({ modal: true, closeOnEscape: false, open: function() {$(this).parents('.ui-dialog:first').find('.ui-dialog-titlebar-close').remove()}})";
        $("form").attr("onsubmit", dialogTemplate);
    }

    try {
        // styled combobox
        $("select.linkselect").linkselect();
    } catch (e) { }

    function DisableSearch(button, link, disable) {
        if (disable) {
            button.addClass("ui-state-disabled");
            link.attr("disabled", "true");
            link.css("cursor", "default");
        } else {
            button.removeClass("ui-state-disabled");
            link.attr("disabled", "");
            link.css("cursor", "pointer");
        }
    }

    var search = $("#pattern");
    if (search.length) {
        var button = $("#pattern-button");
        var a = button.find("a");

        search.bind("change keyup", function() {
            if ($(this).val().length > 0) {
                DisableSearch(button, a, false);
            } else {
                DisableSearch(button, a, true);
            }
        });

        DisableSearch(button, a, true);
    }

    // comment for suuport only checkbox
    $("#SupportOnly").click(function() {
        var val = $("#SupportOnly:checked").length
        var checkBox = $("#IsClosed");
        checkBox.attr("disabled", val);
        checkBox.attr("checked", false);
        $("#SelectedCloseReason").attr("disabled", val);

        var fieldset = $("fieldset.ui-close-fieldset");

        if (val > 0) {
            fieldset.addClass("ui-state-disabled");
        }
        else {
            fieldset.removeClass("ui-state-disabled");
        }

    });

    // admin report bug

    $("select#BugCompany").change(function() {
        var emptyList = "<option value='0'>" + noProducts + "</option>";
        var val = $(this).val();
        if (val > 0) {

            //$("select#BugProduct").attr("disabled", "true").html(emptyList);
            $("select#BugProduct").html(emptyList);
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "/FindProducts/" + val + "?timestamp=" + (new Date()).getTime(),
                dataType: "json",
                success: function(data) {
                    if (data.length > 0) {
                        var options = '';
                        for (p in data) {
                            var product = data[p];
                            options += "<option value='" + product.ProductId + "'>" + product.Name + "</option>";
                        }
                        $("select#BugProduct").html(options);
                        //$("select#BugProduct").removeAttr("disabled").html(options);
                    } else {
                        $("select#BugProduct").html(emptyList);
                        //$("select#BugProduct").attr("disabled", "true").html(emptyList);
                    }
                }
            });
        }
        else {
            //$("select#BugProduct").attr("disabled", "true").html(emptyList);
            $("select#BugProduct").html(emptyList);
        }

    });

    // scroll when bug is about to be closed
    var reopen = getUrlVars()["reopen"];
    if (reopen) {
        $.scrollTo("#comment-form", 500);
    }



    // bug details
    var buttons = {}; buttons[Localization.Close] = function() { window.parent.$(this).dialog('close') };
    $("div.bug-details").dialog({ autoOpen: false, bgiframe: true,
        resizable: false, modal: true, width: 600, height: 400,
        position: ['center', 'center'], title: Localization.BugOpenDetails,
        buttons: buttons
    });

    $("#bugDetails").click(function() {
        if ($("div.bug-details table").length == 0) {
            var bugId = $($("#bugDetails")[0]).attr("rel")
            $.ajax({
                type: "GET",
                url: "/Bug/DetailsControl/" + bugId + "?timestamp=" + (new Date()).getTime(),
                dataType: "html",
                async: false,
                success: function(msg) {
                    $("div.bug-details").append(msg);
                }
            });
        }
        $("div.bug-details").dialog('open');
        return false;
    });

    // start on corrective action page
    $("#correctiveActions").find("tbody td.stars-holder").stars({ inputType: 'select', disabled: true, cancelShow: false }).find("select").hide();
});


// jquery ui corrections
/*
$.ui.dialog.prototype.destroy = function() { 
    var th = this;
    (th.overlay && th.overlay.destroy());
        this.uiDialog.hide(this.options.hide, {}, "slow", function() {
        th.uiDialog.remove();
    });
}
*/



(function($) {
    $(document).ready(function() {
        $("form[onsubmit]").each(function(idx, form) {
            var onsubmit = $(form).attr("onsubmit");
            $(form).removeAttr("onsubmit").submit(new Function(onsubmit));
        });
    });
})(jQuery);
