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();
    
    //if (cssClass == null || cssClass == '' || cssClass == undefined)
    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);

    //x().document.write("<img src=\"/images/spinner.gif\"/>");


    _CurrentModalFrame.attr("src", url);

    _CurrentModalFrame.attr("parentWidth", $(window).width());
    _CurrentModalFrame.attr("parentHeight", $(window).height());
    _CurrentModalFrame.attr("parentScroll", $(window).scrollTop());
    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;
    }
    // Create DL and DD
    //var dl = $("<span class=\"modal-wrapper1\" />");
    //_CurrentPopupBox.append(dl);
    //var dd = $("<dd />");
    //dl.append(dd);
    parent.append(_CurrentModalFrame);
    //dd.append(_CurrentModalFrame);
    //_CurrentModalFrame.css("visibility", 'visible');

    // Create new cover:
    _CurrentModalCover = $("<div class='modal-cover'>&nbsp;</div>");
    //_CurrentModalCover.append($(""));
    //_CurrentModalCover.addClass("");
    _CurrentModalCover.width($(window).width() * 2);
    _CurrentModalCover.height($(window).height() * 2);
    // 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 {
        $(document.body).css("overflow", "hidden");
    }

    // hide items
    _CurrentModalCover.hide();
    _CurrentPopupBox.hide();

    // Add all to the body:     
    $('form').append(_CurrentPopupBox);
    $('form').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 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;

    var document = iFrame.get(0).contentWindow.document;

    // 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 = $(document.body).width(); //+ 10;
    var actualContentHeight = $(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");
        $(document.body).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 ShowPleaseWait(blockScreen) {
    var image = document.createElement("img");

    image.style.position = "absolute";
    image.style.left = 0;
    image.style.top = 0;
    image.style.margin = '30% 50% 50% 50%';
    image.style.zIndex = 100;
    image.setAttribute("src", "/Images/PleaseWait.gif");

    document.getElementById('aspnetForm').appendChild(image);

    if (blockScreen) {
        var cover = $("<div class='modal-cover'>&nbsp;</div>");
        cover.width($(window).width() * 2);
        cover.height($(window).height() * 2);
        cover.css("display", "block");

        $(document.getElementById('aspnetForm')).append(cover);
    }
}


function UpdateFileUploadStatus(lstMode, fileUploadControlId) {
    var prefix = lstMode.getAttribute('id').substring(0, lstMode.getAttribute('name').lastIndexOf("$") + 1);
    var file = document.getElementById(prefix + fileUploadControlId);

    if (lstMode.selectedIndex == 1 && file.style.display == 'none')
        file.style.display = '';
    else
        file.style.display = 'none';

    return true;
}

function SelectAllRows(chkSelectAll) {
    var grid = $(chkSelectAll).closest("table");
    $("td.grid-select-checkbox :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);


$(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() {

        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);
    }
}


// Add style to sorting columns ----------------------------------
$(document).ready(function() {
    Sys.Application.add_load(
        function() {
            $(".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.attr("class", "sorted-ascending");
                }
                else if (sort + " DESC" == currentSort) {
                    link.attr("class", "sorted-descending");
                }

            });
        });
});


// MessageBox support for Update panel ========================================================================
$(document).ready(function() {

    Sys.Application.add_load(ShowUpdatePanelMessageBox);

    function ShowUpdatePanelMessageBox() {
        // Find the latest Message box command. Each messagebox command is specified in a special hidden field:
        var message = null;
        var latest = -1;
        // Find message box:
        $('input[type="hidden"][MessageBox="true"]').each(function() {
            var command = $(this);

            var version = parseFloat(command.attr("Version"));
            if (version > latest) {
                latest = version;
                message = command.attr("Message");

                // Set done to true:
                command.val("true");
            }
        });

        if (message)
            alert(message);
    }
});
// ========================================================================
$(document).ready(function() {
    Sys.Application.add_load(function() {

        // solve the IE bug of not firing check event properly 
        $("form :checkbox").click(function() {
            if ($.browser.msie) {
                $(this).fire("change").blur();
                $(this).focus();
            }
        });
    });
});

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;
    }
});