﻿$(document).ready(function() {
    $('#orchestrationsDetails').hide();
    $('#receivePortDetails').hide();
    $('#sendPortDetails').hide();

    $(document).ajaxError(function(info, xhr) {
        showErrorMessage("<p>Oops... Page update failed.</p><p>Status code: " + xhr.status + "<br />Description: " + xhr.statusText + "</p><p>The error has been logged, please try again later. If the error persists, please contact the site administrator.</p>");
    });

    $('.instancesOfApplication').tablesorter().tablesorterPager({ container: $("#instanceTablePager"), positionFixed: false });

    // if the page has any throughput chart loaders, load them after the page has been loaded
    $('div#throughputLoader').AjaxLoadImage();

    setupErrorDialog();
    setupMonitorDialog();
    setupMonitorActions();
    setupAlertDialog();
    setupAlertActions();
});

function openDialogOnce(dialog) {
    if (!dialog.dialog('isOpen')) {
        dialog.dialog('open');
    }
}

function showErrorMessage(message) {
    $("#AjaxErrorDivMessage").html(message);

    var errorDialog = $("#AjaxBottomErrorDiv");
    openDialogOnce(errorDialog);
}

function setupErrorDialog() {
    $("#AjaxBottomErrorDiv").dialog({
        width: 440,
        resizable: false,
        title: 'Error',
        modal: true,
        autoOpen: false
    });
}

/*
jQuery method to load image with Ajax

Assumes the image to load is contained in a div with attributes
* class: loading - so the background spinner is shown
* title: <url to the picture>

Original from http://jqueryfordesigners.com/image-loading/
*/
(function($) {
    $.fn.AjaxLoadImage = function() {
        var div = $(this);

        var picUrl = div.attr('title');  // we are reusing the title tag so we don't need any custom tags
        var img = new Image();

        // wrap our new image in jQuery, then:
        $(img)
        // once the image has loaded, execute this code
        .load(function() {
            // set the image hidden by default    
            $(this).hide();

            div
            // remove the loading class (so no background spinner), 
                .removeClass('loading')
            // then insert our image
                .append(this);

            $(this).show();
        })
        .error(function() {
            showErrorMessage("<p>Oops... Loading image failed.</p><p>The error has been logged, please try again later. If the error persists, please contact the site administrator.</p>");
            div.removeClass('loading');
        })

        // *finally*, set the src attribute of the new image to our image
        .attr('src', picUrl);
    }
})(jQuery);

/*
Helper function to show info div
*/
function showInfoMessage(targetId, message) {
    $(targetId).html('<div class="BizTalkMonitorInfo">' + message + '</div>');
}

