// **************************
var gallery = {

  entries:[],
  running:false,
  delay:3500,
  fadeOutType:'slow',
  fadeInType:'slow',
  idGalleryContainer:'imgGallery',
  idGalleryImage:'imgGallery_Image',

  currentIndex:0,
  htmlImage:'<img id="imgGallery" />',
  
  setIdGalleryContainer: function(str) {
      this.idGalleryContainer = str;
      var idImage = str + '_Image';
      this.idGalleryImage = idImage;
      this.htmlImage = '<img id="' + idImage +  '" src="[src]" />';
      //debugObj(this, '*** [setIdGalleryContainer]:' + str);
  },
    
  addUrl: function (url) {
    debug('[addUrl]:' + url);
    var newImage = new Image();
    var entry = {url:url, image:newImage};
    newImage.onload=function() {
        debug('  *** Just loaded image, adding:' + url);
        gallery.entries.push(entry);
        gallery.entries.sort(function(a, b) {
            //debug((a.url > b.url) + ', ' + a.url + ', ' + b.url);
            return (a.url > b.url);
          });
        var arrUrls = [];
        for(var i=0;i<gallery.entries.length;i++) {
          arrUrls.push(gallery.entries[i].url);
        }
        //debug('Sorted:' + arrUrls);
      };
    newImage.src = url;
  },
  
  run:function() {
    this.showImage(0);
  },
  
  showNextImage: function() {
    var gallery = this;
    $('#' + gallery.idGalleryImage).fadeOut(this.fadeOutType, function() {
        var n = gallery.currentIndex + 1;
        if(n >= (gallery.entries.length)) {
          n = 0;
        }
        gallery.currentIndex = n;
        gallery.showImage(n);
      });


  },
  
  showImage: function(n) {
    this.currentIndex = n;
    if(this.entries.length == 0) {
      debug('.');
      setTimeout('gallery.showImage(' + n + ')', 50);
      return;
    }
    if(!this.running) { 
      var str = this.htmlImage;
      str = str.replace('[src]', this.entries[n].url);
      $('#' + this.idGalleryContainer).html(str);
      this.running = true;
    } else {
      var img=document.getElementById(this.idGalleryImage);
      debug('image:' + this.entries[n].url);
      img.src = this.entries[n].url;
    }
    $('#' + this.idGalleryImage).fadeIn(this.fadeInType);
    setTimeout("gallery.showNextImage()", this.delay);
  } // end func showImage
}
