var LOADING_HTML = '<br/><br/><br/><center><img src="/images/spinner.gif"/><center>';
var _CurrentPopupBox = null;
var _CurrentModalFrame = null;
var _CurrentModalCover = null;
var _IFrameEventInterval = null;

function OpenModal(url, openEffect, width, height) {
    GetOpenModal(url, openEffect, width, height);
}

function GetOpenModal(url, openEffect, width, height) {
    CloseModal(false);

    $(".popup-blocker").hide();

    var cssClass = 'defaultModal';

    // Create a box:
    _CurrentPopupBox = $('<div style="position:absolute;" />');
    _CurrentPopupBox.addClass(cssClass);

    // Create an IFRAME:
    _CurrentModalFrame = $("<iframe frameborder='0' />");
    _CurrentModalFrame.css("visibility", 'hidden');
    _CurrentModalFrame.attr('ALLOWTRANSPARENCY', 'true');

    if (width)
        _CurrentModalFrame.css("width", width);

    if (height)
        _CurrentModalFrame.css("height", height);


    _CurrentModalFrame.attr("src", url);

    _CurrentModalFrame.attr("parentWidth", $(window).width());
    _CurrentModalFrame.attr("parentHeight", $(window).height());
    _CurrentModalFrame.attr("parentScroll", $(window).scrollTop());
    if (width)
        _CurrentModalFrame.attr("specifiedWidth", width);
    if (height)
        _CurrentModalFrame.attr("specifiedHeight", height);
    if (openEffect) //openEffect = "fast";
    {
        _CurrentModalFrame.attr("openEffect", openEffect);
    }

    // Wrappers:
    var parent = _CurrentPopupBox;
    for (var i = 1; i <= 6; i++) {
        var box = $("<span class=\"modal-wrapper" + i + "\" />");
        parent.append(box);
        parent = box;
    }

    parent.append(_CurrentModalFrame);

    // Create new cover:
    _CurrentModalCover = $("<div class='modal-cover'>&nbsp;</div>");

    _CurrentModalCover.width(FindMaximumPageWidth());
    _CurrentModalCover.height(FindMaximumPageHeight());

    // in the next code 50 is the half of the spinner image width (height)
    _CurrentModalCover.css("background-position", ($(window).width() / 2 - 50) + "px " + ($(window).height() / 2 - 50) + "px");
    _CurrentModalCover.css("top", $(window).scrollTop());

    $(window).scroll(function () {
        if (_CurrentModalCover) {
            _CurrentModalCover.css("top", $(window).scrollTop() + "px");
            _CurrentModalFrame.css("top", (($(window).height() - _CurrentModalFrame.height()) / 2 + $(window).scrollTop()) + "px");
        }
    });

    if ($.browser.msie) {
        // IE has problem with setting overflow.
    }
    else {
        $("html").css("overflow", "hidden");
    }

    // hide items
    _CurrentModalCover.hide();
    _CurrentPopupBox.hide();

    // Add all to the body:     
    $(document.body).append(_CurrentPopupBox);
    $(document.body).append(_CurrentModalCover);

    // show items
    //_CurrentModalCover.show();
    _CurrentModalCover.css("filter", "alpha(opacity=60)");
    _CurrentModalCover.fadeIn(100);
    _CurrentPopupBox.show();

    _CurrentPopupBox.css("top", 0);
    _CurrentPopupBox.css("left", 0);


    _CurrentModalFrame.ready(InitializeModalPage);
    _CurrentModalFrame.hide();
    _CurrentModalFrame.load(AdjustFrameSize);

    return _CurrentModalFrame;
}

function FindMaximumPageWidth() {
    var result = Math.max($(document).width(), $(window).width());

    var outerWidth = $(document).outerWidth();
    if (!isNaN(outerWidth))
        result = Math.max(result, outerWidth);

    outerWidth = $(window).outerWidth();
    if (!isNaN(outerWidth))
        result = Math.max(result, outerWidth);

    return result;
}

function FindMaximumPageHeight() {
    var result = Math.max($(document).height(), $(window).height());

    var outerHeight = $(document).outerHeight();
    if (!isNaN(outerHeight))
        result = Math.max(result, outerHeight);

    outerHeight = $(window).outerHeight();
    if (!isNaN(outerHeight))
        result = Math.max(result, outerHeight);

    return result;
}

