$.fn.jqGallery = function(options) {

  jqGallery = {
    defaults: {
      previewGetUrl: 'href', // src, href, function callback
      fullsizeGetUrl: 'href', // src, href, function callback
      previewUrlPath: '',
      fullsizeUrlPath: '',
      previewPrefix: '',
      fullsizePrefix: '',
      previewWidthUrlVar: 'MW',
      previewHeightUrlVar: 'MH',
      fullsizeWidthUrlVar: 'MW',
      fullsizeHeightUrlVar: 'MH',
      previewMaxWidth: 420,
      previewMaxHeight: 340,
      fullsizeMaxWidth: 1024,
      fullsizeMaxHeight: 800,
      clientResize: false,
      showPreview: true,
      showPreviewNavigation: true,
      showImageTitle: true,
      showThickbox: true,
      showThickboxNavigation: true,
      showThumbnails: true,
      instructionText: 'Click preview image for fullsize view.<br/>Keyboard Navigation use left and right arrows. ',
      instructionShowOnce: true,
      instructionInTitle: true,
      cycleNavigation: false,
      allowPurchase: false,
      buttonThemePath: '/Modules/ICB/Image Gallery/Images/',
      previewThemePath: 'default',
      fullsizeThemePath: 'default',
      previewButtonBg: '',
      fullsizeButtonBg: '',
      cmdAddToBasket: { oldsrc: 'AddToBasket.jpg', src: 'add.png', title: 'Add this photograph to my shopping basket', click: function(gallery) { if (gallery.inPlay && !gallery.inPause) alert('Pause Slideshow to add item to basket'); else { mfBuyNow($('#txtImage_' + gallery.index)[0].value); } } },
      cmdBasket: { oldsrc: 'ViewBasket.jpg', src: 'view.png', title: 'View the content of my basket', click: function(gallery) { mfViewBasket(); } },
      cmdListView: { oldsrc: 'ListView.jpg', src: 'list.png', title: 'Show Images in List View', click: function() { mfListView(); } },
      cmdZoom: { oldsrc: 'zoom.jpg', src: 'zoom.png', title: 'Show Full Size Images' },
      cmdPlay: { oldsrc: 'Play.jpg', src: 'play.png', title: 'Play slide show' },
      cmdPause: { oldsrc: 'Pause.jpg', src: 'pause.png', title: 'Pause slide show' },
      cmdStop: { oldsrc: 'Stop.jpg', src: 'stop.png', title: 'Stop slide show' },
      cmdNext: { oldsrc: 'next.jpg', src: 'next.png', title: 'Next Image' },
      cmdPrev: { oldsrc: 'prev.jpg', src: 'prev.png', title: 'Previous Image' },
      slideShowDelaySeconds: 4,
      slideShowStopReset: true,
      slideShowStartCurrent: true,
      slideShowAutoStart: false,
      animateThumbnailFlash: true,
      hoverPreview: false,
      swapImageFade: 500,
      transitionEffect: 'fade',
      ajaxPreloadUrl: '',
      ajaxLoadUrl: '',
      linkSelector: 'a',
      instanceId: null,
      launchFullview: false,
      nowrap: false,
      onload: function() { document.getElementById('divLoading_' + mstrSlideShowComponentName).style.display = 'none'; document.getElementById('divContainer_' + mstrSlideShowComponentName).style.visibility = 'visible'; }
    },

    setOptions: function(options, defaults) {
      var opts = defaults;
      for (var x in options) {
        if (typeof opts[x] === 'undefined') alert('Invalid option ' + x);
        else if (opts[x] === null) opts[x] = options[x];
        else opts[x] = opts[x].constructor == Object ? this.setOptions(options[x], opts[x]) : options[x];
      }
      return opts;
    },

    setImageWrapHeight: function(gallery) {
      var div = $('.jqGalleryPreviewImage', gallery.el),
          h = (gallery.options.previewMaxHeight + 30);
      $(div).height(h);
      $('.imageWrap').height(h);
    },

    drawGallery: function(gallery) {
      var order = ['instructions', 'title', 'preview', 'navigation', 'thumbs'],
            el = $(gallery.el),
            opts = gallery.options;
      if (opts.instanceId != null) el.attr('id', opts.instanceId);
      $(order).each(function() {
        switch (this + '') {
          case 'instructions':
            if (opts.instructionText && !opts.instructionInTitle) el.append('<div class="jqGalleryInstructions"><div><span>' + opts.instructionText + '</span></div></div>');
            break;

          case 'title':
            if (opts.showImageTitle) el.append('<div class="jqGalleryTitle"><div></div></div>');
            break;

          case 'preview':
            if (opts.showPreview) el.append('<div class="jqGalleryPreviewImage"><div class="imageWrap"></div></div>');
            break;

          case 'navigation':
            if (opts.showPreview && opts.showPreviewNavigation) el.append('<div class="jqGalleryNavigation"><div align="center">' + jqGallery.returnNavigationButtons(gallery) + '</div></div>');
            break;

          case 'thumbs':
            var wrap = opts.showThumbnails ? '<div class="jqGalleryThumbs"></div>' : '<div class="jqGalleryThumbs" style="display:none;"></div>';
            if (gallery.options.nowrap == false) $(gallery.thumbs).appendTo(el).wrap(wrap);
            break;
        }
      });
      jqGallery.drawGalleryOverlay(gallery);
    },

    returnNavigationButtons: function(gallery, order, fullsize) {
      var html = '', fullsize = fullsize || false, order = order || ['cmdAddToBasket', 'cmdBasket', 'br', 'cmdPrev', 'cmdNext', 'cmdPlay', 'cmdPause', 'cmdStop', 'cmdListView', 'cmdZoom'];
      for (var i = 0, l = order.length; i < l; i++) {
        switch (order[i]) {
          case 'cmdAddToBasket': case 'cmdBasket':
            if (gallery.options.allowPurchase) html += jqGallery.returnNavigationImg(gallery, order[i], fullsize);
            break;
          case 'br':
            html += '<br/>';
            break;
          case 'cmdPrev':
            if (gallery.options.showPreview) html += jqGallery.returnNavigationImg(gallery, order[i], fullsize, { align: 'left' });
            break;
          case 'cmdNext':
            if (gallery.options.showPreview) html += jqGallery.returnNavigationImg(gallery, order[i], fullsize, { align: 'right' });
            break;
          case 'cmdPlay': case 'cmdPause': case 'cmdStop': case 'cmdListView': case 'cmdZoom':
            if (gallery.options[order[i]].src) html += jqGallery.returnNavigationImg(gallery, order[i], fullsize);
            break;
        }
      }
      return html;
    },

    returnNavigationImg: function(gallery, name, fullsize, attrs) {
      var opts = gallery.options;
      var item = opts[name];
      var path = fullsize ? opts.fullsizeThemePath : opts.previewThemePath;
      var color = fullsize ? opts.fullsizeButtonBg : opts.previewButtonBg;
      var src = (path == 'default') ? opts.buttonThemePath + item.oldsrc : opts.buttonThemePath + path + "/" + item.src;
      var attrs = attrs || {};
      var html = '<img id="' + name + '" src="' + src + '" title="' + item.title + '" alt=""';
      for (var x in attrs) {
        html += ' ' + x + '="' + attrs[x] + '"';
      }
      if (path.match(/_trans/) && color != '') html += ' style="background-color:' + color + ';"';
      html += '/>';
      return html;
    },

    drawGalleryOverlay: function(gallery) {
      // Gallery Thickbox
      $('body, html').css({ height: '100%', width: '100%', margin: 0 });
      $('body').append('<div id="jqOverlayWrap"><iframe id="jqGalleryHide"></iframe><div id="jqGallerOverlay"></div><div id="jqGalleryWindow"></div></div>');
      $('#jqOverlayWrap, #jqGalleryHide, #jqGallerOverlay').css({ width: '100%', height: '100%', border: '0', position: 'absolute', top: 0, left: 0, zIndex: 100 });
      $('#jqGalleryHide').css({ opacity: 0 });
      $('#jqGallerOverlay').css({ opacity: '0.8', zIndex: 101, padding: '1px', background: '#000' });
      $('#jqGalleryWindow').css({ position: 'relative', zIndex: 102, float: 'left' }).append('<div id="jqGalleryWindowClose"><a href="#">Close</a> or Esc Key</div><div id="jqGalleryWindowImg" align="center"/><div id="jqGalleryWindowTitle"/>');
      $('#jqGalleryWindow div').css({ position: 'relative', clear: 'left' });
      $('#jqGalleryWindowImg').append('<img id="cmdPrevFull" src="/Modules/ICB/Image Gallery/Images/prev.gif" border="0" alt="Prev &lt;" /><img id="jqImageFull" /><img id="cmdNextFull" src="/Modules/ICB/Image Gallery/Images/next.gif" border="0" alt="Next &gt;" />');
      $('#jqOverlayWrap').hide();
      if (gallery.options.showThickboxNavigation) {
        $('#jqGalleryWindowTitle').after('<div class="jqGalleryNavigation" align="center">' + jqGallery.returnNavigationButtons(gallery, ['cmdAddToBasket', 'cmdPlay', 'cmdPause', 'cmdStop', 'cmdListView', 'cmdBasket'], true) + '</div>');
      }
    },

    showGalleryOverlay: function(gallery) {
      $("html").css({ overflow: 'hidden' });
      $('#jqOverlayWrap').css({ top: $('html').scrollTop() + 'px' }).show();
      gallery.thickboxOpen = true;
      if (gallery.inPlay) jqGallery.pause(gallery); else jqGallery.stop(gallery);
      jqGallery.centerOverlay(gallery);
    },

    hideGalleryOverlay: function(gallery) {
      jqGallery.stop(gallery);
      gallery.thickboxOpen = false;
      $('#jqImageFull').hide();
      $('#jqOverlayWrap').fadeOut(300);
      setTimeout(function() { $("html").css({ overflow: 'auto' }); jqGallery.updatePreview(gallery); }, 500);
    },

    viewFullsize: function(gallery) {
      $('#jqGalleryWindow').fadeIn(300);
      $('#jqGalleryWindowImg').css({ width: 'auto', height: 'auto' });
      $('#jqGalleryWindowTitle').html($('img', gallery.thumbs[gallery.index]).attr('title') || gallery.imgTarget.title + '<br/><span>Image ' + (gallery.index + 1) + ' of ' + gallery.links.length + '</span>');
      jqGallery.resize(gallery);
      jqGallery.centerOverlay(gallery);
    },

    centerOverlay: function(gallery) {
      var t = Math.floor(($('#jqOverlayWrap').height() - $('#jqGalleryWindow').height()) / 2);
      var l = Math.floor(($('#jqOverlayWrap').width() - $('#jqGalleryWindow').width()) / 2);
      $('#jqGalleryWindow').css({ top: t + 'px', left: l + 'px' });
      $('#jqGalleryWindowImg').css({ width: $('#jqGalleryWindowImg').width() + 'px', height: $('#jqGalleryWindowImg').height() + 'px' });
    },

    centerImg: function(gallery) {
      var m = Math.floor(($('.jqGalleryPreviewImage', gallery.el).height() - $(gallery.imgMain).height()) / 2) + 'px 0';
      $(gallery.imgMain).css({ margin: m });
    },

    animateFlash: function(aLink) {
      $('.jqGalleryThumbFlash', aLink).css({ opacity: '.90', display: 'block' }).stop().animate({ opacity: '.01' }, 300);
    },

    getPreviewSrc: function(gallery, index) {
      return jqGallery.setDynamicUrlVars(gallery, jqGallery.setImageUrlPath(gallery, index));
    },

    setImageUrlPath: function(gallery, index) {
      var url, index,
        getUrl = (gallery.thickboxOpen) ? gallery.options.fullsizeGetUrl : gallery.options.previewGetUrl,
        urlPath = (gallery.thickboxOpen) ? gallery.options.fullsizeUrlPath : gallery.options.previewUrlPath,
        prefix = (gallery.thickboxOpen) ? gallery.options.fullsizePrefix : gallery.options.previewPrefix;
      if (typeof index == 'undefined') index = gallery.index;
      if ($.isFunction(getUrl)) return getUrl.call(gallery.links[index], gallery);
      else if (getUrl == 'src') { url = $('img', gallery.links[index]).attr('src'); }
      else if (getUrl == 'href' || getUrl == '') { url = $(gallery.links[index]).attr('href'); }
      if (urlPath) url = urlPath + url.split('/').pop();
      else if (prefix) url = url.replace(prefix, '');
      return url;
    },

    setDynamicUrlVars: function(gallery, url) {
      var w = (gallery.thickboxOpen) ? gallery.options.fullsizeWidthUrlVar : gallery.options.previewWidthUrlVar,
        h = (gallery.thickboxOpen) ? gallery.options.fullsizeHeightUrlVar : gallery.options.previewHeightUrlVar,
        x = (gallery.thickboxOpen) ? gallery.options.fullsizeMaxWidth : gallery.options.previewMaxWidth,
        y = (gallery.thickboxOpen) ? gallery.options.fullsizeMaxHeight : gallery.options.previewMaxHeight,
        getStr = '',
        wTest = new RegExp(w + '=(\\d+)', 'i'),
        hTest = new RegExp(h + '=(\\d+)', 'i');
      if (/\?/.test(url)) {
        url = w ? url.replace(wTest, w + '=' + x) : url;
        url = h ? url.replace(hTest, h + '=' + y) : url;
        return url.replace(/\?&/, '?').replace(/&&/, '&');
      } else {
        if (w) getStr += w + '=' + x;
        if (h) getStr += (w) ? '&' + h + '=' + y : h + '=' + y;
        return getStr ? url + '?' + getStr : url;
      }
    },

    updateNavigation: function(gallery) {
      if (gallery.options.cycleNavigation === false) {
        var prev = $('#cmdPrev', gallery.el), next = $('#cmdNext', gallery.el),
          prevFull = $('#cmdPrevFull'), nextFull = $('#cmdNextFull'),
          cur = gallery.index || 0, len = gallery.links.length - 1;
        if (cur == 0) {
          prev.css({ visibility: 'hidden' }); prevFull.css({ visibility: 'hidden' });
        } else {
          prev.css({ visibility: 'visible' }); prevFull.css({ visibility: 'visible' });
        }
        if (cur == len) {
          next.css({ visibility: 'hidden' }); nextFull.css({ visibility: 'hidden' });
        } else {
          next.css({ visibility: 'visible' }); nextFull.css({ visibility: 'visible' });
        }
      }
    },

    getNextLink: function(gallery, index) {
      var cur = gallery.index || 0, len = gallery.links.length - 1, index = index || 0;
      if (gallery.options.cycleNavigation === false) {
        if ((cur == 0 && index == -1) || (cur == len && index == +1)) return false;
      }
      cur = (cur + index >= 0 && cur + index <= len) ? cur + index : (cur == len) ? 0 : len;
      return cur;
    },

    nextNav: function(gallery, index) {
      if (gallery.ignoreNav) return; else gallery.ignoreNav = true;
      var index = index || 0, i = jqGallery.getNextLink(gallery, index);
      if (i !== false) jqGallery.viewImage(gallery, gallery.links[i]);
    },

    jumpLast: function(gallery) {
      jqGallery.viewImage(gallery, gallery.links[gallery.links.length - 1]);
    },

    jumpFirst: function(gallery) {
      jqGallery.viewImage(gallery, gallery.links[0]);
    },

    viewImage: function(gallery, aLink, delay) {
      var delay = delay || gallery.options.swapImageFade, index = aLink.galleryIndex || 0,
            src = jqGallery.getPreviewSrc(gallery, index);
      if (gallery.inPlay) jqGallery.clear(gallery);
      if (gallery.imgTarget.src == src) {
        gallery.ignoreNav = false;
        $(gallery.imgTarget).fadeIn();
        return;
      }
      jqGallery.fadeImage(gallery);
      gallery.imgNext.loaded = false;
      gallery.imgNext.title = aLink.title;
      gallery.imgNext.galleryIndex = index;
      gallery.imageFaded = false;
      $(gallery.imgNext).bind('load', function() {
        $(this).unbind('load');
        if (gallery.imageFaded) jqGallery.swapOut(gallery); else gallery.imgNext.loaded = true;
      }).attr('src', src);
      var timer = setTimeout(function() {
        clearTimeout(timer);
        if (gallery.imgNext.loaded) jqGallery.swapOut(gallery); else gallery.imageFaded = true;
      }, delay);
    },

    swapOut: function(gallery) {
      if (!gallery.thickboxOpen && !gallery.options.showPreview) return;
      gallery.imgTarget.title = gallery.imgNext.title;
      gallery.imgTarget.galleryIndex = gallery.index = gallery.imgNext.galleryIndex;
      gallery.imgNext.loaded = false;
      gallery.imageFaded = false;
      gallery.imgTarget.src = gallery.imgNext.src;
    },

    showImage: function(gallery) {
      var timer = setTimeout(function() { clearTimeout(timer); gallery.ignoreNav = false; }, gallery.options.swapImageFade);
      $(gallery.imgTarget).fadeIn(gallery.options.swapImageFade);
      if (gallery.thickboxOpen) {
        jqGallery.viewFullsize(gallery);
      } else {
        jqGallery.resize(gallery);
        jqGallery.centerImg(gallery);
        jqGallery.updateImageTitle(gallery);
      }
      jqGallery.updateNavigation(gallery);
      if (gallery.inPlay && !gallery.inPause) jqGallery.play(gallery);
    },

    fadeImage: function(gallery) {
      $(gallery.imgTarget).fadeOut(gallery.options.swapImageFade);
      if (gallery.options.showPreview) $('.jqGalleryTitle div', gallery.el).slideUp();
    },

    updateImageTitle: function(gallery) {
      var html = $('img', gallery.thumbs[gallery.index]).attr('title') || gallery.imgTarget.title || '&nbsp;'
      if (gallery.options.showPreview) {
        if (gallery.options.instructionInTitle) {
          if (gallery.options.instructionShowOnce) gallery.options.instructionInTitle = false;
          html = gallery.options.instructionText + '<br/>' + html;
        }
        $('.jqGalleryTitle div').html(html).slideDown();
      }
    },

    updatePreview: function(gallery) {
      if (gallery.thickboxOpen) {
        gallery.imgTarget = $('#jqImageFull')[0];
        jqGallery.nextNav(gallery);
      } else if (gallery.options.showPreview) {
        gallery.imgTarget = gallery.imgMain;
        jqGallery.nextNav(gallery);
      }
    },

    showFullSize: function(gallery) {
      if (gallery.options.showThickbox && gallery.ignoreNav === false) {
        jqGallery.showGalleryOverlay(gallery);
        jqGallery.updatePreview(gallery);
      }
    },

    play: function(gallery) {
      var i = jqGallery.getNextLink(gallery, +1), delay = gallery.options.slideShowDelaySeconds * 1000;
      if (i !== false) {
        if (!gallery.inPlay && !gallery.inPause && !gallery.options.slideShowStartCurrent) i = gallery.index == 0 ? 1 : 0;
        gallery.inPlay = true;
        gallery.inPause = false;
        gallery.timer = setTimeout(function() {
          jqGallery.viewImage(gallery, gallery.links[i]);
        }, delay < 2000 ? 2000 : delay);
      } else {
        jqGallery.stop(gallery, true);
      }
    },

    stop: function(gallery, skip) {
      var skip = skip || false;
      if (!gallery.inPlay) return;
      gallery.inPlay = false;
      gallery.inPause = false;
      jqGallery.clear(gallery);
      if (gallery.options.slideShowStopReset && !skip) {
        jqGallery.jumpFirst(gallery);
      }
    },

    pause: function(gallery) {
      jqGallery.clear(gallery);
      gallery.inPlay = false;
      gallery.inPause = true;
    },

    clear: function(gallery) {
      clearTimeout(gallery.timer);
      gallery.timer = null;
    },

    resize: function(gallery) {
      var newW, newH, curW, curH,
            opts = gallery.options,
            rImg = (gallery.thickboxOpen) ? $('#jqImageFull') : $(gallery.imgMain);
      if (gallery.imgNext.width > 0) rImg.css({ width: gallery.imgNext.width + 'px', height: gallery.imgNext.height + 'px', margin: 0 });
      // if clientSide resizing is on and image exceeds max dimensions (normally used for non dynamic urls)
      if (opts.clientResize) {
        newW = (gallery.thickboxOpen) ? opts.fullsizeMaxWidth : opts.previewMaxWidth;
        newH = (gallery.thickboxOpen) ? opts.fullsizeMaxHeight : opts.previewMaxHeight;
        curW = rImg.width();
        curH = rImg.height();
        if (curW <= newW && curH <= newH) return;
        if (curW > newW) { // lanscape image
          curH = Math.floor(curH * (newW / curW));
          curW = newW;
          if (curH > newW) {
            curW = Math.floor(curW * (newH / curH));
            curH = newH;
          }
        } else if (curH > newH) { // portrait
          curW = Math.floor(curW * (newH / curH));
          curH = newH;
          if (curW > newW) {
            curH = Math.floor(curH * (newW / curW));
            curW = newW;
          }
        }
        rImg.css({ width: curW + 'px', height: curH + 'px' });
      }
    }


  }; // end jqGallery Object methods

  /**
  * Process Each gallery on page
  */
  return this.each(function(i) {
    var gallery = {}, firstLoad = false;
    gallery.imgMain = new Image();
    gallery.imgNext = new Image();
    gallery.imgTarget = gallery.imgMain;

    /**
    * Setup Gallery Object variables
    */
    gallery.options = jqGallery.setOptions(options, jqGallery.defaults);
    if (gallery.options.nowrap == false) $(this).wrap('<div class="jqGalleryWrap">');
    gallery.el = $(this).parent();
    gallery.thumbs = $(this);
    gallery.timer = null;
    gallery.imageFaded = false;
    gallery.ignoreNav = false;
    gallery.inPlay = false;
    gallery.inPause = false;
    gallery.thickboxOpen = false;
    gallery.index = 0;

    /**
    * Preload first image and setup gallery display
    */
    jqGallery.drawGallery(gallery);
    jqGallery.setImageWrapHeight(gallery);
    if (gallery.options.ajaxPreloadUrl) {
      $.get(gallery.options.ajaxPreloadUrl, '', function(data) {
        $(gallery.thumbs).append(data);
        setTimeout(preloadImage, 100);
        if (gallery.options.ajaxLoadUrl) $.get(gallery.options.ajaxLoadUrl, '', function(data) { $(gallery.thumbs).append(data); init(); });
        else init();
      });
    } else {
      preloadImage();
      init();
    }
    if (gallery.options.cycleNavigation === false) {
      $('#cmdPrev', gallery.el).css({ visibility: 'hidden' });
      $('#cmdPrevFull').css({ visibility: 'hidden' });
    }
    /**
    * Show first preloaded image
    */
    function preloadImage() {
      gallery.links = $(gallery.options.linkSelector, gallery.el);
      var aLink = gallery.links[0];
      if (aLink) $(gallery.imgMain).attr('src', jqGallery.getPreviewSrc(gallery)).attr('title', aLink.title || $('img', $(aLink)).attr('alt'));
      $('.imageWrap', gallery.el).append(gallery.imgMain);
    }

    /**
    * Initialise Events on Gallery images
    */
    function init() {
      /**
      * Setup Gallery Links variable
      */
      gallery.links = $(gallery.options.linkSelector, gallery.el)
      /**
      * Setup Gallery Links mousedown Events (triggers faster than click.)
      */
      .bind('mousedown', function() {
        if (gallery.options.showPreview && gallery.index == this.galleryIndex) return;
        if (!gallery.options.showPreview && gallery.options.showThickbox) {
          jqGallery.showGalleryOverlay(gallery);
          gallery.imgTarget = $('#jqImageFull')[0];
        }
        if (gallery.options.animateThumbnailFlash) jqGallery.animateFlash(this);
        jqGallery.viewImage(gallery, this);
      })
      /**
      * Assign Variables to each Link and add flash div
      */
      .each(function(i) {
        var title = this.title || $('img', $(this)).attr('alt');
        $(this).attr('target', '_blank').attr('title', title);
        this.galleryIndex = i;
        if (gallery.options.animateThumbnailFlash) $('<div class="jqGalleryThumbFlash">').css({ cursor: 'pointer' }).appendTo(this);
      })
      /**
      * Animate Flash on mouseover links
      */
      .bind('mouseover', function() {
        if (gallery.options.animateThumbnailFlash) jqGallery.animateFlash(this);
        if (gallery.options.hoverPreview && firstLoad) {
          if (gallery.options.showPreview && gallery.index == this.galleryIndex) return;
          if (gallery.ignoreNav) return; else gallery.ignoreNav = true;
          jqGallery.viewImage(gallery, this);
        }
      })
      /**
      * Prevent Default actions on Anchor Links if we have showPreview or showThickbox set otherwise links open image in current window or anchor target attr
      */
      .click(function() { if (gallery.options.showPreview || gallery.options.showThickbox) return false; });

      /**
      * Bind Events to preview Image
      */
      $(gallery.imgMain).bind('load', function() {
        if (firstLoad && gallery.options.instructionShowOnce) $('.jqGalleryInstructions span', gallery.el).animate({ opacity: '.01' }, 400);
        if (!firstLoad && gallery.options.slideShowAutoStart) jqGallery.play(gallery);
        if (!gallery.options.showThickbox) $(this).css({ cursor: 'default' });
        firstLoad = true;
        jqGallery.showImage(gallery);
      })
      .bind('click', function() {
        jqGallery.showFullSize(gallery);
      });

      /**
      * Bind Navigation click events
      */
      $('.jqGalleryNavigation img, img#cmdNextFull, img#cmdPrevFull').bind('click', function() {
        switch (this.id) {
          case 'cmdNext': case 'cmdNextFull': jqGallery.nextNav(gallery, 1); break;
          case 'cmdPrev': case 'cmdPrevFull': jqGallery.nextNav(gallery, -1); break;
          case 'cmdZoom': jqGallery.showFullSize(gallery); break;
          case 'cmdPlay': jqGallery.play(gallery, true); break;
          case 'cmdStop': jqGallery.stop(gallery); break;
          case 'cmdPause': jqGallery.pause(gallery); break;
          case 'cmdAddToBasket': case 'cmdBasket': case 'cmdListView':
            if ($.isFunction(gallery.options[this.id].click)) gallery.options[this.id].click.call(this, gallery);
            break;
        }
      });

      /**
      * Bind keypress navigation events
      */
      $(document).bind('keydown', function(e) {
        keycode = e.which || e.keyCode;
        switch (keycode) {
          case 37: case 100: case 34: jqGallery.nextNav(gallery, -1); break; // left arrow, numpad left(4), page down
          case 39: case 102: case 33: jqGallery.nextNav(gallery, +1); break; // right arrow, numpad right(6), page up
          case 36: jqGallery.jumpFirst(gallery); break; // home key
          case 35: jqGallery.jumpLast(gallery); break; // end key
          case 27: jqGallery.hideGalleryOverlay(gallery); break;
        }
      });
      $(window).bind('resize', function(e) {
        if (gallery.thickboxOpen) jqGallery.centerOverlay(gallery);
      });

      /**
      * Bind gallery thickbox closure events
      */
      $('#jqGallerOverlay, #jqGalleryWindowClose a').unbind().mousedown(function() { jqGallery.hideGalleryOverlay(gallery); }).click(function() { return false; });
      /**
      * Bind gallery thickbox image load events
      */
      $('#jqImageFull').load(function() {
        jqGallery.showImage(gallery);
      });
      // if launch in fullview mode
      if(gallery.options.launchFullview) jqGallery.showFullSize(gallery);

      /**
      * Unload Event Destructor
      */
      $(window).unload(function() {
        $(window).unbind();
        $(document).unbind();
        $('img, a').unbind();
        jqGallery.clear(gallery);
        jqGallery = null;
        gallery = null;
      });

      /**
      * Onload function call
      */
      if ($.isFunction(gallery.options.onload)) gallery.options.onload.call(this, gallery);

    } // end init function


  });


}