// attrib_name may be
// id|class|readOnly
// or a style property name like 'display'
function setAttributeForElement(id, attrib_name, attrib_value)
{
	var element = document.getElementById(id);
	if (!element) return;
	
	if (attrib_name == 'class') {
		element.className = attrib_value;
	}
	else if (attrib_name == 'id') {
		element.id = attrib_value;
	}
	else if (attrib_name == 'readOnly') {
		element.readOnly = attrib_value;
	}
	else {
		element.style[attrib_name] = attrib_value;
	}
	return 1;
}

function contentGallery(args)
{
	var self = arguments.callee;
	
	if (!args) args = new Object;

	if (!self.__constants) {
		self.__constants = 1;

		self.DO_LOG          = 0;
		self.MIN_AD_INTERVAL = 7;
		self.MAGNIFIER       = {x: 20, y: 20};
		self.PREVIEWER       = '/php-bin/functions/imagepreview/gallery_magnifier.php';
		self.DEFAULT_HEIGHT  = 404;
		
		self.POPUP = {x_min: 748, y_min: 500, x_max: 1000, y_max: 690, y_top: 111, scrollbar_delta: 20};

		self.DO_FADE           =    0;
		self.OPACITY_SPEED     =   10;
		self.OPACITY_STEPS     =   15;
		self.MIN_OPACITY       =   10;
		self.MAX_FADE_DURATION = 1000;
		// Prevent endless recursion
		self.MAX_FADE_ROUNDS   =  200;
		
		// IE bug:
		// when alpha filter is applied, #02050a pixels are rendered transparent.
		// Set background to a slightly different color to allow fading of background.
		self.IE_MISSING_PIXEL_COLOR = '#02050b';
		self.IS_IE = navigator.userAgent.indexOf('MSIE') >= 0 ? true : false
	}

	this.global          = (args.global || new Object);
	this.items           = (args.items || new Array);
	// this.defaults.copyright is only set with args
	// if for *no* item the copyright property equals the empty string.
	this.defaults        = (args.defaults || new Object);
	this.total           = (this.items.length);
	this.max_height      = (args.max_height || self.DEFAULT_HEIGHT);
	this.current         = (args.current || 0);
	this.channel         = (args.channel || '');
	this.format          = (args.format  || '');
	this.directory       = window.location.pathname;
	this.display_mode    = 'gallery';
	this.clicked         = 1;
	this.ad_interval     = Number(args.ad_interval || self.MIN_AD_INTERVAL);
	if (!this.ad_interval || this.ad_interval < self.MIN_AD_INTERVAL) this.ad_interval = self.MIN_AD_INTERVAL;
	
	this.do_fade           = args.do_fade != null ? args.do_fade : self.DO_FADE;
	this.opacity_speed     = args.opacity_speed != null ? args.opacity_speed : self.OPACITY_SPEED;
	this.opacity_steps     = (args.opacity_steps || self.OPACITY_STEPS);
	this.__current_opacity = 100;
	
	this.containers  = new Object;

	if (!self.__init) {
		self.__init = 1;

		// Public methods
		self.prototype.next = function() {
				if (this.__prepare(1)) this.__display();
			};

		self.prototype.previous = function() {
				if (this.__prepare(-1)) this.__display();
			};

		self.prototype.showOrigImage = function() {
				var item = this.items[this.current];

				var img, x, y;
				
				if (item.orig_img) {
					img = item.orig_img;
					x   = item.orig_x;
					y   = item.orig_y;
				}
				else {
					img = item.img;
					x   = (item.x || this.defaults.x);
					y   = (item.y || this.defaults.y);
				}
				
				var dir = (item.dir || this.defaults.img_dir);
				if (!dir || !img) return;
				
				var src = [dir, img].join('/');
				
				var popup_x, popup_y;
				
				if (x > self.POPUP.x_max) {
					popup_x = self.POPUP.x_max;
				}
				else if (x >= self.POPUP.x_min) {
					popup_x = x;
				}
				else {
					popup_x = self.POPUP.x_min;
				}
				
				if (y > self.POPUP.y_max - self.POPUP.y_top) {
					popup_y = self.POPUP.y_max;
				}
				else {
					popup_y = y + self.POPUP.y_top;
				}
				
				popup_x += self.POPUP.scrollbar_delta;
				popup_y += self.POPUP.scrollbar_delta;
				
				var params = "url=" + escape(src)
					+ '&contentkategorie=gallery'
					+ '&x=' + x
					+ '&y=' + y
					+ '&popupx=' + popup_x
					+ '&popupy=' + popup_y
					+ '&directory=' + escape(this.directory);
				
				if (this.channel) params += '&channel=' + this.channel;
				if (this.format)  params += '&format=' + this.format;
				
				var copyright = (item.copyright || this.defaults.copyright);
				if (copyright) params += '&copyright=' + escape(copyright);

				var url = [self.PREVIEWER, params].join('?');
				// Always set scrollbars because popup window is re-used.
				var features = 'scrollbars=yes,resizable=yes,innerwidth='+ popup_x + ',innerheight=' + popup_y;

				var clack=window.open(url, 's1_gallerypreview', features);
				if (clack) clack.focus();
			};
			
		self.prototype.adjustImageContainer = function() {
				var item = this.items[this.current];
				if (!item.img) return;

				var image_container = this.__getElement('cgal-image-container');
				if (!image_container) return;
				
				var y = (item.y || this.defaults.y);

				var delta = parseInt((this.max_height - y) / 2);

				var padding_top = 0;
				var max_height  = this.max_height;

				if (delta > 0) {
					padding_top = delta;
					max_height  -= delta;
				}

				image_container.style.paddingTop = padding_top + 'px';
				image_container.style.height     = max_height + 'px';
				
				this.__setMagnifier();
		}
			
		// The properties passed by SIMAdWriter are:
		// init, ad_type
		self.prototype.notify = function(args) {
				if (args.init) this.display_mode = 'rectangle1';
			};

		self.prototype.setFading = function(flag) {
			this.do_fade = flag ? 1 : 0;
		};

		// Private methods
		self.prototype.__prepare = function(direction) {
				if (this.__in_progress) return;
				this.__in_progress = 1;

				++this.clicked;
				this.__direction = direction;

				if (this.do_fade) {
					this.__fix_ie_02050a_pixels(1);
					this.__current_fading = -1;
					this.__fade_rounds    =  0;
					this.__start_time     = (new Date).getTime();
				}
				
				return true;
			};
			
		self.prototype.__display = function() {
				var status = this.__setOpacity();
				
				if (status == 'NO FADE' || status == 'FADED OUT') {
					if (this.__handleAd()) {
						this.__in_progress = 0;
						return;
					}
					this.__setItem();
				}

				if (!status || status == 'NO FADE') {
					this.__finishOffItem();
					return;
				}

				// Scope of setTimeout is window,
				// i.e. inside of setTimeout *this* refers to window
				var that = this;
				setTimeout(function() {that.__display()}, this.opacity_speed);
			};

		self.prototype.__setItem = function() {
				this.__setCurrent();
				if (typeof(this.items[this.current]) != 'object') return;

				this.__adjustForDisplayMode();
				this.__setImage();
				this.__setSubTitle();
				this.__setDescription();
				this.__setLinks();
			};
			
		self.prototype.__finishOffItem = function() {
				this.__updateAds();
				if (window.trackGallery) trackGallery(this.current, document.title);
				if (window.count_ivw) count_ivw();
				this.__in_progress = 0;
				this.__preloadImages();
			};

		self.prototype.__handleAd = function() {
				var exists;
				if (this.display_mode == 'rectangle1') {
					var exists = existsRectangle('rectangle1');
					if (exists) this.__adjustForDisplayMode();
					this.display_mode = 'gallery';
				}
				return exists;
			};

		self.prototype.__setSubTitle = function() {
				var container = this.__getElement('cgal-subtitle');
				if (!container) return;

				var item = this.items[this.current];

				if (item.title) {
					container.innerHTML = item.title;
					container.style.display = 'block';
				}
				else {
					container.innerHTML = '';
					container.style.display = 'none';
				}
			};

		self.prototype.__setDescription = function() {
				var container = this.__getElement('cgal-description');
				if (!container) return;

				var item = this.items[this.current];
				container.innerHTML = (item.text || this.global.text || '');
			};

		self.prototype.__setLinks = function() {
				var container = this.__getElement('cgal-links');
				if (!container) return;

				var links = this.items[this.current].links;

				var inner_html = '';
				
				if (typeof(links) == 'object') {
					for (var i = 0; i < links.length; i++) {
						inner_html += this.__createLink(links[i]);
					}
				}
				
				container.innerHTML = inner_html;
			};
			
		self.prototype.__createLink = function(data) {
				var text = data.text;
				var url  = data.url;
				
				if (!text || !url) return '';
				
				var handler = data.handler;
				var target  = data.target;
				
				var attribs = '';
				if (target)  attribs += ' target="' + target + '"';
				if (handler) attribs += ' handler="' + handler + '"';

				return '<a class="linkstyle" href="' + url + '"' + attribs + '>'
					+ '&gt;&nbsp;' + text
					+ '<\/a><br \/>\n';
			};

		self.prototype.__setImage = function() {
				var img = this.__getElement('cgal-image');
				if (!img) return;

				var item = this.items[this.current];
				
				var dir = (item.dir || this.defaults.img_dir);
				if (!dir || !item.img) return;
				
				var x = (item.x || this.defaults.x);
				var y = (item.y || this.defaults.y);
				
				var old_x = (parseInt(img.style.width)  || img.width  || 0);
				var old_y = (parseInt(img.style.height) || img.height || 0);
				
				if ((old_x && x && old_x != x) || (old_y && y && old_y != y)) {
					if (x) {
						img.width        = x;
						img.style.width  = x + 'px';
					}

					if (y) {
						img.height       = y;
						img.style.height = y + 'px';
					}
				}
				
				img.src = [dir, item.img].join('/');
				
				// IMPORTANT: no html entities in attribute values
				img.alt = (item.caption || item.title || '');
				img.title = img.alt;
				
				this.adjustImageContainer();

				var caption   = (item.caption || '');
				var copyright = (item.copyright || this.defaults.copyright);

				if (copyright) {
					if (caption) caption += ' - ';
					caption += 'Foto: &copy; ' + copyright;
				}

				var caption_container = this.__getElement('cgal-caption');
				if (caption_container) caption_container.innerHTML = (caption || '&nbsp;');
				
				var number_container = this.__getElement('cgal-number');
				if (number_container) number_container.innerHTML = 'Bild ' + (this.current + 1) + ' von ' + this.total;
			};
			
		self.prototype.__setMagnifier = function() {
				var magnifier_container = this.__getElement('cgal-magnifier');
				if (!magnifier_container) return;

				var item = this.items[this.current];
				var dir = (item.dir || this.defaults.img_dir)
				
				if (dir && item.orig_img) {
					var y = (item.y || this.defaults.y);
					magnifier_container.style.marginTop = (y - self.MAGNIFIER.y) + 'px';
					magnifier_container.style.display = 'inline';
				}
				else {
					magnifier_container.style.display = 'none';
				}
		};

		// Return value: NO FADE|FADING IN|FADED IN|FADING OUT|FADED OUT|empty string
		self.prototype.__setOpacity = function() {
				if (!this.do_fade) return 'NO FADE';
				
				if (!this.__current_fading) return;

				var img = this.__getElement('cgal-image');
				if (!img) return;

				++this.__fade_rounds;

				var duration = (new Date).getTime() - this.__start_time;
				var status = '';

				if (this.__current_fading == -1) {
					// Fading out
					if (this.__fade_rounds < self.MAX_FADE_ROUNDS
						&& duration < self.MAX_FADE_DURATION / 2
						&& this.__current_opacity - this.opacity_steps > self.MIN_OPACITY) {
						this.__current_opacity -= this.opacity_steps;
						status = 'FADING OUT';
					}
					else {
						if (this.__current_opacity > self.MIN_OPACITY) this.__current_opacity = self.MIN_OPACITY;
						this.__current_fading = 1;
						status = 'FADED OUT';
					}
				}
				else if (this.__current_fading == 1) {
					// Fading in
					if (this.__fade_rounds < self.MAX_FADE_ROUNDS
						&& duration < self.MAX_FADE_DURATION
						&& this.__current_opacity + this.opacity_steps < 100) {
						// Cases are necessary for smoother first fading in step.
						this.__current_opacity += this.__current_opacity == self.MIN_OPACITY ? 1 : this.opacity_steps;
						status = 'FADING IN';
					}
					else {
						this.__current_opacity = 100;
						this.__current_fading  =   0;
						status = 'FADED IN';
					}
				}

				if (self.IS_IE) {
					var bg_container = this.__getElement('cgal-image-bg');

					// IE < 8
					img.style.filter = 'alpha(opacity=' + this.__current_opacity + ')';
					if (bg_container) bg_container.style.filter = 'alpha(opacity=' + this.__current_opacity + ')';

					// IE-8: FIXME: check if property name is correct (in css probably: -ms-filter)
					// Must be *after* IE-7 definition??
					// Disable until needed
					// img.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + this.__current_opacity + ')';
				}
				else {
					// Just set other properties without browser check.
					var opacity_as_percent = this.__current_opacity / 100;

					img.style.opacity = opacity_as_percent;

					// Safari, Konqueror
					// FIXME: Do we need this?
					img.style.KhtmlOpacity = opacity_as_percent;
				}

				return status;
			};

		self.prototype.__fix_ie_02050a_pixels = function(flag) {
				if (!self.IS_IE) return;
				var container = this.__getElement('cgal-image-bg');
				if (!container) return;
				container.style.backgroundColor = flag ? self.IE_MISSING_PIXEL_COLOR : 'transparent';
			};
		
		self.prototype.__preloadImages = function() {
				this.__loaded = new Object;
				var index = this.current;

				var next_index = index + 1;
				if (next_index > this.total - 1) next_index = 0;
				var previous_index = index - 1;
				if (previous_index < 0) previous_index = this.total - 1;

				if (this.__loaded[next_index] && this.__loaded[previous_index]) return;

				try {
					// Important: Preloading requires freshly initialized Image objects.
					if (!this.__loaded[next_index]) {
						var image = new Image;
						var next_dir = (this.items[next_index].dir || this.defaults.img_dir);
						if (next_dir) image.src = [next_dir, this.items[next_index].img].join('/');
					}

					if (!this.__loaded[previous_index]) {
						var image = new Image;
						var previous_dir = (this.items[previous_index].dir || this.defaults.img_dir);
						if (previous_dir) image.src = [previous_dir, this.items[previous_index].img].join('/');
					}
				}
				catch(e) {}
			};

		self.prototype.__setCurrent = function() {
				this.current += (this.__direction || 0);
				if (this.current > this.total - 1) {
					this.current = 0;
				}
				else if (this.current < 0) {
					this.current = this.total - 1;
				}
			};
			
		self.prototype.__updateAds = function() {
				if (!window.SIMAdWriter) return;

				if (!(this.clicked % this.ad_interval)) {
					// Reset display_mode before update.
					this.display_mode = 'gallery';
					SIMAdWriter.updateAds(
						{
							triggered_for:     'contentgallery',
							callback_object:   this,
							callback_function: 'notify',
							callback_caller:   'rectangle1'
						});
				}
			};
			
		self.prototype.__adjustForDisplayMode = function() {
				if (this.display_mode == 'rectangle1') {
					setAttributeForElement('cgal-caption', 'visibility', 'hidden');
					setAttributeForElement('cgal-number', 'visibility', 'hidden');
					setAttributeForElement('cgal-info', 'visibility', 'hidden');
					setAttributeForElement('cgal-image-container', 'display', 'none');
					setAttributeForElement('cgal-ad-container', 'display', 'block');
				}
				else {
					setAttributeForElement('cgal-caption', 'visibility', 'visible');
					setAttributeForElement('cgal-number', 'visibility', 'visible');
					setAttributeForElement('cgal-info', 'visibility', 'visible');
					setAttributeForElement('cgal-image-container', 'display', 'block');
					setAttributeForElement('cgal-ad-container', 'display', 'none');
				}
			};

		self.prototype.__getElement = function(id) {
				if (!this.containers[id]) this.containers[id] = document.getElementById(id);
				return this.containers[id];
			};

		// For testing only
		self.prototype.__logMsg = function(msg) {
				var panel = this.__getElement('debug-panel');
				if (!panel) return;

				var container = this.__getElement('debug-panel-container');
				if (container) container.style.display = 'block';

				if (!panel.innerHTML.match(/\n$/)) panel.innerHTML += '<br />';
				panel.innerHTML += msg;
			};
	}

	this.__preloadImages();
}

