 /*
  initalize some global variables
*/
var gallery_images_array = new Array;
var gallery_texts_array = new Array;
var gallery_headlines_array = new Array;
var current_gallery_image = 0;


/*
  load the images from the image div into the global array
  this function should be called on body load
*/
function gallery_init(){
  // get all images from the gallery div
  if ($('gallery_images')) {
    gallery_images_array = $('gallery_images').select('img');
    gallery_headlines_array = $('gallery_images').select('h1');
    var gallery_paragraphs = $('gallery_images').select('p');
    
    var counter = -1;
    /* 
      loop over all paragraphs
      exclude all images
      exclude all headlines
    */
    for (i = 0; i < gallery_paragraphs.length; i++){
      if (gallery_paragraphs[i].select('img') != '') {
        counter++; // increment the counter
        continue; // continue the loop without doing anything -> we don't need the images
      }
      if (gallery_paragraphs[i].select('h1') != '') {
        continue; // continue the loop without doing anything -> we don't need the headlines
      }
      if (!gallery_texts_array[counter]) {
        gallery_texts_array[counter] = '';
      }
      gallery_texts_array[counter] += '<p>' + gallery_paragraphs[i].innerHTML + '</p>';
    }
        
    // get the first image for initial display
    if (gallery_images_array[0] != undefined){
      switch_gallery_image();
    } 
  } 
}

/*
  calculate the previous image array index
  take into account the edge cases (first/last)
*/
function gallery_prev(){
  if (current_gallery_image == 0) {
    current_gallery_image = (gallery_images_array.length - 1);
  } else {
    current_gallery_image--;
  }
  
  switch_gallery_image(current_gallery_image);
}

/*
  calculate the next image array index
  take into account the edge cases (first/last)  
*/
function gallery_next(){
  if (current_gallery_image == (gallery_images_array.length - 1)) {
    current_gallery_image = 0;
  } else {
    current_gallery_image++;
  }
  
  switch_gallery_image(current_gallery_image);
}

/*
  you can define the following here
  - effects to be used for the transition
  - fields to be updated with image attributes
*/
function switch_gallery_image(){
  $('gallery_headline').update(gallery_headlines_array[current_gallery_image].innerHTML);
  $('gallery_description').update(gallery_texts_array[current_gallery_image]);
  Effect.Fade('gallery_canvas', { duration: 0.5 });
  setTimeout("$('gallery_canvas').src = gallery_images_array[current_gallery_image].src", 500);
  setTimeout("Effect.Appear('gallery_canvas', {duration: 1.0})", 1000);
}

Event.observe(window, 'load', function() {
  gallery_init();
});
