 /*
     $Revision$
     $Id$

    File:               notify.js
    Description:
    Parameters:
    Context:
    Note:
*/

var notify_url = "notify.asp";
//var notify_url = "http://logc.facws001.sg.nl/trunk/appl/chat/notify.asp";
//var notify_url = "https://demo.facilitorlabs.nl/appl/chat/notify.asp"; // Pas wel op voor CORS gezeur...

var CHECKTIME = 1500; // milliseconde voor een actieve chat

var notify =
{
    timeoutTimer: null,
    callback: null,
    channelId: null,
    params: null,
    chatSendchannelId: null,

    signal: function _signal (signalchannelId, message)
    {
        $.post(notify_url + "?action=signal&channelId=" + signalchannelId + (message?"&msg=" + message:"")); // Signal new message
    },
    end: function _end (channelId, fromchannelId, message)
    {
        $.post(notify_url + "?action=end&channelId=" + channelId + "&fromchannelId=" + fromchannelId + (message?"&msg=" + message:"")); // Signal end of chat
        notify.stopwait();
    },
    stopwait: function _stopwait ()
    {
        clearTimeout(notify.timeoutTimer);
    },
    wait: function _wait (channelId, sendChannelId, fnCallback, params)
    {
        params = params || {};
        notify.chatSendchannelId = sendChannelId;
        notify.callback = fnCallback;
        notify.channelId = channelId;
        notify.params = params;
        notify.start = new Date();
        if (params.alwaysafter > 0)
        {
            notify.alwaysaftertime = new Date();
            notify.alwaysaftertime.setSeconds(notify.alwaysaftertime.getSeconds() + params.alwaysafter)
        }
        notify.check();
    },
    check: function ()
    {
        if (notify.alwaysaftertime && new Date() > notify.alwaysaftertime)
        {
            notify.callback({}); // altijd dummy data
        }
        else
            $.getJSON(notify_url + "?action=check&channelId=" + notify.channelId
                + (notify.chatSendchannelId ? "&sendchannelId=" + notify.chatSendchannelId : ""), notify.process_notify);
    },
    process_notify: function(data)
    {
        clearTimeout(notify.timeoutTimer);
        if (data && data.message)
            notify.callback(data);
        else if (data && ("last_alive" in data || "end" in data))
        {
            if (notify.callback(data))
                notify.timeoutTimer = setTimeout(notify.check, CHECKTIME);
        }
        else
            notify.timeoutTimer = setTimeout(notify.check, CHECKTIME);
    }
};

