;(function($) {
	jQuery.fn.imagegallery = function(options) {
		var options = $.extend({}, jQuery.fn.imagegallery.defaults, options);

		return this.each(function() {
			var $this = jQuery(this);

			/**
			 * All code for the panel is below here
			 */
			// move preview items from where ever in the gallery to the preview viewport
			jQuery('.previewItem', $this)
				.appendTo('.pwsPreview .viewport ul')
				.wrap('<li></li>');

			var $previewViewport = $this.find('.pwsPreview .viewport').css('overflow', 'hidden'),
				$previewItems = $previewViewport.find('> ul > li'),

				previewItemCount = $previewItems.length,
				previewItemWidth = $previewItems.filter(':first').outerWidth(),
				currentPreview = 0,

				previewBackArrow = jQuery('.pwsPreview a.back', $this),
				previewForwardArrow = jQuery('.pwsPreview a.forward', $this);

			previewBackArrow.click(function() {
				scrollPreviewTo(currentPreview - 1);
				return false;
			});

			previewForwardArrow.click(function() {
				scrollPreviewTo(currentPreview + 1);
				return false;
			});

			$this.bind('scrollPreview', function(event, position) {
				scrollPreviewTo(position);
			});

				//initialize the lightbox
			$previewItems.find('a')
				.fancybox({
					'showNavArrows': true,
					'titleShow' : options.fancyboxTitleShow,
					onStart : function(currentArray, currentIndex, currentOpts) {
						scrollPreviewTo(currentIndex);
					}
				});

			checkPreviewArrows();

			/**
			 * Checks if position is between zero and the itemcount minus one.
			 * Sets the preview viewport scrolling to the given position without
			 * scrolling
			 *
			 * @param	integer	the position
			 * @return	boolean
			 */
			function scrollPreviewTo(position) {
				if ((position >= 0) && (position < previewItemCount)) {
					$previewViewport.scrollLeft(previewItemWidth * position);
					currentPreview = position;
					checkPreviewArrows();
				}
				return false;
			}

			/**
			 * Starts with value visible to both arrows. Checks if the current
			 * preview is at the begin or the end of the list and changes the
			 * value to hidden for either case. Sets the value to visibility before
			 * the method if left
			 *
			 * @return	void
			 */
			function checkPreviewArrows() {
				var back = 'visible',
					forward = 'visible';
				if (currentPreview == 0) {
					back = 'hidden';
				} else if (currentPreview >= (previewItemCount - 1)) {
					forward = 'hidden';
				}

				previewBackArrow.css('visibility', back);
				previewForwardArrow.css('visibility', forward);
			}



/******************************************************************************/



			/**
			 * Below are all function related to the thumbnails
			 */
			var $thumbnailViewport = $this.find('.pwsThumbnails .viewport').css('overflow', 'hidden'),
				$thumbnailItems = $thumbnailViewport.find('> ul > li'),

				thumbnailItemCount = $thumbnailItems.length,
				thumbnailItemWidth = $thumbnailItems.filter(':first').outerWidth(),
				currentThumbnail = 0,
				visibleThumbnails = Math.ceil($thumbnailViewport.innerWidth() / thumbnailItemWidth),

				thumbnailBackArrow = jQuery('.pwsThumbnails a.back', $this),
				thumbnailForwardArrow = jQuery('.pwsThumbnails a.forward', $this),

				thumbnailScrollLoop = false,
				thumbnailScrollBusy = false;

				// Top and tail the list with 'visibleThumbnails' number of items, top has the
				// last section, and tail has the first if viewport ist wider than item available
			if (thumbnailItemCount > visibleThumbnails) {
				$thumbnailItems.filter(':first')
					.before($thumbnailItems.slice(- visibleThumbnails)
						.clone()
						.addClass('cloned')
					);
				$thumbnailItems.filter(':last')
					.after($thumbnailItems.slice(0, visibleThumbnails)
						.clone()
						.addClass('cloned')
					);
					// reselect because there are cloned items added
				$thumbnailItems = $thumbnailViewport.find('> ul > li');

					// Set the left position to the first 'real' item
				$thumbnailViewport.scrollLeft(thumbnailItemWidth * visibleThumbnails);
			} else {
				thumbnailBackArrow.css('visibility', 'hidden');
				thumbnailForwardArrow.css('visibility', 'hidden');
			}

				// Bind to the forward and back buttons and give a public interface
			if (!options.scrollOnHover) {
				thumbnailBackArrow.click(function() {
					scrollThumbsTo(currentThumbnail - options.scrollBy);
					return false;
				});
				thumbnailForwardArrow.click(function() {
					scrollThumbsTo(currentThumbnail + options.scrollBy);
					return false;
				});
			} else {
				thumbnailBackArrow.bind({
					mouseenter: function() {
						thumbnailScrollLoop = true;
						scrollThumbsTo(currentThumbnail - options.scrollBy);
					},
					mouseleave: function() {
						thumbnailScrollLoop = false;
					}
				});
				thumbnailForwardArrow.bind({
					mouseenter: function() {
						thumbnailScrollLoop = true;
						scrollThumbsTo(currentThumbnail + options.scrollBy);
					},
					mouseleave: function() {
						thumbnailScrollLoop = false;
					}
				});
			}

			$this.bind('scrollThumbs', function(event, position) {
				scrollThumbsTo(position);
			});

			jQuery('li', $thumbnailViewport).each(function(index) {
				$('a', this).click(function() {
					var position = index;

					if (thumbnailItemCount > visibleThumbnails) {
						var position = index - visibleThumbnails;

						if (position > (thumbnailItemCount - 1)) {
							position -= thumbnailItemCount;
						} else if (position < 0) {
							position += thumbnailItemCount;
						}
					}

					scrollPreviewTo(position);
					return false;
				});
			});

			/**
			 * Scrolls the list to given position. Either directly to one item or
			 * with chained animation. Chaining is in this case only posible if
			 * option.scrollOnHover is set to true
			 *
			 * @param	integer	the position
			 * @return	boolean
			 */
			function scrollThumbsTo(position) {
				if (thumbnailItemCount <= visibleThumbnails) {
					return false;
				}
				var dir = position < currentThumbnail ? -1 : 1,
					n = Math.abs(currentThumbnail - position),
					left = thumbnailItemWidth * dir * n;

				if (thumbnailScrollBusy == false) {
					thumbnailScrollBusy = true;

					$thumbnailViewport.animate({
						scrollLeft : '+=' + left
					}, options.scrollDuration, options.scrollEasing, function() {
						checkThumbsPosition(position);

						thumbnailScrollBusy = false;
						if (thumbnailScrollLoop) {
							scrollThumbsTo(currentThumbnail + (n * dir));
						}
					});
				}

				return false;
			}

			/**
			 * Checks wether the first or last item was passed by, then sets the list
			 * position to that item on the opposite end of the list and sets current
			 * value to that positionnumber
			 *
			 * @param	integer	the position
			 * @return	void
			 */
			function checkThumbsPosition(position) {
				if (position < 0) {
						// set to end of list
					position = position + thumbnailItemCount;
					$thumbnailViewport.scrollLeft(thumbnailItemWidth * (position + visibleThumbnails));
				} else if (position > (thumbnailItemCount - 1)) {
						// set to beginning of list
					position = position - thumbnailItemCount;
					$thumbnailViewport.scrollLeft(thumbnailItemWidth * (position + visibleThumbnails));
				}
				currentThumbnail = position;
			}
		});
	};

	// default values for the options
	jQuery.fn.imagegallery.defaults = {
		scrollBy : 1,
		scrollEasing : 'swing',
		scrollDuration : 600,
		scrollOnHover : 0
	};

	jQuery.fn.igpagebrowser = function(options) {
		var options = jQuery.extend({}, jQuery.fn.igpagebrowser.defaults, options),
			rscript = /<script(.|\s)*?\/script>/gi;

		return this.each(function() {
			var $this = jQuery(this),
				loadedImages = new Array();

			var $pwlPreview = $this.find('.pwlPreview'),
				$pwlViewport = $this.find('.viewport'),
				$pwlThumbnails = $this.find('.pwlThumbnails'),
				$pwlPagebrowser = $this.find('.pwlPagebrowser').hide();

			var $tabs = jQuery('<ul/>')
				.toggleClass('tabs')
				.prependTo($pwlThumbnails);

			var pageCount = 1;
			$pwlPagebrowser.find('.page').each(function() {
				var $self = $(this);

					// we add pane_1 to the first ul and then add additional ul with pane_*
				if (pageCount == 1) {
					$pwlViewport.find('ul').toggleClass('pane_' + pageCount);
				} else {
					jQuery('<ul/>')
						.toggleClass('pane_' + pageCount)
						.css('display', 'none')
						.appendTo($pwlViewport);
				}

					// we add li to ul.pages with event for loading and switching the tabs
				jQuery('<li/>')
					.toggleClass('tab_' + pageCount)
					.appendTo($tabs)
					.html($self.html())
					.bind({
						click: function(event) {
							var $this = $(this),
								paneNumber = getPaneNumber($this);

							$tabs.find('> li').toggleClass('active', false);
							$this.toggleClass('active', true);

							var $pane = $pwlViewport.find('.pane_' + paneNumber);

							if ($pane.children().length == 0) {
								var $loader = jQuery('<div/>')
									.toggleClass('loading')
									.appendTo($pwlViewport);

								jQuery.ajax({
									url: $self.attr('href'),
									type: 'POST',
									dataType: 'html',
									complete: function(res, status) {
										jQuery('<div/>')
											.append(res.responseText.replace(rscript, ''))
											.find('.pwlThumbnails .viewport li')
												.appendTo($pane)
												.find('a')
													.bind({
														click: loadImage
													});

										switchToSelectedPane($pane, $this);

										$loader.remove();
									}
								});
							} else {
								switchToSelectedPane($pane, $this);
							}
						},
						mouseenter: function() {
							$(this).toggleClass('hover');
						},
						mouseleave: function() {
							$(this).toggleClass('hover');
						}
					});

				pageCount++;
			});
			$tabs.find('> li').eq(0).toggleClass('active', true);


			var $itemLinks = $pwlViewport.find('a');
			$itemLinks.bind({
				click: loadImage
			});

			function getPaneNumber($tab) {
				var classnames = $tab.attr('class').split(' ');

				for (i = 0; i < classnames.length; i++) {
					var classParts = classnames[i].split('_');
					if (classParts[0] == 'tab') {
						return classParts[1];
						break;
					}
				}
			}

			function switchToSelectedPane($pane, $tab) {
				$pwlViewport.find('ul').css('display', 'none');
				$pane.css('display', 'block');
			}

			function loadImage(event) {
				var $self = $(this),
					url = $self.attr('href');

				if (typeof(loadedImages[url]) == 'undefined') {
					var $loader = jQuery('<div/>')
						.toggleClass('loading')
						.appendTo($pwlPreview);

					jQuery.ajax({
						url: url,
						type: 'POST',
						dataType: 'html',
						complete: function(res, status) {
							$pwlPreview.find('> div').detach();
							loadedImages[url] = jQuery('<div/>')
								.append(res.responseText.replace(rscript, ''))
								.find('.pwlPreview > div')
									.appendTo($pwlPreview)
									.find('.previewItem')
										.fancybox({
											'hideOnContentClick' : true,
											'titleShow' : options.fancyboxTitleShow
										})
										.end();
							$loader.remove();
						}
					});
				} else {
					$pwlPreview.find('> div').detach();
					loadedImages[url].appendTo($pwlPreview);
				}

				return false;
			}
		});
	};

	// default values for the options
	jQuery.fn.igpagebrowser.defaults = {
	};
})(jQuery);



;(function($) {
	$(document).ready(function() {
		var $preview = jQuery('.pwnPreview, .pwlPreview'),
			$information = null,
			$pwnImage = $('.previewItem').fancybox({hideOnContentClick : true});

		$preview.bind({
			mouseenter: function() {
				$information = $preview.find('.informations');
				$information.stop().animate({opacity: '0.6'}, 'fast');
			},
			mouseleave: function() {
				$information.stop().animate({opacity: '0.0'}, 'fast');
			}
		});
	});
})(jQuery);