function jumpToAnchor(anchor) {
    window.location = String(window.location).replace(/\#.*$/, "") + "#" + anchor;
}

function ChangeSelectedRow(type, id) {
    $('.' + type + 'Selected').removeClass(type + 'Selected').addClass(type);
    $('#' + type + id).removeClass(type).addClass(type + 'Selected');
}

/*
Fetches the message flow for the chosen process instance
*/
function GetMessageFlow(id, url) {
    ChangeSelectedRow('instancesOfApplicationInstanceRow', id);
    showInfoMessage('.BizTalkMonitorMessageFlowCon', 'Loading message flow');
    showInfoMessage('.BizTalkMonitorDetailsContainer', 'No instance selected');

    $.get(url, function(data) {
        $('.BizTalkMonitorMessageFlowCon').html(data);
        var clickLastMsgFlowItem = $('.BizTalkMonitorMessageFlowCon div.MessageFlowServiceInstanceRow:last-child').attr("onclick");
        if (clickLastMsgFlowItem != null)
            clickLastMsgFlowItem(null);
    });
}

//targetId: id of the element to show/hide
function ToggleTargetVisibility(sender, targetId) {
    var target = $('#' + targetId);
    var imageElem = $(sender).find('img.logolink');
    var imageSrc = imageElem.attr('src');
    var altValue = "";

    if (target.is(":visible")) {
        imageSrc = imageElem.attr('src').replace('arrow_down', 'arrow_right');
        altValue = '&gt;&nbsp;';
        target.hide('slow');
    }
    else {
        imageSrc = imageElem.attr('src').replace('arrow_right', 'arrow_down');
        altValue = 'V&nbsp;';
        target.show('slow');
    }
    imageElem.attr({ src: imageSrc, alt: altValue });

    return false;
}

/*****************************************
Message Details functions
*****************************************/

/*
Fetches the message chosen from messageflow
*/
function ShowMessage(id, url) {
    ChangeSelectedRow('MessageFlowServiceInstanceRow', id);
    showInfoMessage('.BizTalkMonitorDetailsContainer', 'Loading message...');

    $.get(url, function(data) {
        $('.BizTalkMonitorDetailsContainer').html(data);
    });
}

/*****************************************
Service Instance Details functions
*****************************************/

function ShowServiceInstance(id, url) {
    ChangeSelectedRow('MessageFlowServiceInstanceRow', id);
    showInfoMessage('.BizTalkMonitorDetailsContainer', 'Loading service instance details...');

    $.get(url, function(data) {
        $('.BizTalkMonitorDetailsContainer').html(data);
    });
}

/**********************************************************
Monitor related javascript functions for application page
***********************************************************/

function addTicksToSlider() {
    $(".tick").show();
}

function removeTicksFromSlider() {
    $(".tick").hide();
}

function uncheckAll() {
    $('.dayCheck').attr('checked', false);
}

function hourlySelected() {
    $(".monitorDailyTimewindowDescription").hide();
    $(".monitorHourlyTimewindowDescription").show();
    addTicksToSlider();
}

function dailySelected() {
    $(".monitorHourlyTimewindowDescription").hide();
    $(".monitorDailyTimewindowDescription").show();
    removeTicksFromSlider();
}

function setupSlider(sliderElement) {
    /// <Functions for adding ticks to slider>
    function refreshRange() {
        var s = slider
                , min = s.slider("option", "min"), max = s.slider("option", "max")
                , lo = s.slider("values", 0), hi = s.slider("values", 1)
                , atMin = (lo == min), atMax = (hi == max);
        s.find(".ui-slider-range")
                [(atMin ? 'add' : 'remove') + 'Class']("ui-corner-left")
                [(atMax ? 'add' : 'remove') + 'Class']("ui-corner-right");
    }

    function refreshTicks() {
        var s = slider
                , lo = s.slider("values", 0), hi = s.slider("values", 1);
        s.find(".tick").each(function(i) {
            var inRange = (i >= lo && i < hi);
            $(this)
                    [(inRange ? 'add' : 'remove') + 'Class']("ui-widget-header")
                    [(inRange ? 'remove' : 'add') + 'Class']("ui-widget-content");
        });
    }
    /// </Functions for adding ticks to slider>

    var slider = sliderElement.slider({
        range: true,
        min: 0,
        max: 24,
        values: [$("#ActiveTime_StartTime").val(), $("#ActiveTime_EndTime").val()],
        slide: function(event, ui) {
            $("#ActiveTime_StartTime").val(ui.values[0]);
            $(".startTimeText").attr("innerHTML", ui.values[0]);
            $("#firstCheckText").attr("innerHTML", ui.values[0] + 1); // The first check need to be one bigger the the start time.
            $("#ActiveTime_EndTime").val(ui.values[1]);
            $(".endTimeText").attr("innerHTML", ui.values[1]);
            refreshRange();
            refreshTicks();
        }
    });

    var hours = 24;
    for (var i = 0; i < hours; i++) {
        var tick = $('<div class="tick "></div>').appendTo(slider);
        tick.css({
            left: (100 / hours * i) + '%',
            width: (100 / hours) + '%'
        });
    }
    slider.find(".tick:first").css("border-left", "none");

    refreshRange();
    refreshTicks();
}



function closeMonitorDialog() {
    $('#monitorDialog').dialog('close');
}

function setupMonitorDialog() {
    $("#monitorDialog").dialog({
        width: 440, //Width needs to be set here, the dialog content does not affect the width of the dialog, instead it is set to the default of 300px
        modal: true,
        resizable: false,
        autoOpen: false
    });
}

function setupMonitorActions() {
    $('.monitorLink')
        .unbind('click') // clean up old click handlers
        .click(function(e) {
            var clicked = $(this);

            var monitorDialog = $('#monitorDialog');
            if (!openDialog(monitorDialog)) {
                return;
            }
            setMonitorDialogTitle("");

            var url = clicked.attr('href');
            $.get(url, {}, function(data) {
                fillMonitorDialog(data, clicked);
            });
            return false; // do not pass the click
        });

    $('.deleteMonitorLink')
        .unbind('click') // clean up old click handlers
        .click(function(e) {
            var clicked = $(this);

            var deleteUrl = clicked.attr('href');

            if (confirm('Really delete the monitor?')) {
                $.post(deleteUrl, {}, function(data) {
                    clicked.parent().html(data);
                    setupMonitorActions(); // TODO: may this cause the links to be registered also on delete failure? Multiple times?
                });
            }

            return false; // do not pass the click
        });

    function setMonitorDialogTitle(newTitle) {
        $('#monitorDialog').dialog('option', 'title', newTitle);
    }

    function fillMonitorDialog(data, clickedLink) {
        //Load the new dialog
        var monitorDialog = $("#monitorDialog");
        monitorDialog.html(data);

        // set the title 
        // (jQuery UI dialog cannot set it automatically, 
        // because it is not in the source div)
        var title = $("#monitorDialog > div").attr("title");
        setMonitorDialogTitle(title);

        var formOptions = {
            beforeSubmit: disableMonitorDialogSubmit,
            target: clickedLink.parent(),
            error: closeMonitorDialog,
            success: function() {
                closeMonitorDialog();
                setupMonitorActions();
            }
        };
        var form = $('#monitorForm');
        form.ajaxForm(formOptions);

        setupMonitorDialogEvents();

        setupSlider($("#timewindow-slider"));

        function disableMonitorDialogSubmit() {
            $('#monitorSubmit').attr('disabled', 'disabled');
        }
    }

    function setupMonitorDialogEvents() {
        $("#Hourly").change(function() {
            if ($(this).val() == "true")
                hourlySelected();
            else
                dailySelected();
        });

        $("#ActiveTime_DayPreset").change(function() {
            var value = $(this).val();
            switch (value) {
                case "Custom":
                    $('#monitorDayCheckTable').show();
                    break;
                case "Weekdays":
                case "Everyday":
                default:
                    $('#monitorDayCheckTable').hide();
                    break;
            }
        });
    }


}


/**********************************************************
Alert related javascript functions
***********************************************************/

function setupAlertDialog() {
    var alertDialog = $("#alertDialog");
    alertDialog.dialog({
        width: 600,
        height: 500,
        minWidth: 250,
        resizable: true, // allow horizontal resizing 
        minHeight: 500,
        maxHeight: 500,
        modal: true,
        autoOpen: false
    });
}

function closeAlertDialog() {
    var alertDialog = $('#alertDialog');
    alertDialog.dialog('close');
}

function openDialog(dialog) {
    if (dialog.dialog('isOpen')) {
        return false;
    }

    dialog.dialog('open');
    dialog.html("<p>Loading...</p>")

    return true;
}

function setupAlertActions() {
    $('.alertLink')
        .click(function(e) {
            var alertDialog = $('#alertDialog');
            if (!openDialog(alertDialog)) {
                return;
            }


            var url = $(this).attr('href');

            $.get(url, {}, function(data) {
                fillAlertDialog(data);
            });

            return false;
        });

    function fillAlertDialog(data) {
        var alertDialog = $('#alertDialog');
        alertDialog.html(data)

        var formOptions = {
            beforeSubmit: disableAlertDialogSubmit,
            error: closeAlertDialog,
            success: function() {
                closeAlertDialog();
                /* reload the current page so redundant alert icons are not shown */
                location.reload(true);
            }
        };
        var form = $('#alertForm');
        form.ajaxForm(formOptions);

        setupAlertDialogEvents();

        $("#alertDialogCancel").focus(); //Set the focus to the cancel button
    }

    function setupAlertDialogEvents() {
        $(".resolveCheckbox").click(function() {
            enableAlertDialogSubmit();
        });
        $("#alertDialogCancel").click(function() {
            $('#alertDialog').dialog('close');
        });
        $("#CheckNone").click(function() {
            checkNoResolveCheckboxes();
            return false;
        });
        $("#CheckAll").click(function() {
            checkAllResolveCheckboxes();
            return false;
        });
    }

    function checkAllResolveCheckboxes() {
        $('.resolveCheckbox').attr("checked", true);
        enableAlertDialogSubmit();
        $('#CheckAll').css('display', 'none');
        $('#CheckNone').css('display', 'block');
    }

    function checkNoResolveCheckboxes() {
        $('.resolveCheckbox').attr("checked", false);
        $('#CheckNone').css('display', 'none');
        $('#CheckAll').css('display', 'block');
    }

    function enableAlertDialogSubmit() {
        $('#alertDialogSubmit').removeAttr('disabled');
    }

    function disableAlertDialogSubmit() {
        $('#alertDialogSubmit').attr('disabled', 'disabled');
    }
}