function contentGalleryTeasers(args) {
		var self = arguments.callee;
		
		if (!args) args = new Object;

		if (!self.__constants) {
			self.__constants = 1;

			self.SCROLL_AMOUNT = 174;
			self.SCROLL_STEP   =   5;
			self.SCROLL_DELAY  =   0;
		}
		
		this.scroll = new Object;

		this.scroll.amount    = (args.scroll_amount || self.SCROLL_AMOUNT);
		this.scroll.step      = (args.scroll_step   || self.SCROLL_STEP);
		this.scroll.delay     = (args.scroll_delay  || self.SCROLL_DELAY);
		this.scroll.direction = 0;

		this.containers = new Object;

		if (!self.__init) {
			self.__init = 1;
			
			var app_ver = navigator.appVersion.toLowerCase();
			self.__is_msie = app_ver.indexOf('msie') >= 0 ? 1 : 0;
			
			self.prototype.doFocus = function(container) {
					if (!this.__adjustForTeaserTotal()) return;

					var teaser_display_container = this.__getElement('cgal-teaser-display');
					if (!teaser_display_container) return;

					if (!container) {
						var view = this.__getElement('cgal-teaser-view');
						if (!view) return;
						
						var divs = view.getElementsByTagName('div');
						
						for (var i = 0; i < divs.length; i++) {
							if (divs[i].className == 'cgal-teaser') {
								container = divs[i];
								break;
							}
						}
					}
					
					if (!container) return;

					if (this.active_teaser) this.active_teaser.className = 'cgal-teaser-image';

					var divs = container.getElementsByTagName('div');
					
					for (var i = 0; i < divs.length; i++) {
						var div = divs[i];
						var class_name = div.className;
						if (class_name == 'cgal-teaser-image') {
							div.className = 'cgal-teaser-image boxmodul2';
							this.active_teaser = div;
						}
						else if (class_name = 'cgal-teaser-text') {
							teaser_display_container.innerHTML = div.innerHTML;
						}
					}
				};

			self.prototype.scrollForward = function() {
					this.doScroll(1);
				};

			self.prototype.scrollBack = function() {
					this.doScroll(-1);
				};
			
			self.prototype.doScroll = function(direction) {
					if (!this.scroll.amount) return;

					var container = this.__getElement('cgal-teaser-view');
					if (!container) return;

					if (direction) {
						if (this.__scrolling) return;
						this.__scrolling = 1;
						// Argument *direction* is only passed with initial call,
						// not with recursion.
						this.scroll.direction = direction > 0 ? 1 : -1;
						this.scroll.todo = this.scroll.amount;
					}
					else {
						if (!this.scroll.direction) return;
					}
					
					if (!this.scroll.todo || this.scroll.todo < 0) {
						this.__scrolling = 0;
						return;
					}
					
					var step = this.scroll.step ;
					if (step > this.scroll.todo) step = this.scroll.todo;

					this.scroll.todo -= step;
					
					container.scrollLeft += step * this.scroll.direction;

					// Scope of setTimeout is window,
					// i.e. inside of setTimeout *this* refers to window
					var that = this;
					// Do not pass direction!
					setTimeout(function() {that.doScroll()}, (this.scroll.delay || 0));
				};
				
			self.prototype.__adjustForTeaserTotal = function() {
					if (!this.__adjusted) {
						this.__adjusted = 1;
						this.teaser_total = 0;
						var container = this.__getElement('cgal-teaser-container');
						if (container) {
							var teasers = container.getElementsByTagName('div');
							for (var i = 0; i < teasers.length; i++) {
								if (teasers[i].className == 'cgal-teaser') ++this.teaser_total;
							}
							container.style.width = (this.teaser_total * this.scroll.amount) + 'px'
						}
						
						if (!this.teaser_total) {
							var teaser_panel = this.__getElement('cgal-teasers');
							if (teaser_panel) teaser_panel.style.display = 'none';
							var cgal_spacer = this.__getElement('cgal-spacer');
							if (cgal_spacer) cgal_spacer.style.display = 'none';
						}
					}
					return this.teaser_total;
				};
				
			self.prototype.__getElement = function(id) {
					if (!this.containers[id]) this.containers[id] = document.getElementById(id);
					return this.containers[id];
				};
		}
	};