function InitializeModalPage() {

    // What is this for?
    if (_CurrentModalFrame.attr('name') == "frmContent") {
        return;
    }

    var IFrame = _CurrentModalFrame;
    $(IFrame.get(0).contentWindow).focus();

    return;

    switch (IFrame.attr("openEffect")) {
        case "slow":
        case "normal":
        case "fast":
            IFrame.show(IFrame.attr("openEffect"));
            break;
        case "slide":
            IFrame.slideDown();
            break;
        case "fade":
            IFrame.fadeIn();
            break;
        default:
            IFrame.show();
            break;
    }
}

function AdjustFrameSize() {

    var isFirstTimeLoad =
_CurrentModalFrame.attr("IsModalWindowOpened") != "true";
    // ----- Mark this window as loaded (for handing navigation on the popup itself)
    _CurrentModalFrame.attr("IsModalWindowOpened", "true");

    var iFrame = _CurrentModalFrame;



    // Find variables --------------------------------------------
    var margin = 80;
    var parentWidth = parseInt(iFrame.attr("parentWidth"));
    var parentHeight = parseInt(iFrame.attr("parentHeight")) - margin;
    var parentScroll = parseInt(iFrame.attr("parentScroll"));

    // Show and hide the box, so that we can get actual content in FireFox #####
    if (isFirstTimeLoad) {
        iFrame.css("visibility", "hidden");
        iFrame.show();
    }

    var actualContentWidth = 0;
    var actualContentHeight = 0;
    var specifiedWidth = iFrame.attr("specifiedWidth");
    var specifiedHeight = iFrame.attr("specifiedHeight");
    if (specifiedWidth) {
        actualContentWidth = specifiedWidth;
    } else {

        actualContentWidth = $(iFrame.get(0).contentWindow.document.body).width(); //+ 10;
    }
    if (specifiedHeight)
    { actualContentHeight = specifiedHeight; }
    else {

        actualContentHeight = $(iFrame.get(0).contentWindow.document.body).height() + 1; //+ 50;
    }
    if (isFirstTimeLoad) {
        iFrame.hide();
    }
    //#########################################################################

    // Set the dimensions ----------------------------------------
    var width = Math.min(actualContentWidth, parentWidth);
    var height = Math.min(actualContentHeight, parentHeight);

    if (!iFrame.css("width"))
        iFrame.width(width);

    iFrame.height(height);

    // Find position ---------------------------------------------
    var top = iFrame.offset().top;
    top = (parentHeight - height) / 2;
    top = Math.max(top, margin / 2);
    top += parentScroll;
    var left = (parentWidth - width) / 2;
    iFrame.css("top", top + "px");
    iFrame.css("left", left + "px");

    if (isFirstTimeLoad) {
        // Now show it:
        iFrame.css("visibility", 'visible');
        iFrame.fadeIn(500);
        iFrame.show();
    }

    _CurrentModalFrame.css("top", (($(window).height() - _CurrentModalFrame.height()) / 2 + $(window).scrollTop()) + "px");
}


function CloseModal(refreshParent, closeEffect) {

    $(".popup-blocker").show();

    if ($.browser.msie) {
        // IE has problem with setting overflow.
    }
    else {
        //$(document.body).css("overflow", "scroll");
        $("html").css("overflow", "auto");
    }

    if (closeEffect == undefined) closeEffect = "fade";

    if (_CurrentModalFrame) {

        _CurrentModalFrame.attr("isLoaded", "false");

        if (closeEffect == "immediate")
            _CurrentModalFrame.hide();
        else if (closeEffect == "fade") {
            _CurrentModalFrame.fadeOut();
        }
        else if (closeEffect == "normal" || closeEffect == "fast" || closeEffect == "slow")
            _CurrentModalFrame.hide(closeEffect);
        else if (closeEffect == "slide")
            _CurrentModalFrame.slideUp();
        else
            _CurrentModalFrame.hide();
    }





    //    if (_CurrentModalCover != null) {
    //        _CurrentModalCover.fadeOut(function() {

    //            _CurrentModalCover.hide();
    //            _CurrentModalCover = null;
    //        });
    //    }

    //    if (_CurrentPopupBox != null) {
    //        _CurrentPopupBox.fadeOut(function() {
    //            _CurrentPopupBox.hide();
    //            _CurrentPopupBox = null;
    //        });
    //    }



    if (_CurrentModalCover) {
        _CurrentModalCover.fadeOut(function () {
            if (_CurrentModalCover) {
                _CurrentModalCover.hide();
                _CurrentModalCover = null;
            }
        });
    }

    if (_CurrentPopupBox) {
        _CurrentPopupBox.fadeOut(function () {
            if (_CurrentPopupBox) {
                _CurrentPopupBox.hide();
                _CurrentPopupBox = null;
            }
        });
    }








    if (refreshParent == true) {
        __doPostBack('', '');
    }

    $(window).focus();
}













