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;
var _IsPageLoaded = false;

$(function ()
{
    $.browser.iphone = (navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1);
    $.browser.ipad = navigator.platform.indexOf("iPad") != -1;
});

function OpenModal(url, openEffect, width, height)
{
    // Ensure it runs after page load:
    if (_IsPageLoaded)
        GetOpenModal(url, openEffect, width, height);
    else
        Sys.Application.add_load(function () { GetOpenModal(url, openEffect, width, height); });
}

function GetOpenModal(url, openEffect, width, height)
{
    CloseModal(false);

    $(".popup-blocker").hide();

    var cssClass = 'defaultModal';

    if ($.browser.msie) { ; /* IE has problem with setting overflow.*/ }
    else { $("body").css("overflow", "hidden"); }

    // Create a box and Iframe:
    _CurrentPopupBox = $('<div style="position:absolute;" />')
        .addClass(cssClass);

    _CurrentModalFrame = $("<iframe frameborder='0' />")
        .css("visibility", 'hidden')
        .attr('ALLOWTRANSPARENCY', 'true')
        .attr("src", url);

    InitializeFrameSize(width, 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>")
        .width(FindMaximumPageWidth())
        .height(FindMaximumPageHeight());

    // in the next code 50 is the half of the spinner image width (height)
    _CurrentModalCover.css("backgroundPosition", ($(window).width() / 2 - 50) + "px " + ($(window).height() / 2 - 50) + "px")
        .css("top", $(window).scrollTop() + "px").css("left", $(window).scrollLeft() + "px");


    $(window).scroll(function ()
    {
        if ($.browser.ipad || jQuery.browser.mobile) return;
        if (_CurrentModalCover)
        {
            _CurrentModalCover.css("top", $(window).scrollTop() + "px");
            _CurrentModalFrame.css("top", (($(window).height() - _CurrentModalFrame.height()) / 2 + $(window).scrollTop()) + "px");
        }
    });

    $(window).resize(function ()
    {
        if (_CurrentModalCover)
        {
            _CurrentModalCover.css({ width: $(window).width(), height: $(window).height() });
        }

        if (_CurrentModalFrame.attr("IsModalWindowOpened") == "true")
        {
            InitializeFrameSize();
            AdjustFrameSize();
            $(document).trigger("afterModalResize");
        }
    });


    // hide items
    _CurrentModalCover.hide();
    _CurrentPopupBox.hide();

    // Add all to the body:
    $(document.body).append(_CurrentPopupBox);
    $(document.body).append(_CurrentModalCover);

    // show items
    $(document).trigger("beforeModalShow");
    _CurrentModalCover.css("filter", "alpha(opacity=60)")
                        .fadeIn(100);
    _CurrentPopupBox.css("top", 0)
                    .css("left", 0)
                    .show();


    _CurrentModalFrame.ready(InitializeModalPage)
                      .hide()
                      .load(AdjustFrameSize)
                      .load(function () { $(document).trigger("afterModalShow"); });


    return _CurrentModalFrame;
}

function InitializeFrameSize(width, height)
{
    if (_CurrentModalFrame == null) return;

    if (width) _CurrentModalFrame.css("width", width);
    if (height) _CurrentModalFrame.css("height", height);

    _CurrentModalFrame.attr("parentWidth", $(window).width())
                      .attr("parentHeight", $(window).height())
                      .attr("parentScroll", $(window).scrollTop())
                      .attr("parentHScroll", $(window).scrollLeft());

    if (width) _CurrentModalFrame.attr("specifiedWidth", width);
    if (height) _CurrentModalFrame.attr("specifiedHeight", height);
}

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 iframeTopBorderWidth = parseInt(iFrame.css("border-top-width").replace("px", "")) | 0;
    var iframeBottomBorderWidth = parseInt(iFrame.css("border-bottom-width").replace("px", "")) | 0;

    var parentWidth = parseInt(iFrame.attr("parentWidth"));
    var parentHeight = parseInt(iFrame.attr("parentHeight")) - margin - iframeTopBorderWidth - iframeBottomBorderWidth;
    var parentScroll = parseInt(iFrame.attr("parentScroll"));
    var parentHScroll = parseInt(iFrame.attr("parentHScroll"));

    // 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;
    left += parentHScroll;

    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");
        $("body").css("overflow", "auto");
    }

    if (closeEffect == undefined) closeEffect = "fade";

    if (_CurrentModalFrame)
    {

        if (_CurrentModalFrame.attr("isLoaded") != "false") $(document).trigger("beforeModalClose");
        _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)
    {
        _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';

    // 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 { $('.modal-cover').remove(); 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' class='please-wait-image' />");
    $("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 ==============================================:
//# OLD #####################################
//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](); }
// \OLD #####################################

function RunOnLoad(func)
{
    var uniqueID = new Date().getTime();
    var functionName = "m_" + uniqueID;
    var done = false;

    window[functionName] = function ()
    {
        $(document).unbind("ready." + uniqueID);
        if ('Sys' in window) Sys.Application.remove_load(window[functionName]);

        if (done) return;
        done = true;
        func.call();
    };
    $(document).bind("ready." + uniqueID, window[functionName]);
    if ('Sys' in window) Sys.Application.add_load(window[functionName]);
}


RunOnLoad(SetTextboxClasses);

/* ========= Runs a specified action on startup of a page, as well as ever Ajax call back ====== */
function OnStartUp(action)
{
    if (typeof (window["Sys"]) == "undefined")
    {
        $(document).ready(function () { Sys.Application.add_load(action); });

    }
    else
    {
        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 = link.closest("table");
                var sort = parts[1].substr("Sort$".length);


                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();
            }
        });
    });
});

