/****************************** siemens' new web appearance script *****/
/****************************** Copyright (c) 2007-2009 Siemens AG *****/
/***********************************************************************/
/*********************************************** module gui select *****/
/***********************************************************************/
/************************************** author virtual identity AG *****/
/* $LastChangedDate: 2009-04-22 16:38:48 +0200 (Mi, 22 Apr 2009) $ *****/
/* Edited: 2009-09-12 10:56:00 +0200 (Mi, 12 Aug 2009)  by ChrisWell ***/

/********************************************************************/
/* START: functional initalisation                                  */

function init_guiSelect(transformer) {
    
	// register events for IE<6
	if(Info.browser.isIEpre6) {
		// add onchange handler and abandon initialization
		var selects = document.getElementById('content-zone').getElementsByTagName("select");
		for (var i = 0, l = selects.length; i < l; ++i) {
			var select = selects[i];
			if (select.className.match(/\bsearch-options\b/)) {
				select.onchange = function() {
					this.parentNode.parentNode.submit();
				}
			}
		}
		return;
	}
	
	// build and init gui select boxes
	
	GuiSelect.build($("content-zone").getElementsByTagName("select"), transformer);

	// init mousewheel

	var wheel = new MouseWheelObserver;
	wheel.register(
		function(value) {
			if (Layer.current && Layer.current.onmousescroll && Layer.current.scrollbar) {
				return Layer.current.onmousescroll(value);
			} else {
				return true;
			}
		}
	);
}

/* END: functional initalisation                                    */
/********************************************************************/
/* START: GuiSelect class                                           */

var GuiSelect = Class.create();

GuiSelect.sliderCounter = 0;

