var OnIdle = Class.create({
    initialize: function (params) {

        this.label     = params.label;  
        this.timeout   = params.timeout * 1000;
        this.condition = params.condition;

        document.observe('state:active', this.install_timer.bindAsEventListener(this));
        document.observe(this.label, this.install_timer.bindAsEventListener(this));
        this.install_timer();
    },
    
    install_timer: function(event) {
        if (this.timer_id) {
            window.clearTimeout(this.timer_id);
        }
        this.timer_id = window.setTimeout( function() {
            if (!this.condition || (this.condition && this.condition())) {
                document.fire(this.label, this); 
            }
        }.bind(this), this.timeout);
    }
});

var ActivityDetector = Class.create({
    initialize: function() {
        var activity_events = [
            [ window, 'scroll', 'resize' ],
            [ document, 'mousemove', 'mousedown', 'keydown' ]
        ];

        activity_events.each(function(events) {
            var element = events.shift();
            events.each(function (activity_event) {
                Event.observe(element, activity_event, function(e) {
                    var now = new Date();
                    now = now.getTime();
                    // Don't fire activity events unless they are more than 0.5 seconds apart.
                    // the reason for this is that OnIdle objects reset their timers when 'state:active' is fired
                    // and since there can be N OnIdle objects, we want to minimize the performance impact
                    // this could have. Long story short, this means we have a precision of +/- 500ms to detect
                    // when the broser goes idle.
                    if (!this.last_activity || (this.last_activity && ((now - this.last_activity) > 500))) {
                        this.last_activity = now;
                        document.fire('state:active', { last_activity: now });
                    }
                }.bindAsEventListener(this));
            });
        });
    }
});

var detector = new ActivityDetector();

