var POPUPPAGE = {
	hs: {
		control: null,
		overlays: {},
		storedOnClicks: {},

		initialize: function() {
			if (typeof hs != 'object') {
				window.setTimeout(POPUPPAGE.hs.initialize, 50);
			} else {
				POPUPPAGE.hs.setupHighslide();
			}
		},

		setupHighslide: function() {
			with (hs) {
				graphicsDir = 'typo3conf/ext/oh_popup_page/res/highslide/graphics/';
				padToMinWidth = true;
				showCredits = false;
			}
			with (hs.lang) {
				loadingText = '';
				loadingTitle = '';
				moveText = '';
				closeText = '';
				closeTitle = '';
				previousText = '';
				previousTitle = '';
				nextText = '';
				nextTitle = '';
				restoreTitle = '';
			}

			// Global event handlers:
			hs.onActivate = function() {
				var targetNode = hs.$('main-content');
				if (targetNode) {
					targetNode.appendChild(hs.container);
				}
			};
			// Expander specific event handlers:
			hs.Expander.prototype.onInit = function(expander) {
				if (/^popuppage-image-single$/.test(expander.wrapperClassName)) {
					// Create dynamic overlay for current ident/group:
					POPUPPAGE.hs.getHighslideControlOverlay(expander.slideshowGroup);
					// Handle custom elements (if any) - in general this is used in galleries only:
					if (!Object.isUndefined(expander.custom)) {
						POPUPPAGE.hs.commitHighslideAnchors(expander);
					}
				} else if (/^popuppage-image-group$/.test(expander.wrapperClassName)) {
					POPUPPAGE.hs.getHighslideSlideshowOverlay(expander.slideshowGroup);
					if (!Object.isUndefined(expander.custom)) {
						POPUPPAGE.hs.commitHighslideAnchors(expander);
					}
				} else if (expander.wrapperClassName == 'popuppage-html' && !expander.contentId) {
					/*
						var cache = hs.getCacheBinding(expander.a);
						Element.select(cache, 'div.highslide-header ul li a').each(function(element) {
							element.innerText = '.';
						});
					*/
				}
				return true;
			};
			hs.Expander.prototype.onAfterClose = function(expander) {
				if (/^popuppage-image-(group|single)$/.test(expander.wrapperClassName) && !Object.isUndefined(expander.custom)) {
					POPUPPAGE.hs.revertHighslideAnchors(expander);
				}
			};
		},

		commitHighslideAnchors: function(expander) {
			var count = 0;
			if (Object.isUndefined(POPUPPAGE.hs.storedOnClicks[expander.custom.ident])) {
				POPUPPAGE.hs.storedOnClicks[expander.custom.ident] = [];
				$$('#'+expander.custom.ident+'_thumbnails a').each(function(element) {
					POPUPPAGE.hs.storedOnClicks[expander.custom.ident][count] = element.onclick;

					var options = { src: expander.custom.images[count] };
					$A(['slideshowGroup', 'outlineType', 'wrapperClassName', 'align', 'transitions']).each(function (property) {
						options[property] = expander[property];
					});

					element.removeAttribute('onclick');
					element.onclick = function() { return hs.expand(this, options, expander.custom); };

					count++;
				});
				// HighslideJS v4 specific:
				if (!Object.isUndefined(hs.updateAnchors)) {
					hs.updateAnchors();

					// Update group array to start from within a group, e.g. using the third thumbnail:
					var count = 0;
					var lastArr = [];
					var firstArr = [];
					var elementFound = false;
					var anchorException = false;

					$A(hs.anchors.groups[expander.slideshowGroup]).each(function(anchor) {
						// Skip first element:
						if (count++ > 0) {
							if (hs.getParam(anchor, 'src') == expander.src) {
								elementFound = true;
								firstArr.push(anchor);
							} else if (elementFound) {
								firstArr.push(anchor);
							} else {
								lastArr.push(anchor);
							}
						}
					});
					$A(lastArr).each(function(anchor) {
						firstArr.push(anchor);
					});
					hs.anchors.groups[expander.slideshowGroup] = firstArr;
				}
				hs.preloadImages();
			}
		},

		revertHighslideAnchors: function(expander) {
			var count = 0;
			if (!POPUPPAGE.hs.checkActiveGroupExpanders(expander.slideshowGroup) && !Object.isUndefined(POPUPPAGE.hs.storedOnClicks[expander.custom.ident])) {
				$$('#'+expander.custom.ident+'_thumbnails a').each(function(element) {
					element.onclick = POPUPPAGE.hs.storedOnClicks[expander.custom.ident][count++];
				});
				delete(POPUPPAGE.hs.storedOnClicks[expander.custom.ident]);
			}
		},

		checkActiveGroupExpanders: function(group) {
			var result = false;
			$A(hs.expanders).each(function(expander) {
				if (expander && expander.a && expander.slideshowGroup && expander.slideshowGroup == group && Element.hasClassName(expander.a, 'highslide-active-anchor')) {
					result = true;
					return;
				}
			});
			return result;
		},

		getHighslideControlContent: function() {
			if (!POPUPPAGE.hs.control) {
				var control = ''
				+	'<a class="highslide-previous" onclick="return POPUPPAGE.hs.previous(this)" href="#" title="'+hs.lang.previousText+'"></a>'
				+	'<a class="highslide-next"onclick="return POPUPPAGE.hs.next(this)" href="#" title="'+hs.lang.nextText+'"></a>'
				+	'<a class="highslide-move"href="#" onclick="return false" title="'+hs.lang.moveText+'"></a>'
				+	'<a class="highslide-close"onclick="return hs.close(this)" title="'+ hs.lang.closeTitle +'" href="#"></a>';
				POPUPPAGE.hs.control = hs.createElement(
					'div',
					{ id: 'popuppage-image-control', className: 'highslide-overlay controlbar', innerHTML: control },
					{},
					document.body
				);
			}
			return POPUPPAGE.hs.control;
		},

		getHighslideControlOverlay: function(ident) {
			// @TODO: IE6 crashes with dynamic overlays
			if (!(Prototype.Browser.IE && parseFloat(navigator.appVersion.split(';')[1].strip().split(' ')[1]) == 6)) {
				var identName = (ident || 'single');

				POPUPPAGE.hs.getHighslideControlContent();
				if (!POPUPPAGE.hs.overlays[identName]) {
					POPUPPAGE.hs.overlays[identName] = {
						slideshowGroup: ident,
						overlayId: 'popuppage-image-control',
						position: 'top right',
						hideOnMouseOut: false,
						useOnHtml: true,
						fade: false
					};
					hs.registerOverlay(POPUPPAGE.hs.overlays[identName]);
				}
			}
		},

		getHighslideSlideshowOverlay: function(ident) {
			var identName = (ident || 'group');

			if (!POPUPPAGE.hs.overlays[identName]) {
				POPUPPAGE.hs.overlays[identName] = {
					slideshowGroup: ident,
					interval: 5000,
					repeat: false,
					useControls: true,
					fixedControls: true,
					overlayOptions: {
						opacity: .6,
						position: 'top center',
						hideOnMouseOut: true
					}
				};
				if (hs.addSlideshow) {
					hs.addSlideshow(POPUPPAGE.hs.overlays[identName]);
				}
			}
		},

		previous: function(el) {
			return (POPUPPAGE.hs.checkPreviousOrNext(el, -1) ? hs.previous(el) : hs.previousOrNext(el, -2));
		},

		next: function(el) {
			return (POPUPPAGE.hs.checkPreviousOrNext(el, 1) ? hs.next(el) : hs.previousOrNext(el, 2));
		},

		// Check against the currently shown popup image:
		checkPreviousOrNext: function(el, op) {
			var expander = hs.getExpander(el);
			var result = false;

			// @TODO: Wait for HighslideJS final release and then refactor this function:
			// Known Bug: When different to first image is selected, stepping back does not work -> hs.anchors.groups

			try {
				var adjacent = expander.getAdjacentAnchor(op);
				if (hs.getParam(adjacent, 'src') != expander.src) {
					result = true;
				}
			} catch(e) {}

			return result;
		}
	}
};

POPUPPAGE.hs.initialize();