GuiSelect.build = function(elements, transformer, openImmediately) {
	transformer = transformer || GuiSelect.defaultTransformer;
	$A(elements).filter(
		function(select) {
			return $(select).hasClassName("search-options");
		}).each(
		function(select) {
			select = $(select);

			// build html

			var options        = $A(select.getElementsByTagName('option'));
			var index          = select.selectedIndex;
			var titleClassName = (index) ? 'title selected-title' : 'title';
			var text           = transformer.replaceTitle(options[index].text);
			var id             = select.id + '-gui';
			var className      = select.className;
			var wrappedText    = (select.disabled) ? '<span class="a">' + text + '</span>' : '<a href="javascript:void();">' + text + '</a>';

			var _html = '<div id="' + id + '" class="' + className + '"><p class="' + titleClassName + '">' + wrappedText + '</p>'
				+ '<input type="hidden" name="' + select.name + '" value="' + select.value + '" />'
				+ '<div class="content">';
			
			if (!select.disabled) {
				var isFirst = true;
				_html += '<ul>';
				options.each(
					function(option) {
						var classes = [];
						if (isFirst) {
							classes.push('first-child');
						}
						if (option.selected) {
							classes.push('selected');
						}
						var classSnippet = (classes.length) ? ' class="' + classes.join(' ') + '"' : '';
						
						var text = transformer.replaceOption(option.innerHTML);
						var rel = '';
						var href = 'javascript:void();';

						if(EXTOPTIONSLIGHTBOX_REL_REGEX.test(option.value) || option.value.match('trigger-contact'))
						{
							var key = option.value.split('|');
							rel = 'rel="'+key[0]+'"';
							href = key[1];
//							console.log("writing rel: " + rel + "|| with: " + href);
						}
						
						_html += '<li' + classSnippet +'><span class="value">' + option.value + '</span><a href="' + href + '" ' + rel + '>' + text + '</a></li>';
						isFirst = false;
					}
				);
				_html += '</ul>';
			}
			_html += '</div></div>';
			// replace html select element with new gui select element

			var wrapper = select.parentNode;
			Element.remove(select);
			wrapper.innerHTML += _html;
			
			if (select.disabled) {
				// if the select element is disabled, all is done
				return;
			}
			
			// init layer logic

			// optimized performance for IE6 and siemens search
			var div        = $(id);
			var form       = $(div.parentNode.parentNode);
			var input      = $(div.childNodes[1]);
			var contentDiv = $(div.childNodes[2]);
			var linkList   = $(contentDiv.firstChild);
			var links      = $A(contentDiv.getElementsByTagName('a'));
			var titleLink  = $(div.firstChild.firstChild);

			var layer   = new GuiSelectLayer(contentDiv);
			
			// add events to title
			
			titleLink.observe('focus', function() {
				layer.open();
			});
			titleLink.observe('click', function(e) {
				if (layer._state == 'open') {
					layer.close();
				} else if (layer._state == 'closed') {
					layer.open();
				}
				Event.stop(e);
			});
			
			// add events to links to submit form with selected value
			
			links.each(function(a) {
				a = $(a);

				if(a.rel && EXTOPTIONSLIGHTBOX_REL_REGEX.test(a.rel))
				{
					var id = a.rel.replace(
							EXTOPTIONSLIGHTBOX_REL_REGEX, "$1");
					var elm = "<div id='lightbox-layer-"
							+ id
							+ "' class='lightbox-layer'><div class='close'><a href='javascript:void(0);'>";
					elm += "<span class='access'>Close Layer</span></a></div>";
					elm += "<div class='layer-content'><div id='layer-content-"
							+ id + "'></div></div></div>";
					new Insertion.Before(
							$('footer-position-placeholder'), elm);
					var node = $("lightbox-layer-" + id);
					var key = "lightbox-layer-" + id;
					GLOBAL_LAYER_CONTROLLER[key] = new ExternalOptionsLightboxLayer(
							node, a, id);
				}

				
				a.observe('focus', function(e) {
					$(this.parentNode).addClassName('active');
					if (layer != Layer.current) {
						layer.open();
						if (layer.scrollbar) {
							layer.scrollbar.scrollIntoView(a.up('li'));
						}
					}
				}.bindAsEventListener(a));

				a.observe('blur', function(e) {
					$(this.parentNode).removeClassName('active');
				}.bindAsEventListener(a));
				
				a.observe('mouseover', function(e) {
					a.focus();
				}.bindAsEventListener(a));

				a.observe('mousemove', function(e) {
					a.focus();
				}.bindAsEventListener(a));

				
				a.observe('click', function(e) {
					Event.stop(e);
					/*
					if (this.up().hasClassName('selected')) {
						Layer.closeCurrent();
					} else {
					*/
						input.value = this.previous('span.value').innerHTML;
						titleLink.innerHTML = this.innerHTML;
						this.up().up().down('li.selected').removeClassName('selected');
						this.up().addClassName('selected');
						var myString = input.value;
						
						var TRIGGER_CONTACT_REL_REGEX = /^ext-trigger-contact$/;
//						console.log("click: "+this.rel+" | "+TRIGGER_CONTACT_REL_REGEX.test(this.rel));
						Layer.closeCurrent();
						if(myString == '')
						{	
							/* return on dropdown/no value label */
							return;
						}
						else if(myString.match('window.location.href ='))
						{
							window.location.href = myString.slice(("window.location.href = '").length,myString.lastIndexOf("'"));
						}
						else if(EXTOPTIONSLIGHTBOX_REL_REGEX.test(this.rel))
						{
							var imax = this.rel.replace(
									EXTOPTIONSLIGHTBOX_REL_REGEX, "$1");
							var kmax = "lightbox-layer-" + imax;
							GLOBAL_LAYER_CONTROLLER[kmax].toggle();
						}
						else if(TRIGGER_CONTACT_REL_REGEX.test(this.rel))
						{
//							console.log("drinn: "+TRIGGER_CONTACT_REL_REGEX.test(this.rel));
							IFRAME_CONTACT_LAYER["contact"].toggle();
						}
						else
						{
							window.open(myString.slice(("window.open('").length,myString.lastIndexOf("')")));
						}
//					}
				}.bindAsEventListener(a));

				// show nicer link on status bar:
				//a.href = '?' + input.name + '=' + encodeURIComponent(a.previousSibling.innerHTML);
			});
			
			// add scrollbar, if necessary

			if (linkList.getHeight() <= contentDiv.getHeight()) { // no slider needed

				contentDiv.style.height = 'auto'; // for IE6

			} else {

				GuiSelect.sliderCounter++;
				
				linkList.addClassName('has-scrollbar');

				/// add slider gui elements

				var sliderWrapper = document.createElement('div');
				sliderWrapper.className = 'slider-wrapper';
				sliderWrapper.innerHTML = '<div class="arrow-up"></div><div class="slider" id="slider' + GuiSelect.sliderCounter + '"><div class="handle" id="handle' + GuiSelect.sliderCounter + '"></div></div><div class="arrow-down"></div>';
				contentDiv.appendChild(sliderWrapper);

				// init scrollbar and add scrollbar object to layer

				layer.scrollbar = new GuiScrollbar("handle" + GuiSelect.sliderCounter, "slider" + GuiSelect.sliderCounter, layer);

				// add click events

				var elts = $(sliderWrapper).childElements();

				elts[0].observe("click", function() {
					layer.scrollbar.moveUp();
				});
				elts[2].observe("click", function() {
					layer.scrollbar.moveDown();
				});

				// add other evens

				var handler = (Info.browser.isIE) ? "activate" : "focus";

				links.each(function(a) {
					$(a).observe(handler, function(e) {
						layer.scrollbar.scrollIntoView($(this).up("li"));
					}.bind(a));
				});

			}
			
			// open immediately if option is true
			
			if (openImmediately) {
				layer.open();
			}
			
		}
	);	
}

