/*
 * Time tracking module for GtCMS and Gt-Shop
 * 
 * @author Cezar “ikari” Pokorski
 */

var TimeTracker = {

    running: true,
    reported: false,
    time: 0,
    resolution: 100,
    timer: null,

    /* 
     * Initialization of the module. 
     * Runs on page load, starts tracking time.
     */
    init: function() {
        TimeTracker.timer = setInterval(TimeTracker.tick, TimeTracker.resolution);
        jQuery(window).bind('unload', TimeTracker.record);
        //jQuery(window).bind('beforeunload', TimeTracker.record);
        jQuery(document)
            .blur(TimeTracker.suspend)
            .focus(TimeTracker.resume);
    },
    
    /*
     * Deinit - executes when page is being left,
     * submits the recorded time to the server
     */
    record: function() {
        // this fails even when async :(
        if (!TimeTracker.reported) {
            TimeTracker.reported = true;
            jQuery.ajax({
                            url: '/_json/',
                            async: false,
                            data: {
                                "component": 'TimeTracking',
                                method: "record",
                                url: window.location.pathname,
                                milis: TimeTracker.time
                            },
                            complete: function() {
                                // callback that didn't get called
                                // console.log('time reported');
                            }
                        });
            // no sense to handle success on error,
            // since we're navingating right away anyway
        }
    },

    /*
     * Suspending if window loses focus
     */
    suspend: function() {
        TimeTracker.running = false;
    },

    resume: function() {
        TimeTracker.running = true;
    },

    tick: function() {
        if (TimeTracker.running) {
            TimeTracker.time += TimeTracker.resolution;
        }
    }
};

jQuery(window)
    .ready(TimeTracker.init);
