/**
 * Diverse hjälpfunktioner till Holgerspexets hemsida Hemsidan.
 */

function toggle(element) {
        if (Element.hasClassName(element, 'hidden')) {
                show(element);
        } else {
                hide(element);
        }
}
function hide(element) {
        Element.addClassName(element, 'hidden');
}

function show(element) {
        Element.removeClassName(element, 'hidden');
}

function hideWidgets() {
        hide('widgets');
}

function showWidgets() {
        show('widgets');
}

function flashEffect() {
        new Effect.Highlight('flash', {startcolor: '#ffffff', duration: 1.0});
}

/**
 * Hash-länkar som <a href="#foobar">Link</a> fungerar inte bra
 * tillsammans med den nuvarande sidlayouten i alla webbläsare.  Följande
 * funktion scrollar till rätt del av sidan i stället för att följa
 * länken, vilket fungerar bättre.  Se #183 för detaljer.
 */
function initializeScrollLinks() {
    forEach($$('a.scroll'),
	    function (link) {
		Event.observe(link, 'click',
			      function (e) {
				  var domId = this.href.split("#")[1];
				  var target = $(domId);
				  if (target) {
				      target.scrollTo();
				      e.stop();
				  }
			      });
	    }
    );
}

Event.observe(window, 'load', flashEffect);
Event.observe(window, 'load', initializeScrollLinks);

var BackoffPeriodicalExecuter = Class.create();
BackoffPeriodicalExecuter.prototype = {
  initialize: function(callback, delays) {
    this.callback = callback;
    this.delays = delays;
    this.delay = this.delays.shift();

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearTimeout(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    try {
      this.callback(this);
    } finally {
      this.timer = null;
      if (this.delays.length > 0) {
        this.delay = this.delays.shift();
      }
      this.registerCallback();
    }
  }
}