function getQueryString(key)
{
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + key + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}


// 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();
            });

        }).keydown(function (e)
        {
            if (e.keyCode == 13) e.preventDefault();
        });

    });
}







// ====================== 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);
    });

    // Also try once immediately (needed in some complex scenarios):
    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 ()
{

    if (this.Grid)
        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')
                             validator.get(0).enabled = shouldSave;
                         // 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;
};

/* ================================  COOKIES ====================================== */

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();
}

// ========= collapsible panel =========================
function collapsiblePanel_initialize(link)
{
    link.unbind("click.collapse").bind("click.collapse", collapsiblePanel_click);
    collapsiblePanel_refreshState(link);
}

function collapsiblePanel_refreshState(link)
{
    link = $(link);

    var hiddenField = link.siblings("input[type=hidden]");
    var groupSearchPanel = link.siblings(".collapsed-body");
    var groupSearchIcon = link.siblings("img");

    if (hiddenField.val().toLowerCase() == "true")
    {
        groupSearchPanel.slideUp("fast");
        groupSearchIcon.attr("src", "/images/icons/expand.gif");
    }
    else
    {
        groupSearchPanel.slideDown("fast");
        groupSearchIcon.attr("src", "/images/icons/collapse.gif");
    }
}

function collapsiblePanel_click()
{
    link = $(this);
    var hiddenField = link.siblings("input[type=hidden]");
    var box = link.siblings(".collapsed-body");
    hiddenField.val(box.is(":visible"));
    collapsiblePanel_refreshState(link);
}

function HighlightTableRow(link)
{
    $(link).closest('tr').siblings('tr').removeClass('selected');
    $(link).closest('tr').addClass('selected');
}


// ------------------------ Ajax Update Panel | FileUpload problem -----------
$(document).ready(function ()
{
    Sys.Application.add_load(ajaxFileUploadFix_init);
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(ajaxRequest_began);
});

function ajaxFileUploadFix_init()
{
    // bring back fus from reservoir
    var fuReservoir = getFileUploadReservoir();
    fuReservoir.find(":file").each(function (index, fileElement)
    {
        fileElement = $(fileElement);
        var realFileElement = $('#' + fileElement.attr("originalID"));
        if (realFileElement.length == 1)
        {
            fileElement.insertBefore(realFileElement);
            realFileElement.remove();
            fileElement.attr("id", fileElement.attr("originalID"));
        }
    });
};

