var galleries = [];
var fundGal = null;
var firstGal;
function parseXML(data) {
  $('gallery', data).each(function(id, val){
    var gallery = {
      name: $(this).children('name').text(),
      url: $(this).children('url').text(),
      slides: []
    }
    $(this).find('slides>slide').each(function() {
      //calculate thumb src
      var thumbSrc = $(this).find('img').eq(0).attr('src').split('/');
      thumbSrc[thumbSrc.length - 2] += '/thumbs';
      thumbSrc = thumbSrc.join('/');
      //thumbSrc = thumbSrc.replace('.jpg', '_t.jpg');
      //set slide attrs
      var slide = { src: $(this).find('img').eq(0).attr('src'), thumbSrc: thumbSrc };
      slide.caption = $(this).find('caption').text() || false;
      gallery.slides.push(slide);
    });
    galleries[gallery.url] = gallery;
    if (id == 0) {
      firstGal = gallery.url;
    }
  });
  fundGal = new Gallery();
  $.historyInit(loadGal);
  if ($.historyCurrentHash == '' || $.historyCurrentHash == '#') {
    $.historyLoad(firstGal);
  }
  //$.historyLoad(firstGal);
  $('a.galleryLink').click(function(){
    $.historyLoad($(this).attr('href').replace('#', ''));
    var targetOffset = $('a[name=gallery]:eq(0)').offset().top - 10;
    $('html,body').animate({scrollTop: targetOffset}, 1000);
  });
}
$(document).ready(function() {
  $.get("galleries.xml", function(data) {
    parseXML(data);
  });
});
function loadGal(hash) {
  fundGal.loadGallery(hash);
}
function Gallery() {
  var images = new Array();
  var preloadMax = 4;
  options = typeof(options) == 'undefined' ? {} : options;
  var thumbCount = 0;
  var defaults = {
    thumbs: true
  };
  var thumbDim = {x:100 , y:67 }
  var galDim = {x:587, y: 320}
  var curGal = null;
  var curImg = null;
  
  var errorImg = new Image();
  errorImg.src = "/images/ui/image-error.png";
  errorImg.width = 500;
  errorImg.height = 310;
  var scrollable = null;
  
  var errorThumbImg = new Image();
  errorThumbImg.src = "/images/ui/thumb-error.png";
  errorThumbImg.width = 100;
  errorThumbImg.height = 67;
  
  var opts = $.extend({}, defaults, options);
  
  function preloadImages(i) {
    i = i || 0;
    var img = new Image();
    $(img).bind('load', {index: i}, imageOnLoad);
    $(img).load(function(){
       preloadNextImage(i+1);
     }).one('error', function(){
       $('#'+i+'-slide').empty().append(errorImg).children('img').eq(0).data('complete', true);
       curGal.slides[i].error = true;
       preloadNextImage(i+1);
     });
    img.src = curGal.slides[i].src;
    $(img).appendTo($('#'+i+'-slide'));

  }
  function preloadNextImage(i) {
    var pMax = preloadMax > curGal.slides.length-1 ? curGal.slides.length-1 : preloadMax; 
    if (i < pMax) {
      preloadImages(i);
    }
    else {
      preloadThumbs();
    }
  }
  function preloadThumbs(index) {
    index = index || 0;
    if (opts.thumbs) {
      var img = new Image();
     $(img).load(function(){
      $('#preCount').empty().append(index + 1);
       curGal.slides[index].thumbWidth = this.width;
       curGal.slides[index].thumbHeight = this.height;
       preloadNextThumb(index+1);
     });
     $(img).one('error', function(){ 
       curGal.slides[index].thumbError = true;
       preloadNextThumb(index+1);
      });
      img.src = curGal.slides[index].thumbSrc;
    }
    else {
      preloadComplete();
    } 
  }
  
  function preloadNextThumb(i) {
    if (i < curGal.slides.length) {
     preloadThumbs(i);
    }
    else {
      preloadComplete();
    }
  }
  
  function preloadComplete(){
    //start the slideshow
     $('#slideshow').cycle({
        pager: '#thumbScroll',
        pagerAnchorBuilder: opts.thumbs ? pagerFactory : null,
        prev: '#prev',
        next: '#next',
        prevNextClick: prevNext,
        pagerClick: pagerClick,
        timeout: 0
      });
      $('#galLoad').fadeOut(500);
      $('#preloadInd').css('display', 'none');
      if (!scrollable) {
        scrollable = $('#thumbs').scrollable({
            size: 5,
            clickable: false,
            api: true
        });
      }
      else {
        scrollable.begin();
      }
      updateCounter(0);
  }
  /*add the thumbnails*/
  function pagerFactory(idx, slide) {
    var thumbSrc = curGal.slides[idx].thumbError ? errorThumbImg.src : curGal.slides[idx].thumbSrc;
    var attrs = '';
    //scale thumbnails if they are too big
    if (typeof(curGal.slides[idx].thumbWidth) != 'undefined' && typeof(curGal.slides[idx].thumbHeight) != 'undefined') {
      var thumbWidth = curGal.slides[idx].thumbWidth;
      var thumbHeight = curGal.slides[idx].thumbHeight;
      var newHeight = null;
      if (curGal.slides[idx].thumbWidth > thumbDim.x) {
        newHeight = Math.floor((thumbDim.x/thumbWidth)*thumbHeight);
        attrs = 'width="'+thumbDim.x+'" ';
        attrs += 'height="'+newHeight+'" ';
      }
      else if(curGal.slides[idx].thumbHeight > thumbDim.y) {
        if (curGal.slides[idx].thumbHeight > thumbDim.y) {
          attrs = 'height="'+thumbDim.y+'" ';
          attrs += 'width="'+Math.floor((thumbDim.y/thumbHeight)*thumbWidth)+'" ';
        }
      }
      if (thumbHeight < thumbDim.y || newHeight < thumbDim.y) {
        var h = newHeight ? newHeight : thumbHeight;
        attrs += 'style="padding-top:'+Math.floor((thumbDim.y - h)/2)+'px;"';
      }
    }
    return '<a class="thumb"><img src="'+thumbSrc+'"' + attrs + '/></a>';
  }
  function prevNext (isNext, index, slideElement) {
    updateCounter(index);
    loadImage(index);
  }
  function pagerClick(index, slideElement) {
    updateCounter(index);
    loadImage(index);
  }
  function updateCounter(index) {
    $('#countCur').empty().append(index+1);
    $("#caption").empty();
    if (curGal.slides[index].caption) {
     $('#caption').empty().append(curGal.slides[index].caption);
    }

  }
  function loadImage(index) {
    if (curImg) {
      $(curImg).unbind('load', fadeLoading);
    }
    curImg = curGal.slides[index];
    if (!$('#'+index+'-slide>img:eq(0)').data('complete')) {
      $('#galLoad').fadeIn(300);
    }
    else {
      $('#galLoad').css('display', 'none');
    }
    $('#slideshow>div.slide').slice(index-1, index+2).each(function(){
      var i = parseInt($(this).attr('id'));
      if (!$(this).children('img').length) {
       var img = new Image();
       img.style.display = 'none';
       //bind the load and error events
       $(img).bind('load', {index: i}, imageOnLoad).bind('load', fadeLoading).bind('error', {index: i}, imageOnError);
       $(this).append(img);
        img.src = curGal.slides[i].src; 
      }
    });
  }
  function imageOnLoad(event) {
    var padding = '0px';
    if (this.height < galDim.y) {
      padding = Math.floor((galDim.y - this.height) / 2) + 'px';
    }
    $('#'+event.data.index+'-slide>img').eq(0).css('display', 'block').css('padding-top', padding).data('complete', true);
  
  }
  function imageOnError(event) {
    $('#'+event.data.index+'-slide>img').attr('src', errorImg.src).data('complete', true);
    curGal.slides[event.data.index].error = true;
  }
  function fadeLoading() {
    $('#galLoad').fadeOut(300);
  }

  this.loadGallery = function(target) {
    if (typeof(galleries[target]) != 'undefined' && curGal != galleries[target]) {
      curGal = galleries[target];
      $('#galLoad').css('display', 'block');
      $('#slideshow').empty();
      $('#thumbScroll').empty();
      $('#countMax').empty().append(curGal.slides.length);
      $('#galleryTitle').empty().append(curGal.name+':');
      if (scrollable) {
        scrollable.begin(0);
      }
      //insert divs
      for (var i = 0; i < curGal.slides.length; i++) {
        $('#slideshow').append('<div id="'+i+'-slide" class="slide"></div>');
      }
      $('#preCount').empty().append(0);
      $('#preTotal').empty().append(curGal.slides.length);
      $('#preloadInd').css('display', 'block');
      preloadImages();
    }
  };
  
};