GuiSelect.defaultTransformer = {
	replaceOption: Prototype.K,
	replaceTitle:  Prototype.K
}

/* END: GuiSelect class                                             */
/********************************************************************/
/* START: layer subclass for gui.select                             */

var GuiSelectLayer = Class.create();

GuiSelectLayer.prototype = Object.extend(new Layer, {

	list: null,
	scrollbar: null,
	_state: "closed",

	initialize: function(node, trigger) {
		this.name = "test"; //node.up().id.match(/^filter-(.*)-gui$/)[1];
		this.initSuper(node, trigger);
		this.list = node.firstChild;
	},

	afterClose: function() {
		this.node.up().removeClassName("active-gui-select");
		this._state = "closed";
		
		var activeFilter = this.node.up(2).previous();
		if (activeFilter && activeFilter.id == 'active-filter-' + this.name) {
			activeFilter.show().next().remove();
		}
	},

	afterOpen: function() {
		window.setTimeout(function() {
			this._state = "open";
		}.bind(this), 200);
	},

	beforeOpen: function() {
		this._state = "opening";
		this.node.up().addClassName("active-gui-select");
		if (this.scrollbar) {
			this.scrollbar.setValue(0);
		}
		return true;
	},

	hide: function() {
		this.node.removeClassName("active-content");
	},

	onkeydown: function(e) {
		var ITEMS_PER_PAGE = 9;

		if (Info.browser.isOpera) {
			// no key handling, since preventing default actions doesn't work with Opera
			// see: http://www.quirksmode.org/dom/events/keys.html
			return;
		}
		
		var activeListElement = this.getListElement();
		
		switch (e.keyCode) {
			case Event.KEY_UP:
				if (activeListElement && activeListElement.previous()) {
					this.setListElement(activeListElement.previous());
				}
				Event.stop(e);
				break;
				
			case Event.KEY_DOWN:
				if (activeListElement && activeListElement.next()) {
					this.setListElement(activeListElement.next());
				} else if (!activeListElement) {
					this.setListElement(this.node.select('ul li').first());
				}
				Event.stop(e);
				break;
			
			case Event.KEY_PAGEUP:
				if (activeListElement) {
					if (activeListElement.previous(ITEMS_PER_PAGE - 1)) {
						this.setListElement(activeListElement.previous(ITEMS_PER_PAGE - 1));
					} else {
						this.setListElement(this.node.select('ul li').first());
					}
				} else {
					this.setListElement(this.node.select('ul li').first());
				}
				Event.stop(e);
				break;
				
			case Event.KEY_PAGEDOWN:
				if (activeListElement) {
					if (activeListElement.next(ITEMS_PER_PAGE - 1)) {
						this.setListElement(activeListElement.next(ITEMS_PER_PAGE - 1));
					} else {
						this.setListElement(this.node.select('ul li').last());
					}
				} else {
					var length = this.node.select('ul li').length;
					this.setListElement(this.node.select('ul li')[Math.min(ITEMS_PER_PAGE, length)]);
				}
				Event.stop(e);
				break;

			case Event.KEY_HOME:
				this.setListElement(this.node.select('ul li').first());
				Event.stop(e);
				break;
				
			case Event.KEY_END:
				this.setListElement(this.node.select('ul li').last());
				Event.stop(e);
				break;
		}
	},

	getListElement: function() {
		var activeListElement = this.node.select('ul li.active');
		return activeListElement.length ? activeListElement[0]: null;
	},
	
	setListElement: function(newListElement) {
		if (newListElement) {
			$(newListElement).down('a').focus();
			if (this.scrollbar) {
				this.scrollbar.scrollIntoView(newListElement);
			}
		}
	},

	onmousescroll: function(value) {	
		var activeListElement = this.getListElement();
		if (value < 0) {
			this.scrollbar.moveUp();
			if (activeListElement && activeListElement.previous()) {
				this.setListElement(activeListElement.previous());
			}
		} else if (value > 0) {
			this.scrollbar.moveDown();
			if (activeListElement && activeListElement.next()) {
				this.setListElement(activeListElement.next());
			}
		}
		return false;
	},

	scrollTo: function(offsetTop) {
		this.list.style.top = offsetTop + "px";
	},

	show: function() {
		this.node.addClassName("active-content");
	}

});

