$(function () {


/* footer links hover */
$('img#footerFacebook').mouseenter(
	function(){
		$(this).attr("src","/img/facebook-white2.png");
	}).mouseleave(
	function(){
		$(this).attr("src","/img/facebook-red.png");
	}
);
$('img#footerTwitter').mouseenter(
	function(){
		$(this).attr("src","/img/twitter-white2.png");
	}).mouseleave(
	function(){
		$(this).attr("src","/img/twitter-red.png");
	}
);

  /*
 * Gallery behaviour
 */
  if ($('div#thumb-slide').length == 1) {
    config.gallery.totalThumbCount = $('div#thumb-slide ul li').length;
    config.gallery.containerWidth = config.gallery.totalThumbCount * (config.gallery.thumbWidth + config.gallery.thumbSpace); //?

    // Preload second image
    preloadGalleryImages (0);

    // Thumbnails behaviour
    $($('div#thumb-slide ul li')[0]).addClass ('active');
    $('div#thumb-slide ul a').click (function () {showClickedImage (this); pauseGallery (); return false;});

    // Scroller buttons behaviour
    if ($('div#thumb-slide ul li').length <= config.gallery.thumbCount) {
      $('div#thumbs div#button-down').addClass ('disabledNext');
    }
    else {
      $('div#thumbs div#button-down').click (function () {scrollNext (); pauseGallery ();});
    }

    // Automate gallery
    galleryAutomatize ();

    var $imageMask = $('div#images-mask');
    $imageMask
      .data ('state', 'play')
      .mouseover (function () {
        if ($imageMask.data ('state') == 'play') {
          $imageMask.attr ('id', 'images-mask-pause');
        }
        else if ($imageMask.data ('state') == 'pause') {
          $imageMask.attr ('id', 'images-mask-play');
        }
      })
      .mouseout (function () {
        $imageMask.attr ('id', 'images-mask');
      })
      .click (function () {
        if ($imageMask.data ('state') == 'pause') {
          galleryAutomatize ();
          $imageMask.attr ('id', 'images-mask-pause');
        }
        else if ($imageMask.data ('state') == 'play') {
          pauseGallery ();
          $imageMask.attr ('id', 'images-mask-play');
        }
      })

  }

});

/*
* Config
*/
var config = {
  gallery : {
    containerHeight : 312,
    thumbHeight : 78,
    thumbSpace : 0,
    thumbCount : 12,
    moveCount : 2, // rows
    topOffset : 0,
    speed : 250,
    thumbOpacity: 0.7,
    intervalId: undefined,
    intervalDelay: 5000
  }
};

/*
* FUNCTIONS
*/

/*
* Gallery functions
*/

function pauseGallery () {
  $('div#images-mask, div#images-mask-pause').data ('state', 'pause');
  clearInterval (config.gallery.intervalId);
}

function galleryAutomatize () {
  $('div#images-mask, div#images-mask-play').data ('state', 'play');
  config.gallery.intervalId = setInterval ('galleryPlayNext()', config.gallery.intervalDelay);
}

function galleryPlayNext () {
  var index = $('div#thumb-slide li.active').index ();
  //showClickedImage ($('div#thumb-slide li a')[index + 1]);
  showNextImage();
}

function preloadGalleryImages (currIndex) {
  $('img.preloadedNext, img.preloadedPrevious').remove ();
  var nextImageIndex = getNextImageIndex (currIndex);
  var previousImageIndex = getPreviousImageIndex (currIndex);
  var $thumbNext = $($('div#thumb-slide li a')[nextImageIndex]);
  var $thumbPrevious = $($('div#thumb-slide li a')[previousImageIndex]);
  $('img.displayImage').after (
    '<img class="preloadedNext" style="display: none;" src="'+ $thumbNext.attr ('href') +'" alt="'+ $thumbNext.find ('img').attr ('alt') +'" />'
    + '<img class="preloadedPrevious" style="display: none;" src="'+ $thumbPrevious.attr ('href') +'" alt="'+ $thumbPrevious.find ('img').attr ('alt') +'" />'
    );
  $('img.preloadedNext').data ('index', nextImageIndex);
  $('img.preloadedPrevious').data ('index', previousImageIndex);
}

