if (!console) var console = { log: function(){} }

// Loop of morphs
function home_morph_loop(max, seconds) {
  setTimeout(function() {
    fade_illustrations(max, home_morph_loop.curry(max, seconds))
  }, seconds*1000)
}

// Fade-out the current photo, then fade-in the next by creating a temporary .illustration2
// Start again at photo number 1 when max is reached
function fade_illustrations(max, callback) {
  var illustration = $('contenu').down('.illustration')
  $('contenu').insert('<div class="illustration tmp"></div>')
  var illustration2 = $('contenu').down('.tmp')

  illustration2.setStyle({ backgroundImage:illustration.getStyle('background-image') })
  illustration.increment_background_image(max)

  new Effect.Fade(illustration2, {
    duration: 2,
    afterFinish: function() {
      illustration2.remove()
      new Effect.Appear(illustration, { duration: 2 })
      callback()
    }
  })
}

// Changes the background-image property to the next image if the image is
// in the style: name1.jpg, name2.jpg, etc. Starts back at 1 when max is reached.
// Example:
//   $('foo').style.backgroundImage = "url(foo1.jpg)"
//   $('foo').increment_background_image(5)
//   $('foo').style.backgroundImage # => "url(foo2.jpg)"
Element.addMethods({
  increment_background_image: function(element, max) {
    var style = $(element).getStyle('background-image')
    var image_re = /([0-9]+)\.jpg/
    var current = parseInt(style.match(image_re)[1], 10)
    var next = (current == max) ? 1 : current + 1;
    $(element).setStyle({
      backgroundImage: style.replace(image_re, next + '.jpg')
    })
  }
})

// Moves the first element in an array to the end
// Example: [1, 2, 3, 4].enqueue() # => [2, 3, 4, 1]
Array.prototype.enqueue = function() {
  this.push(this.splice(0, 1)[0]);
  return this;
}


$(document).observe('dom:loaded', function() {

 if ($('page-accueil'))
  home_morph_loop(4, 2)

  Event.observe(window, 'load', function() {
      $$('a[rel="external"]').each(function(link){
          if(link.readAttribute('href') != '' && link.readAttribute('href') != '#'){
              link.writeAttribute('target','_blank');
          }
      });
  });

})