function SetTextboxClasses() {
    var inputs = document.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].type.toLowerCase() == 'text' || inputs[i].type.toLowerCase() == 'password') {
            inputs[i].className += ' textbox';
        }
    }
}

/// This will break the execution for current javascript thread.
function Break() {
    // Return nothing. This method is meant to be used in hyperlink href's
}

//function OpenBrowserWindow(url, target) {

//    if (target == null) target = '_blank';

//    var frame = $("#" + target).get(0);

//    if (frame) {
//        frame.contentWindow.document.body.innerHTML = LOADING_HTML;
//        frame.src = url;
//        return;
//    }
//    window.open(url, target);
//}

function OpenBrowserWindow(url, target) {
    if (target == null) target = '_blank';

    // this line doesn't work in any browser
    //var frame = $("#" + target).get(0);

    if (target == '_self') {
        window.open(url, target);
    }
    else {

        var frame = null;

        if (target != '_blank' && parent != null) {
            try {
                frame = parent.frames[target];
            } catch (error) {
                // Possibly Permission issue / or no Frames.
            }
        }

        if (frame != null) {
            $(frame).get(0).document.body.innerHTML = LOADING_HTML;
            frame.location.href = url;
            return;
        }
        window.open(url, target);
    }
}

// Preload "Please wait" image:
$(document).ready(function () { preloadImages('/Images/PleaseWait.gif'); });

var PleaseWaitImage = null;

function HidePleaseWait() {
    if (PleaseWaitImage == null) return;

    try { PleaseWaitImage.fadeOut(); PleaseWaitImage = null; } catch (ex) { }
}

function ShowPleaseWait(blockScreen) {
    if (blockScreen) {
        var cover = $("<div class='modal-cover'>&nbsp;</div>");
        cover.width(Math.max($(document).width(), $(window).width()));
        cover.height(Math.max($(document).height(), $(window).height()));
        cover.css("display", "block");

        $("form").append(cover);
    }

    PleaseWaitImage = $("<img style='position:absolute; left:0; top:0; display:none; margin:20% 50%; z-index:10000;' src='/Images/PleaseWait.gif' />");
    $("form").append(PleaseWaitImage);
    PleaseWaitImage.fadeIn('slow');
}


function UpdateFileUploadStatus(lstMode) {

    var file = lstMode.siblings("input:file");

    if (lstMode.val() == "UPLOAD") {
        file.show();
        file.css("display", "inline");
    }
    else {
        file.hide();
    }

    return true;
}

function SelectAllRows(chkSelectAll) {
    var grid = $(chkSelectAll).closest("table");
    $("td.grid-select-checkbox input:checkbox", grid).attr("checked", chkSelectAll.checked);
}

// Function list, for window.Onload:
var OnLoadFunctions = new Object();
function RunOnLoad(func) {
    var existing = 0;
    for (method in OnLoadFunctions) existing = existing + 1;

    OnLoadFunctions[existing] = func;
}
window.onload = function () {

    for (method in OnLoadFunctions) {
        OnLoadFunctions[method]();
    }
}

RunOnLoad(SetTextboxClasses);

/* ========= Runs a specified action on startup of a page, as well as ever Ajax call back ====== */
function OnStartUp(action) {
    $(document).ready(function () { Sys.Application.add_load(action); });
}


$(document).ready(function () {
    return;
    // TODO: Debug this - accordion() must exist?!:

    $(".accordion").accordion({ header: "h3", autoHeight: false });
    $(".jtabs").tabs();
    $(".datepicker").datepicker({ showOn: 'both', buttonImage: "/Images/Icons/Calendar.png", buttonImageOnly: true });
});

$(document).ready(function () {
    $("img[HoverImageUrl]").each(function () {
        var img = $(this);
        var url = img.attr("src");
        var hover = img.attr("HoverImageUrl");
        if (hover.charAt(0) == '~') hover = hover.substring(1);

        img.mouseover(function () { this.src = hover; });
        img.focus(function () { this.src = hover; });
        img.mouseout(function () { this.src = url; });
        img.blur(function () { this.src = url; });

        preloadImages(hover);
    });
});

