﻿/* © mySupermarket Limited, 2005-2010. All rights reserved. */

MSBICS.AjaxManager = new Object();

MSBICS.AjaxManager.InitErrorHandler = function()
{
    $.ajaxSetup({
        error: function(x, e)
        {
            if (x.status == 500)
            {
                window.location.href = "/Errors/Error.aspx?Handled=true";
            }
        }
    });
}

MSBICS.AjaxManager.UserControls = new Object();

MSBICS.AjaxManager.UserControls.Update = function(iControlContainerWrapped, iQueryParamsObject, iShowPageProgress, iScrollToTop)
{
    var classNames = iControlContainerWrapped.getClassNames();
    MSBICS.AjaxManager.UserControls.SwitchWith(iControlContainerWrapped, classNames[0], iQueryParamsObject, iShowPageProgress, iScrollToTop)
}

MSBICS.AjaxManager.UserControls.SwitchWith = function(iControlContainerWrapped, iClassNameToFetch, iQueryParamsObject, iShowPageProgress, iScrollToTop)
{
    var controlID = MSBICS.UserConrolsResources[iClassNameToFetch];
    var url = MSBICS.PageResources.Ajax_UpdateUserControl + "?" +
        MSBICS.QueryParamKeys.UserControlKey + "=" + controlID;


    if (iQueryParamsObject != null)
    {
        for (key in iQueryParamsObject)
        {
            url += "&" + key + "=" + iQueryParamsObject[key];
        }
    }

    if (iShowPageProgress)
    {
        MSBICS.UserControls.Mask.BlockPage();
    }

    $.ajax({
        url: url,
        type: "POST",
        dataType: "html",
        complete: function(res, status)
        {
            if (status == "success" || status == "notmodified")
            {
                iControlContainerWrapped.empty().before(res.responseText).remove();
            }

            if (iShowPageProgress)
            {
                MSBICS.UserControls.Mask.UnBlockPage();
            }

            if (iScrollToTop)
            {
                window.scroll(0, 0);
            }
        }
    });
}

MSBICS.AjaxManager.UserControls.SilentFetch = function (iClassNameToFetch, iQueryParamsObject, iOnComplete)
{
    var controlID = MSBICS.UserConrolsResources[iClassNameToFetch];
    var url = MSBICS.PageResources.Ajax_UpdateUserControl + "?" +
        MSBICS.QueryParamKeys.UserControlKey + "=" + controlID;

    if (iQueryParamsObject != null)
    {
        for (key in iQueryParamsObject)
        {
            url += "&" + key + "=" + iQueryParamsObject[key];
        }
    }

    $.ajax({
        url: url,
        type: "POST",
        dataType: "html",
        complete: iOnComplete
    });
}