function getFileUploadReservoir()
{
    var fuReservoir = $("#fuReservoir");
    if (fuReservoir.length == 0)
    {
        fuReservoir = $("<div id='fuReservoir' />").hide();
        $(document.body).append(fuReservoir);
    }
    return fuReservoir;
}

function fileUpload_addToReservoir(index, fu)
{
    var fu = $(fu);
    var fuID = fu.attr("id");
    var fuReservoir = getFileUploadReservoir();

    // remove if any already there
    fuReservoir.find(":file[originalID=" + fuID + "]").remove();

    //keep a clone of the fu control (without the file)
    fu.clone().insertAfter(fu);

    // add to reservoir
    fu.appendTo(fuReservoir).attr("id", fuID + "_copy").attr("originalID", fuID);
}

function ajaxRequest_began()
{
    $("[isUpdatePanel] :file").each(fileUpload_addToReservoir);
}

// ------------------------ Ajax Update Panel | Preserve Scroll -----------
$(document).ready(function ()
{
    Sys.Application.add_load(preserveScroll_init);
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(preserveScroll_store);
});

function preserveScroll_store()
{
    var body = $(document.body);
    body.attr("scrollTopPreserved", $(window).scrollTop());
}

function preserveScroll_init()
{
    var body = $(document.body).filter("[scrollTopPreserved]");
    if (body.length > 0)
    {
        var scroll = parseInt(body.attr("scrollTopPreserved"));
        $("html, body").animate({ scrollTop: scroll }, 1);
    }
}


$.fn.exlusiveCheckboxes = function ()
{
    var chks = $(this).find("input:checkbox").andSelf().filter("input:checkbox");
    chks.change(function ()
    {
        if (this.checked)
        {
            for (var i = 0; i < chks.length; i++)
            {
                var c = chks.get(i);
                if (c != this) c.checked = false;
            }
        }
    });
};

RunOnLoad(function () { _IsPageLoaded = true; });


/*=============== Gentle Alert =======================*/
var GENTLE_ALERT_DEFAULT_BOX_STYLES = 'display:none; position:fixed; top:0; font-size: 16px; padding: 15px 0; width: 100%; border-bottom: 1px solid #333; background-color: #FCF5D4; color: #260D0D; text-align: center; font-weight: bold;';
var GENTLE_ALERT_DEFAULT_BUTTON_STYLES = 'float:right; text-decoration:none; margin-right:30px; background:#fff; font-size:10pt; border:1px solid #555; padding:4px 10px;';
var GENTLE_ALERT_FADE_IN_DURATION = 800;
var GENTLE_ALERT_FADE_OUT_DURATION = 1000;
var GENTLE_ALERT_WAIT_PER_CHARACTER = 100;
var GENTLE_ALERT_WAIT_MINIMUM = 2500;

function alertGently(message)
{
    var wait = message.length * GENTLE_ALERT_WAIT_PER_CHARACTER;
    if (wait < GENTLE_ALERT_WAIT_MINIMUM) wait = GENTLE_ALERT_WAIT_MINIMUM;

    $(document.body).append('<div id="gentle-alert-info-bar" style="' + GENTLE_ALERT_DEFAULT_BOX_STYLES + '">' + message + '</div>');
    $("<a id='gentle-alert-ok-button' style='" + GENTLE_ALERT_DEFAULT_BUTTON_STYLES + "'>OK</a>")
    .prependTo($('#gentle-alert-info-bar'))
    .click(function () { $('#gentle-alert-info-bar').fadeOut(GENTLE_ALERT_FADE_OUT_DURATION / 2); });


    $('#gentle-alert-info-bar').fadeIn(GENTLE_ALERT_FADE_IN_DURATION,
        function ()
        {
            setTimeout(function () { $('#gentle-alert-info-bar').fadeOut(GENTLE_ALERT_FADE_OUT_DURATION); }, wait);
        });
}
