
if (typeof(Prototype) === 'undefined') {
    // Missing required class Prototype.
    throw 'Missing required class: Prototype';
}

if (typeof(SDS) === "undefined") { SDS = {}; };

// Find more documentation for this class at:
// http://wiki.stratusdata.com/doku.php?id=tools:javascript:session_timeout_warning

//
// Instances of this class produce warning dialogs notifying the user about
// various events. The user has the option to cancel or confirm activities
// via this dialog. This class is agnostic of the effect of the user actions
// or the purpose of the timer.
//
SDS.TimeoutWarning = Class.create({
    // Initializes a new TimeoutWarning object. The object will produce a
    // confirmation dialog at the end of the specified timeout period.
    initialize: function(timeout, message, confirmUrl, cancelUrl) {
        // Create a reference to the current object for use by the timeout
        // function.
        var self = this;

        // Store the parameters in this object.
        this.timeout = timeout;
        this.message = message;
        this.confirmUrl = confirmUrl;
        this.cancelUrl = cancelUrl;

        // Produce a unique identifier for the timeout function.
        var uniqueFunctionId = 'timeoutWarning_' + new Date().getTime();
        this.timeoutFunctionCall = uniqueFunctionId + '()';

        // Create the unique timeout function.
        window[uniqueFunctionId] = function() {
            // The confirmation dialog will dispatch events itself
            // and possibly re-arm the countdown.
            self.confirmDialog();
        };

        // Automatically activate this object.
        this.activate();
    },

    // Runs the confirm dialog. By default, this uses the JavaScript confirm
    // function.
    confirmDialog: function() {
        // By default, use the built-in JavaScript dialog.
        var result = confirm(this.message);
        // Activate the event handler corresponding to the user choice.
        if (result) {
            this.onConfirm();
        } else {
            this.onCancel();
        }
    },

    // Activates this object, in effect beginning a countdown.
    activate: function() {
        this.timeoutId = setTimeout(this.timeoutFunctionCall, this.timeout);
    },

    // Cancels the countdown.
    cancel: function() {
        clearTimeout(this.timeoutId);
    },

    // Handles a confirmation event, corresponding to the selection of the
    // OK button by the user.
    onConfirm: function() {
        // Send an AJAX request to the confirm URL.
        new Ajax.Request(this.confirmUrl);
        this.activate();
    },

    // Handles a cancel event, corresponding to the selection of the
    // Cancel button by the user.
    onCancel: function() {
        // Redirect the browser to the cancel URL.
        window.location.href = this.cancelUrl;
    }
});