function getNextImageIndex (index) {
  return (index + 1) % ($('div#thumb-slide li').length);
}

function getPreviousImageIndex (index) {
  if (index - 1 >= 0) {
    return index - 1;
  }
  else {
    return $('div#thumb-slide li').length - 1;
  }
}

function showNextImage () {
  showImage ('next');
  return false;
}

function showPreviousImage () {
  showImage ('previous');
  return false;
}

function showClickedImage (clickedElement) {
  $('div#thumb-slide li.active').removeClass ('active');
  var index = $(clickedElement).parent ('li').index ();
  $(clickedElement).parent ('li').addClass ('active');
  showImage ('noDirection', index);
  return false;
}

function showImage (direction, index) {
  var $thumbnailLinks = $('div#thumb-slide ul a');

  $thumbnailLinks
  .unbind ('click')
  .click (function () {
    return false;
  });
    
  var $activeImage = $('img.displayImage');

  // Animate fade in / fade out
  $activeImage.css ({
    'zIndex' : '0'
  });

  var $preloadedImage = null;
  switch (direction) {
    case 'next':
      $preloadedImage = $('img.preloadedNext');
      break;
    case 'previous':
      $preloadedImage = $('img.preloadedPrevious');
      break;
    case 'noDirection':
      preloadGalleryImages (index - 1);
      $preloadedImage = $('img.preloadedNext');
  }

  // Check if image loaded
  var image = new Image ();
  image.src = $preloadedImage.attr ('src');
  $('span.img-title').text ($preloadedImage.attr ('alt'));
  if (!image.complete) {
    pauseAndDisplayImage (image, $activeImage, $preloadedImage);
  }
  else {
    displayImage ($activeImage, $preloadedImage);
  }
}

function pauseAndDisplayImage (image, $activeImage, $preloadedImage) {
  var loaderImage = '<img src="/img/ajax-loader.gif" class="loader" style="display:none;z-index:10;width:28px;height:28px;position:absolute;margin-top:-14px;margin-left:-14px;top:48%;left:50%;" alt="Loading..." style="display: none;" />';
  $('div#images').prepend (loaderImage);
  var $loaderImage = $('div#images img.loader');
  $loaderImage.fadeIn (200);

  config.gallery.pause = {};
  config.gallery.pause.image = image;
  config.gallery.pause.$loaderImage = $loaderImage;
  config.gallery.pause.$activeImage = $activeImage;
  config.gallery.pause.$preloadedImage = $preloadedImage;

  config.gallery.intId = setInterval ('checkImage ()', 200);
}

function checkImage () {
  if (config.gallery.pause.image.complete) {
    config.gallery.pause.$loaderImage
    .stop().fadeOut (
      200,
      function () {
        $(this).remove ();
      }
      );
    clearInterval (config.gallery.intId);
    displayImage (config.gallery.pause.$activeImage, config.gallery.pause.$preloadedImage);
    // Free data
    config.gallery.pause = {}
  }
}

function displayImage ($activeImage, $preloadedImage) {
  changeCaption ($($('div#thumb-slide ul img')[$preloadedImage.data ('index')]).attr ('alt'));
  moveScroller ('clicked', $preloadedImage.data ('index'));

  // Disable buttons if needed
  if ($preloadedImage.data ('index') == 0) {
    disableGalleryButton ('displayPrevious');
  }
  if ($preloadedImage.data ('index') == config.gallery.totalThumbCount - 1) {
    disableGalleryButton ('displayNext');
  }

  $preloadedImage.css ({
    'position' : 'absolute',
    'top' : '17px',
    'left' : '22px',
    'opacity' : '0',
    'zIndex' : '1',
    'display' : 'block'
  });

  $preloadedImage.animate (
  {
    'opacity' : 1
  },
  config.gallery.speed,
  'swing',
  function () {
    $activeImage.remove ();
    $preloadedImage
    .attr ('class', 'displayImage')
    .removeAttr ('style');
    preloadGalleryImages ($preloadedImage.data ('index'));
    var $thumbnailLinks = $('div#thumb-slide ul a');
    $thumbnailLinks.click (function () {showClickedImage (this);pauseGallery ();return false;});
  }
  );
}

