/*
 * periodical excecuter class from prototype javascript library
 * prototype independent version by: Peter Porfy
 * 
 * snippets from Prototype lib for PE functionality
 */
var slice = Array.prototype.slice;
function merge(array, args) {
    array = slice.call(array, 0);
    return update(array, args);
  }

function update(array, args) {
    var arrayLength = array.length, length = args.length;
    while (length--) array[arrayLength + length] = args[length];
    return array;
}

Function.prototype.bind = function(context) {
    if (arguments.length < 2 && typeof arguments[0] === "undefined") return this;
    var __method = this, args = slice.call(arguments, 1);
    return function() {
      var a = merge(args, arguments);
      return __method.apply(context, a);
    }
 }


function PeriodicalExcecuter(callback, frequency) {
	this.registerCallback = function() {
		this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
	};
	
	this.onTimerEvent = function() { 
		if (!this.currentlyExecuting) {
	      try {
	          this.currentlyExecuting = true;
	          this.execute();
	          this.currentlyExecuting = false;
	        } catch(e) {
	          this.currentlyExecuting = false;
	          throw e;
	        }
	      }
	};

	this.execute = function() { 
	//	alert(this.callback);
		this.callback(this);
	};
	
	this.stop = function() {
		if(!this.timer) return;
		clearInterval(this.timer);
		this.timer = null;
	};
	
	this.callback = callback;
	this.frequency = frequency;
	this.currentlyExecuting = false;
	this.registerCallback();
	
	
}