/* END: layer subclass for gui.select                               */
/********************************************************************/
/* START: scrollbar class                                           */

var GuiScrollbar = Class.create();

GuiScrollbar.prototype = {

	initialize: function(handle, slider, layer) {

		this.outerHeight  = layer.node.getHeight();
		this.innerHeight  = $(layer.node.firstChild).getHeight();
		this.maxScroll    = this.innerHeight - this.outerHeight;
		this.itemHeight   = $(layer.node.firstChild.firstChild.nextSibling).getHeight();
		this.sliderHeight = $(slider).getHeight();

		$(handle).style.height = Math.round(this.sliderHeight * this.outerHeight / this.innerHeight) + "px";

		this.slider = new Control.Slider(handle, slider, {
			axis: 'vertical',
			range: $R(0, this.maxScroll),
			onSlide: function(value) {
				layer.scrollTo(-value);
			},
			onChange: function(value) {
				layer.scrollTo(-value);
			}
		});
	},
	
	moveDown: function() {
		this.setValue(this.slider.value + this.itemHeight);
	},

	moveUp: function() {
		this.setValue(this.slider.value - this.itemHeight);
	},

	scrollIntoView: function(liNode) {
		var offset = $(liNode).offsetTop;
		var minValue = this.slider.value;
		var maxValue = minValue + this.outerHeight;
		if (offset + this.itemHeight > maxValue) {
			this.setValue(offset + this.itemHeight - this.outerHeight);
		} else if (offset < minValue) {
			this.setValue(offset);
		}
	},

	setValue: function(value) {
		this.slider.setValue(value);
	}

}

/* END: scrollbar class                                             */
/********************************************************************/
/**
 * custom lightbox layer due to overwritten click event on gui-select drop down
 * therefore needed to overwrite this.initSuper()
 */
var EXTOPTIONSLIGHTBOX_REL_REGEX = /^ext-ql-lightbox-(.+)$/;