// Attach keywords:
var ShowAllShortkeyToolTips = false;
$(document).ready(function () {

    //var displayHelps = $("<a style=\"position:absolute; bottom:20px; right:100px;\" onclick=\"$('.divShortkeyTooltipaler').css('display', 'block');\">Show helps</a>");
    //var displayHelps = $("<a  ShortKey='Ctrl+Shift+S'>Show helps</a>");
    var displayHelps = $("<span style='display:none;'><a ShortKey='Ctrl+Shift+F1' style='display:none;'>Show helps</a></span>");
    displayHelps.click(function () {
        $('.divShortkeyTooltipaler').css('display', ShowAllShortkeyToolTips ? 'none' : 'block');
        ShowAllShortkeyToolTips = !ShowAllShortkeyToolTips;
    });
    $("form").after(displayHelps);

    $("[ShortKey]").each(function () {

        if (typeof (window["shortcut"]) != "undefined") {

            var shortKey = $(this).attr("ShortKey");
            if (shortKey == null || shortKey == '') return;

            var button = this;

            if (this.onclick)
                shortcut.add(shortKey, function () { button.onclick(); return false; });

            if (button.href)
                shortcut.add(shortKey, function () { window.location = button.href; return false; });
            else if (this.click)
                shortcut.add(shortKey, function () { button.click(); return false; });

            // Create a label to show its shortkey:
            var help = $('<div class="divShortkeyTooltipaler" style="display:none; position:absolute; background: #c1ffff; padding:1px; border:1px solid #000; filter:alpha(opacity=80);-moz-opacity:.8;opacity:.8;  zoom:1;"> <div style="border:3px dashed blue; padding:2px 5px; color: #000; letter-spacing:1px;  font-weight:bold;">' + shortKey + "</div></div>");
            $(button).before(help);
        }
    });
});

function scrollToBottom() {
    var yoffset = -3;
    while (yoffset != window.pageYOffset) {
        yoffset = window.pageYOffset;
        window.scrollBy(0, 600);
    }
}

function preloadImages() {
    for (var i = 0; i < arguments.length; i++) {
        var source = arguments[i];

        if (source.charAt(0) == '~')
            source = source.replace('~', '');

        $("<img/>").attr("src", source);
    }
}

function collapseExpandTreeViewNode(itemID) {
    //control = $(control);
    var control = $("tr[itemid='" + itemID + "']");
    var id = itemID; // control.closest("tr").attr("itemid").replace("node-", "");
    var rows = $("tr." + id, control.closest("table"));
    if (control.is(".collapsed")) {
        $("tr[collapsedfor='" + id + "']").show().removeAttr("collapsedfor");
    }
    else {
        var toHide = new Array();
        rows.each(function (index, el) { el = $(el); if (el.attr("collapsedfor") == undefined) toHide.push(el); });
        for (var i = 0; i < toHide.length; i++)
            $(toHide[i]).hide().attr("collapsedfor", id);
    }
    control.toggleClass("collapsed");
}


// Add style to sorting columns ----------------------------------
$(document).ready(ApplySortingCssClasses);
$(document).ready(function () { Sys.Application.add_load(ApplySortingCssClasses); });

function ApplySortingCssClasses() {
    $(".header-row a[href*='Sort']")
            .each(function (l) {
                var link = $(this);

                var href = link.attr("href");
                href = href.substr("javascript: __doPostBack(".length);
                href = href.substr(0, href.length - 2);
                var parts = href.split("','");

                var grid = parts[0];
                var sort = parts[1].substr("Sort$".length);

                while (grid.indexOf("\$") > -1)
                    grid = grid.replace("\$", "_");

                var currentSort = $("#" + grid).attr("CurrentSort");

                if (sort == currentSort + " DESC") {
                    // Currently ascending sorted:                    
                    link.addClass("sorted-ascending");
                }
                else if (sort + " DESC" == currentSort) {
                    link.addClass("sorted-descending");
                }

            });
}

// ========================================================================
$(document).ready(function () {
    Sys.Application.add_load(function () {

        // solve the IE bug of not firing check event properly 
        $("form input:checkbox").click(function () {
            if ($.browser.msie) {
                $(this).trigger("change").blur();
                $(this).focus();
            }
        });
    });
});

// Note: This can be implemented for supporting "warning on form cancellation"
//$("input, textarea, select").change(function() { IsFormChanged = true; });

