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

  //resize, and keep resizing
  app.resizeApp();
  Event.observe(window, 'resize', app.resizeApp );
  
  if($('gallery')) {
    Event.observe($('nextImage'), 'click', app.loadNextImage);
    Event.observe($('gallery'), 'click', app.loadNextImage);
  }
  
  //make the image visible (it's size has been set)
  $$('#gallery img')[0].appear({duration: 0.4});
});


var app = { 
  ratio:(1200/750),
  currentImageId:0
};

app.resizeApp = function() {
  var w = document.viewport.getWidth();
  var h = document.viewport.getHeight();
  var vh = h;
  
  // resize gallery container
  $('gallery').setStyle({width: w+'px', height: h+'px'});
  
  // calculate the smallest image size that will fill the screen
  if(w/h >= app.ratio){
    h = w/app.ratio;
  } else {
    w = h * app.ratio;
  }
  
  // calculate how much of the height falls off the screen (to lift it up)
  vh = vh - h;
  
  // scale the image preserving it's aspect
  $$('#gallery img').invoke('setStyle', {width: w+'px', height: h+'px', marginTop: vh+'px'});
};

app.loadNextImage = function(e) {

	app.currentImageId++;
	if(app.currentImageId >= imageList.length) {
		app.currentImageId=0;
	}
	
	$$('#gallery img:first')[0].setStyle({opacity:0.75});
	
  //load image in bg gallery
  var im = new Element('img', {'style': 'display: none', 'alt': ''});     

  Event.observe(im, 'load', function(e){
      var ea = (e.target || e.srcElement)
      Element.extend(ea);
      ea.appear({duration: 0.4, after: function(){
      	$$('#gallery img:first')[0].remove(); //remove the previous image
      	
      }});
      app.resizeApp();
  });     
  
  $('gallery').appendChild(im);
  
  im.setAttribute('src', imageList[app.currentImageId]);

	e.preventDefault();
};
