/**
 * A JavaScript implementation of a <meta> refresh that will allow external
 * stopping and restarting via public methods.
 *
 * First implemented on Live Look-In to prevent page refresh from interrupting
 * video playback.
 * 
 * @TODO Proper comments on methods
 * @TODO Supplement isRefresh with a count of number of refreshes
 *
 * @author David Furfero <david.furfero@mlb.com>
 * @version 1.0
 */
(function() {

	bam.imports(bam.cookies);
	
	
	/**
	 * PageRefresh class 
	 *
	 * @class
	 * @param {Number} seconds Time until page refresh (in seconds)
	 * @constructor
	 * @author David Furfero <david.furfero@mlb.com>
	 * @version 1.0
	 */
	var PageRefresh = function(seconds) {
	  
	  this.interval = seconds * 1000; // Convert interval seconds to ms

    /**
     * Determine whether or not page has previously been refreshed
     */
	  var uid = this.getPageId();
	  
	  this.isRefresh = !!bam.cookies.get(uid);
	  
	  if (this.isRefresh) {
	    bam.cookies.remove(uid);
	  }
	  
	  this.start();
	};
	
	PageRefresh.prototype = {
    
    /**
     * Generates unique cookie key based on location.href
     */
	  getPageId: function() {
	    return 'P_' + parseInt(escape(location.href).replace(/\W+/g, ''), 36).toString(16).substr(0, 14);
	  },

	  /**
	   * Refreshes the page
	   */
	  refresh: function() {

	    // Stop timer
  	  this.stop();

	    var uid = this.getPageId(),
	        now = new Date(),
	        exp = new Date(now.getTime() + 120 * 1000);

      // Set temporary cookie 
  	  bam.cookies.set({
  	    name:     uid,
  	    value:    '1',
  	    expires:  exp
  	  });

      // Reload page
  	  location.reload();
	  },
	  
	  start: function() {
  	  var that = this;
  	  this._timer = setTimeout(function() {
  	    that.refresh();
  	  }, this.interval);
	  },
	  
	  stop: function() {
	    clearTimeout(this._timer);
	    this._timer = null;
	  }
	};


  /**
   * Add to bam utility namespace
   */
  bam.util = bam.util || {};
  bam.util.PageRefresh = PageRefresh;

})();
