(function($) {
  overlay = {};
  overlay.active = '';

  // OVERLAY SCROLL THUMBNAILS
  $('div.scrollable').scrollable({
    vertical:true,
    item:"div.next_row",
    size:'3'
  }).mousewheel();

  function doSwap(obj,offset) {
    /* if ($('[id="lg_'+this.id.substr(3)+'"]')[0]) {
      // ADD IMAGE PRELOADING HERE
    } */
    targ = $.findClass(obj,'xgal_',1);
    id = obj.id.substr(offset);
    if (offset == 5) {
      // is overlay
    }
    // pageTracker._trackPageview('/outgoing/example.com');
    // console.warn($page);
    // console.info(id);

		$('div.o_thumb_list a').removeClass('active');
		$('[id="o_th_'+id+'"]').addClass('active');
    $('#lg_img_'+targ).attr('src','/_img/gallery/'+targ+'/lg_'+id);
    $('div#gallery_overlay_'+targ+' .copy_block').hide();
    $('div#gallery_overlay_'+targ+' [id="cp_'+id+'"]').show();
  }

  // THUMBNAILS IN PAGE CLICK
  $('div.thumb_list a[id!=""]').click(function() {
    var targ = $.findClass(this,'xgal_',1);
    overlay.active = targ;

    if (targ != "") {
      if (overlay[targ] == undefined) {
        overlay[targ] = $('div#gallery_overlay_'+targ).overlay({
          expose: {
            color:'#333',
            loadspeed:100,
            opacity:0.8,
            onBeforeLoad:widen,
            maskId:'exposeMask'
          },
          close:'.overlay_close',
          api:true
        })
      }
      
      if ($('div#gallery_overlay_'+targ+' .o_thumb_list a').size() > 6) {
        $('.actions').show();
      } else {
        $('.actions').hide();
      }

      $('#exposeMask').click(function() {
        overlay[targ].close();
        return false;
      })

      overlay[targ].load();
      overlay[targ].getOverlay().css('top',$(window).height()*0.02+$(window).scrollTop()+'px');
      doSwap(this,3);
    }
    return false;
  });

  // THUMBNAILS IN OVERLAY CLICK
  $('div.o_thumb_list a').click(function() {
    doSwap(this,5);
    return false;
  });

  $(window).bind('resize', function() {
    if (overlay[overlay.active] && overlay[overlay.active].isOpened()) {
      widen();
      $('div.gallery_overlay').css({
        'left':$(window).width()*0.5-407+'px',
        'top':$(window).height()*0.02+$(window).scrollTop()+'px'
      });
    }
  });
  
  if (window.location.hash) {
    var hash = window.location.hash.substr(1);
    if (hash != "") $('div.thumb_list a.xthumb_'+hash).click();
  }
})(jQuery);
