// Supporting client-side code for MaxCast client web services

var MC = { // MaxCast
    baseURL : '/cms/nsmaxcast/services/',

    // error codes - needs to match services.py:Err class
    Err : {SUCCESS:0, FAILURE:1, AJAX_FAILURE:2, NO_SESSION:3, NOT_OWNER:4, NOT_FOUND:5, BAD_ARG:6, BAD_LOGIN:7, NEED_CONFIRM:8},
    ChannelStatus : {OFF:0, ON:1, NEED_MORE_MINUTES:-1},

    Init : function()
    {   // called on page load
        var params = MN.GetPageParams();
        if (params.debug)
            MN.Log.ShowPane(5000);
    },

    Call : function(api, cb)
    {   // wrapper for MN.AJAX.Post that evals the result into a JSON object first
        var wrappedCB = function(resp)
        {
            var res = {};
            if (resp.status >= 400)
                res.error = MC.Err.AJAX_FAILURE;
            else
                res = MN.EvalJSON(resp.responseText);
            res._api = api;

            // special case: if there is no session or it expired, call OnNoSession
            if (res.error == MC.Err.NO_SESSION)
                return MC.OnNoSession();

            if (cb != null)
                return cb(res);
        }

        var args = MN.ToArray(arguments).slice(2);
        if (args.length == 0)
        {   // need to send *something* since we're doing a POST
            args.unshift(0);
            args.unshift('__ignoreme');
        }
        args.unshift(wrappedCB);
        args.unshift(MC.baseURL + api);
        MN.AJAX.Post.apply(this, args);
    },

    Call2 : function(api, cb)
    {   // wrapper for MN.AJAX.Post that evals the result into a JSON object first
        var wrappedCB = function(resp)
        {
            var res = {};
            if (resp.status >= 400)
                res.error = MC.Err.AJAX_FAILURE;
            else
                res = MN.EvalJSON(resp.responseText);
            res._api = api;

            // special case: if there is no session or it expired, call OnNoSession
            if (res.error == MC.Err.NO_SESSION)
                return MC.OnNoSession();

            if (cb != null)
                return cb(res);
        }

        var args = MN.ToArray(arguments).slice(2);
        if (args.length == 0)
        {   // need to send *something* since we're doing a POST
            args.unshift(0);
            args.unshift('__ignoreme');
        }
        args.unshift(wrappedCB);
        args.unshift('/cms/nsmaxcast/ingest/' + api);
        MN.AJAX.Post.apply(this, args);
    },    

    OnNoSession : function()
    {   // called when the user has no session defined
        alert('You are not logged in or your session expired')
    }
};

MN.Event.Observe(window, 'load', MC.Init);