var ExternalOptionsLightboxLayer = Class.create();
ExternalOptionsLightboxLayer.prototype = Object.extend(new AbstractLightboxLayer,
		{
			initialize: function(node, trigger, idstring)
			{
				this.idstring = idstring;
				this.layerIdstring = "layer-content-" + idstring;
				this.node = node;
				this.iframehref = trigger.href;
				this.iframeidstring = "iframe-" + idstring;
				this.iframeisloaded = false;
				this.iframeheight = 50;
				this.curtainidstring = "lightbox-curtain" + idstring;
				var iframe = document.createElement('iframe');
				iframe.setAttribute('id', this.iframeidstring);
				iframe.setAttribute('name', this.iframeidstring);
				iframe.setAttribute('src', "about:blank");
				iframe.setAttribute('height', this.iframeheight + 'px');
				iframe.setAttribute('width', '100%');
				iframe.setAttribute('frameBorder', '0');
				iframe.setAttribute('border', '0');
				iframe.setAttribute('marginwidth', '0');
				iframe.setAttribute('marginheight', '0');
				iframe.setAttribute('scrolling', 'no');
				
				this.initSuper(node, trigger);
				
				var closeButton = Helper.getCloseButton(this.node);
				closeButton.observe("click", function() {
					this.close();
				}.bindAsEventListener(this));
				
				trigger.href = "javascript:void(0);";
				new Insertion.After($('content-zone'), "<div id='"
						+ this.curtainidstring
						+ "' class='lightbox-curtain'>&nbsp;</div>");
				this.curtain = $(this.curtainidstring);

				if (Info.browser.isIEpre7) {
					this.iframeLining = new IframeLining(this.curtain);
				}
				this.listener = {
					'augmentDone' :this.handleOpen.bind(this)
				};
				Event.observe(window, "resize", function() {
					this.resizeCurtain();
				}.bindAsEventListener(this));
				$(this.layerIdstring).appendChild(iframe);
			},

			initSuper: function(node, trigger) {
				this.node   = node;
				this.isOpen = false;
				this.trigger = trigger || null;

				if (Info.browser.isIEpre7) {
					this.iframeLining = new IframeLining(this.node);
					this.correctIframe();
				}

			},

			afterOpen : function() {
				if (!this.iframeisloaded) {
					this.setIFrameLocation();
					this.iframeisloaded = true;
				}
				else if(this.iframehref != this.iframecurrenthref) {
					this.setIFrameLocation();
				}
				else {
					this.correctCurtain();
				}
			},
			afterClose : function() {
				$(this.iframeidstring).src = 'about:blank';
				this.iframeheight = 50;
				this.iframeisloaded = false;
			},
			setIFrameLocation : function() {
				new Insertion.Before($(this.iframeidstring),
						"<div id='lightbox-preloader'>&nbsp;</div>");
				Event.observe($(this.iframeidstring), 'load', function(
						e) {
					this.rechunkIFrame(e);
				}.bindAsEventListener(this));
				$(this.iframeidstring).style.visibility = 'hidden';
				$(this.iframeidstring).src = this.iframehref;
			},
			correctCurtain : function() {
				if (this.curtain) {
					
					var wrapper = $('footer-position-wrapper').getDimensions();
					var header = $('header-zone').getDimensions();
					var toolbar = $('toolbar-zone');
					var footer = $('footer-zone');
					
					//	complete height of layer (close Button + iframe content)
					var iframeLayerHeight = $(Layer.current.layerIdstring).up().up().getDimensions().height;
					// total height for curtain/shadow 
					var wrapperHeight = parseInt(wrapper.height);						
					//	layer top position + layer height
					var iframeHeightTotal = parseInt(iframeLayerHeight) + parseInt(this.nodeTop);
					
					// occupied space for the iframe in the content zone
					//var iframeHeightInContentZone = iframeHeightTotal - (parseInt(header.height) + parseInt(toolbar.getDimensions().height));

					//	if layer distance (page top to the lower edge of the layer) is greater than current curtain, then correct curtain
					//	easy: if iframe greater than page

					//	< + footer.getDimensions().height
					if (wrapperHeight < iframeHeightTotal) {
						
						var contentHeightNew = iframeHeightTotal - header.height - toolbar.getDimensions().height; 
						this.diff = -1;
						//	resize content-zone height to total iframe/layer height + position top
						$('content-zone').setStyle( {
							'height' :contentHeightNew + 'px'
						});
						
						this.contentHeight = contentHeightNew;
						this.contentWidth = parseInt(wrapper.width);
						this.curtain.setStyle( {
							'height' :parseInt($('footer-position-wrapper').getDimensions().height) + 'px',
							'width' : this.contentWidth + 'px'
						});									
						if (this.iframeLining) {
							this.iframeLining.refresh();
						}
					}
					else {
						// no correction, but scroll to content (if lightbox is opened in footer etc)
						$('footer-position-wrapper').scrollTo();
					}
				}
			},
			rechunkIFrame : function(loadevt) {
				//	afterClose: sets iframe src=about:blank (IE video hack)
				//	==> fires this function
				//	==> layer/iframe already closed -> skip this function
				if(!Layer.current) return;
				var crossevt = (window.event) ? event : loadevt
				var iframeroot = (crossevt.currentTarget) ? crossevt.currentTarget
						: crossevt.srcElement
				if (iframeroot) {
					if (iframeroot.contentWindow) {
						iframeroot.contentWindow.document.body.style.backgroundImage = "url('')";
						iframeroot.contentWindow.document.body.style.backgroundColor = '#fff';
						if (iframeroot.contentWindow.document
								.getElementById('logo')) {
							iframeroot.contentWindow.document
									.getElementById('logo').style.display = 'none';
						}
						if (iframeroot.contentWindow.document
								.getElementById('header-zone')) {
							iframeroot.contentWindow.document
									.getElementById('header-zone').style.display = 'none';
						}
						if (iframeroot.contentWindow.document
								.getElementById('toolbar-zone')) {
							iframeroot.contentWindow.document
									.getElementById('toolbar-zone').style.display = 'none';
						}
						if (iframeroot.contentWindow.document
								.getElementById('breadcrumb-zone')) {
							iframeroot.contentWindow.document
									.getElementById('breadcrumb-zone').style.display = 'none';
						}
						if (iframeroot.contentWindow.document
								.getElementById('footer-zone')) {
							iframeroot.contentWindow.document
									.getElementById('footer-zone').style.display = 'none';
						}
						if (iframeroot.contentWindow.document
								.getElementById('llhc')
								&& iframeroot.contentWindow.document
										.getElementById('lrhc')) {
						}
						if (iframeroot.contentWindow.document
								.getElementById('content-zone')) {
							iframeroot.contentWindow.document
									.getElementById('content-zone').style.marginLeft = '0px';
						}
						if (iframeroot.contentWindow.document
								.getElementById('content-zone')) {
							var h = iframeroot.contentWindow.document
									.getElementById('content-zone').offsetHeight + 0;
							iframeroot.height = h;
							this.iframeheight = h;
						}
					} else if (iframeroot.contentDocument) {
						iframeroot.contentDocument.document.body.style.backgroundImage = "url('')";
						iframeroot.contentDocument.document.body.style.backgroundColor = '#fff';
						if (iframeroot.contentDocument.document
								.getElementById('logo')) {
							iframeroot.contentDocument.document
									.getElementById('logo').style.display = 'none';
						}
						if (iframeroot.contentDocument.document
								.getElementById('header-zone')) {
							iframeroot.contentDocument.document
									.getElementById('header-zone').style.display = 'none';
						}
						if (iframeroot.contentDocument.document
								.getElementById('toolbar-zone')) {
							iframeroot.contentDocument.document
									.getElementById('toolbar-zone').style.display = 'none';
						}
						if (iframeroot.contentDocument.document
								.getElementById('breadcrumb-zone')) {
							iframeroot.contentDocument.document
									.getElementById('breadcrumb-zone').style.display = 'none';
						}
						if (iframeroot.contentDocument.document
								.getElementById('footer-zone')) {
							iframeroot.contentDocument.document
									.getElementById('footer-zone').style.display = 'none';
						}
						if (iframeroot.contentDocument.document
								.getElementById('llhc')
								&& iframeroot.contentDocument.document
										.getElementById('lrhc')) {
						}
						if (iframeroot.contentDocument.document
								.getElementById('content-zone')) {
							iframeroot.contentDocument.document
									.getElementById('content-zone').style.marginLeft = '0px';
						}
						if (iframeroot.contentDocument.document
								.getElementById('content-zone')) {
							var h = iframeroot.contentDocument.document
									.getElementById('content-zone').offsetHeight + 0;
							iframeroot.height = h;
							this.iframeheight = h;
						}
					} else {
						return;
					}
					this.iframeisloaded = true;
					if ($('lightbox-preloader')) {
						$('lightbox-preloader').remove();
					}
					this.correctCurtain();
					$(this.iframeidstring).style.visibility = 'visible';
				}
			}
	
		});

/*****************************************************************************************/