jQuery.fn.extend({
    fire: function (evttype) {
        el = this.get(0);
        if (document.createEvent) {
            var evt = document.createEvent('HTMLEvents');
            evt.initEvent(evttype, false, false);
            el.dispatchEvent(evt);
        } else if (document.createEventObject) {
            el.fireEvent('on' + evttype);
        }
        return this;
    }
});


/* ========= Selected ============================================= */
var selectColumnsInitiallySelected;

$(document).ready(function () {
    selectColumnsInitiallySelected = $('.select-columns :checked');

    Sys.Application.add_load(function () {
        selectColumnsInitiallySelected = $('.select-columns :checked');
    });
});

function restoreSelectColumnsInitialState() {
    $('.select-columns input:checkbox').each(function (index, elem) { elem.checked = false; });
    selectColumnsInitiallySelected.each(function (index, elem) { elem.checked = true; });
}


function ExecuteAsync(action) {
    setTimeout(action, 0);
}

// ========== Client side filter ========================
function RegisterClientSideFilter(filterControlId, rowSelectorExpression) {
    $(document).ready(function () {

        var filterControl = $("#" + filterControlId);

        filterControl.keyup(function () {

            var keywords = filterControl.val().toLowerCase().split(' ');

            $(rowSelectorExpression).each(function () {

                // Skip the header row:
                if ($(this).attr("class") == "header-row") return;

                var rowContent = $(this).text().toLowerCase();
                var hasAllKeywords = true;

                for (var i in keywords) {
                    var keyword = keywords[i];
                    if (rowContent.indexOf(keyword) == -1) {
                        hasAllKeywords = false;
                        break;
                    }
                }

                if (hasAllKeywords)
                    $(this).show();
                else
                    $(this).hide();
            });

        });

    });
}







// ====================== Master Details =====================================
function MasterDetailsManager(gridId, addButtonId, minimum, maximum) {

    this.Validators = new Array();
    this.Minimum = minimum;
    this.Maximum = maximum;
    this.Grid = null;
    this.AddButton = null;

    var manager = this;

    Sys.Application.add_load(function () {
        manager.Grid = $("#" + gridId);
        manager.AddButton = $("#" + addButtonId);
    });
}

MasterDetailsManager.prototype.AddValidators = function (index, validators) {

    this.Validators[index] = new Array();

    for (i = 0; i < validators.length; i++)
        this.Validators[index][i] = document.getElementById(validators[i]);
};

MasterDetailsManager.prototype.SetVisibilities = function () {
    this.Grid.show();

    var validators = this.Validators;

    $(".record-status", this.Grid).each(
             function (i, hfStatus) {
                 hfStatus = $(hfStatus);
                 var shouldSave = (hfStatus.val() == "save");

                 if (shouldSave) hfStatus.closest('tr').show();
                 else hfStatus.closest('tr').hide();

                 for (var v = 0; v < validators[i].length; v++)
                     try {
                         var validator = $(validators[i][v]);

                         if (validator.length == 0) continue;

                         if (validator.attr('TotallyDisabled') == undefined)
                             validator.attr('TotallyDisabled', validator.get(0).enabled == false);

                         if (validator.attr('TotallyDisabled') != 'true')
                             ValidatorEnable(validator.get(0), shouldSave);
                     }
                     catch (err) { alert("Error in MasterDetailsManager.SetVisibilities: " + err.Message); }
             });

    // Set visibility for delete buttons:
    if ($(".record-status[value='save']", this.Grid).length <= this.Minimum) $(".delete-button", this.Grid).hide();
    else $(".delete-button", this.Grid).show();

    // Set visibility for Add button:
    if ($(".record-status[value='hidden']:first", this.Grid).length == 0) this.AddButton.hide();
    else if (this.Maximum > 0 && $(".record-status[value='save']", this.Grid).length >= this.Maximum) this.AddButton.hide();
    else this.AddButton.show();
};

MasterDetailsManager.prototype.AddRow = function () {

    var nextHidden = $(".record-status[value='hidden']:first", this.Grid);
    if (nextHidden.length == 0) { return false; }
    nextHidden.val("save");
    this.SetVisibilities();
    return false;
};

MasterDetailsManager.prototype.DeleteRow = function (row) {
    $(".record-status", row).val("deleted");
    this.SetVisibilities();
    return false;
};


function CreateCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function ReadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);

        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


function CollapsiblePanel_toggle(panel) {
    panel = $(panel);
    var container = panel.closest(".expand-collapse");
    container.toggleClass("expanded");
    panel.slideToggle();
}