function moveScroller (direction, index) {
  var $thumbList = $('div#thumb-slide ul');
  var position = $thumbList.position ();
  var top = Math.abs (position.top) - config.gallery.topOffset;

  // Move list if needed
  var newPosition = Math.abs (position.top);
  var move = false;

  if (direction == 'clicked') {
    $('div#thumb-slide li.active').removeClass ('active');
    var thumb = $($('div#thumb-slide li')[index]);
    thumb.addClass ('active');
    var moveDistance = config.gallery.moveCount * (config.gallery.thumbHeight + config.gallery.thumbSpace);
    if (index == 0) {
      newPosition = 0;
      move = true;
    }
    else if (thumb.position().top >= top + 312) {
      newPosition = top + config.gallery.topOffset;
      do {
        newPosition += moveDistance;
      } while (newPosition < thumb.position().top - moveDistance);
      move = true;
    }
    else if (thumb.position().top < top) {
      newPosition = top + config.gallery.topOffset;
      do {
        newPosition -= moveDistance;
      } while (newPosition > thumb.position().top);
      move = true;
    }
  }
  else {
    if (direction == 'next') {
      newPosition = top + config.gallery.topOffset + config.gallery.moveCount * (config.gallery.thumbHeight + config.gallery.thumbSpace);
      move = true;
    }
    else if (direction == 'previous') {
      newPosition = top + config.gallery.topOffset - config.gallery.moveCount * (config.gallery.thumbHeight + config.gallery.thumbSpace);
      move = true;
    }
  }
  if (move) {
    $thumbList.animate (
    {
      'top' : '-' + newPosition +'px'
    },
    config.gallery.speed,
    'swing'
    );
  }

  // Disable buttons if needed
  if (newPosition == 0) {
    disableGalleryButton ('scrollPrevious');
  }
  else {
    enableGalleryButton ('scrollPrevious');
  }
  if (Math.ceil (config.gallery.thumbCount / 3) * (config.gallery.thumbHeight + config.gallery.thumbSpace) - newPosition < config.gallery.containerHeight - config.gallery.thumbHeight * 2) {
    disableGalleryButton ('scrollNext');
  }
  else if ($('div#thumb-slide li').length > config.gallery.thumbCount) {
    enableGalleryButton ('scrollNext');
  }
}

function scrollNext () {
  moveScroller ('next');
}

function scrollPrevious () {
  moveScroller ('previous');
}

function changeCaption (alt) {
  alt = alt.split (';');
  if (alt.length == 2) {
    $('div#images span.img-title').text (alt);
  }
}

function disableGalleryButton (button) {
  switch (button) {
    case 'scrollNext':
      $('div#thumbs div#button-down')
      .addClass ('disabledNext')
      .fadeOut (200)
      .unbind ('click');
      break;
    case 'scrollPrevious':
      $('div#thumbs div#button-up')
      .addClass ('disabledPrevious')
      .fadeOut (200)
      .unbind ('click');
      break;
  }
}

function enableGalleryButton (button) {
  switch (button) {
    case 'scrollNext':
      $('div#thumbs div#button-down')
      .removeClass ('disabledNext')
      .fadeIn (200)
      .unbind ('click')
      .click (function () {scrollNext (); pauseGallery ();});
      break;
    case 'scrollPrevious':
      $('div#thumbs div#button-up')
      .removeClass ('disabledPrevious')
      .fadeIn (200)
      .unbind ('click')
      .click (function () {scrollPrevious (); pauseGallery ();});
      break;
  }
}
