/******************************* siemens' new web appearance script *****/
/******************************* Copyright (c) 2007-2008 Siemens AG *****/
/************************************************************************/
/************************************************** javascript core *****/
/************************************************************************/
/*************************************** author virtual identity AG *****/
/* $LastChangedDate: 2008-03-04 16:02:00 +0100 (Di, 04 Mrz 2008) $ *****/

// constants

var USE_FLASH_IN_HEADER = false; // could be overwritten in template

var SAFARI_STYLESHEET_REFERENCE = RESOURCES_PATH + "css/styles-safari.css";
var MACOS_STYLESHEET_REFERENCE  = RESOURCES_PATH + "css/styles-macos.css";
var SIFR_SLAB_PATH              = RESOURCES_PATH + "sifr/siemensslab.swf";

var LINK_REL_REGEX = /^jump-to-(.+)$/;

// global vars

var zone     = {};   // global hash for standard zones
var pageType = null; // page type, set in initGlobals()

// serve special styles for Safari and Mac OS

if (Info.browser.isSafari) document.write ("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + SAFARI_STYLESHEET_REFERENCE + "\" />");
if (Info.os.isMac)         document.write ("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + MACOS_STYLESHEET_REFERENCE + "\" />");

/********************************************************************/
/* START: layout initalisation                                      */

// inits global vars as std zones and page type

function initGlobals() {
	var ptReg = /^page-type-/;
	pageType = $(document.body).classNames().find(function(className) {
		return ptReg.test(className);
	}).replace(ptReg, "");

	$A(["content", "header"]).each(function(zoneId) {
		try {
			var _zone = $(zoneId + "-zone");
			if (!_zone) {
				throw ("Implementation Exception: Zone " + zoneId + " is missing.");
			}
			zone[zoneId] = _zone;
		} catch (e) {
			alert(e);
			return false;
		}
	});
	return true;
}

// provides min-width/max-width for IE < 7

function initLayout_IEPre7() {

	var innerWidth = Position.getWindowSize().width;

	if ($("toolbar-zone")) {
		if (innerWidth < 990) {
			$("toolbar-zone").setStyle({"width": "916px"});
		} else {
			$("toolbar-zone").setStyle({"width": (innerWidth - 66) + "px"});
		}
	}

	if (innerWidth > 960) {
		$("content-zone").style.width = "auto";
	} else {
		$("content-zone").style.width = "960px";
	}

	if ($("headervisual-zone") && $("fluid-zone") && pageType != "1" && pageType != "entry") {
		var realHeaderWidth = $("headervisual-zone").getWidth() + $("fluid-zone").getWidth();
		if (innerWidth <= realHeaderWidth) {
			var fluidWidth = $("fluid-zone").getWidth();
			var newWidth = innerWidth;
			newWidth = (newWidth - fluidWidth < 364) ? fluidWidth + 364 : newWidth;
			zone.header.setStyle({"width": newWidth + "px"});
		} else {
			zone.header.setStyle({"width": realHeaderWidth + "px"});
		}
	}
}

// inits sifr

function initLayout_sifr() {
	if (typeof sIFR != "function" || Info.browser.isOpera) return;

	sIFR.replaceElement(named({sSelector:"div.link-list span.sifr", sFlashSrc: SIFR_SLAB_PATH, sColor:"#666666", sHoverColor:"#990000", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr h3", sFlashSrc: SIFR_SLAB_PATH, sColor:"#333333", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-h1 h1", sFlashSrc: SIFR_SLAB_PATH, sColor:"#333333", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-h2 h2", sFlashSrc: SIFR_SLAB_PATH, sColor:"#666666", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-header h1", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-header h2", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-header h3", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sHoverColor:"#990000", sWmode:"transparent"}));
}

// replaces buttons by a-elements to provide rounded buttons

function initLayout_buttons() {
	$$("button.generic").each(function(elt) {

		if (!elt.form.id) {
			elt.form.id = Helper.getUniqueId();
		}

		var caption      = $(elt).innerHTML;
		var jsCode       = "javascript:submitForm('" + elt.form.id + "');";
		var cssClassName = "generic-button";

		linkAsButton = Builder.node('a', { className: cssClassName, href : jsCode}, [
			Builder.node('span', [Builder.node('span', [caption])]),
		]);

		$(elt).parentNode.replaceChild($(linkAsButton), $(elt));

	});
}
/* END: layout initalisation                                        */
/********************************************************************/
/* START: functional initalisation                                  */

function init_logo() {
	if ($("logo")) {
		$("logo").down().onclick = function() { window.open(this.href); return false; }
	}
}

function init_contentLayers() {
	if ($("toolbar-nav")) {
		$A($("toolbar-nav").getElementsByTagName("a")).each(
			function(trigger) {
				trigger = $(trigger);
				if (LINK_REL_REGEX.test(trigger.rel)) { // layer link
					var id = trigger.rel.replace(LINK_REL_REGEX, "$1");
					var node = $("toolbar-layer-" + id);
					new ContentLayer(node, trigger);
				} else { // standard link, probably external
					trigger.observe("click", function() {
						HeaderAnimation.animate = false;
						Layer.closeCurrent();
						HeaderAnimation.animate = true;
					}.bindAsEventListener(this));
				}
			}.bind(this)
		);
	}
}

function init_siteExplorer() {
	if ($("site-explorer-layer")) {
		trigger = $($("sitemap-link").getElementsByTagName("a")[0]);
		SiteExplorer.layer = new SiteExplorerLayer($("site-explorer-layer"), trigger);
	}
}

/* END: functional initalisation                                    */
/********************************************************************/
/* START: "abstract" layer - do not instantiate                     */

var Layer = Class.create();

Layer.current = null;
Layer.toggle = false;

Layer.initialize = function() {
	Event.observe(document, "click", function(e) {
		if (Layer.current) {
			var element   = $(Event.element(e));
			var layerNode = Layer.current.node;
			if (element != layerNode && !element.descendantOf(layerNode)) {
				Layer.closeCurrent();
			}
		}
	});
}

Layer.closeCurrent = function(newLayer) {
	if (Layer.current) {
		return Layer.current.close(newLayer);
		Layer.current = null;
	}
	return true; /* nothing to close, but ok */
}

Layer.prototype = {

	initialize: function() {
	},

	initSuper: function(node, trigger) {
		this.node   = node;
		this.isOpen = false;
		this.trigger = trigger;

		this.trigger.observe("click", function(e) {this.toggle(); Event.stop(e); }.bindAsEventListener(this));

		if (Info.browser.isIEpre7) {
			this.iframeLining = new IframeLining(this.node);
			this.correctIframe();
		}

	},

	open: function() {
		Layer.toggle = !!Layer.current;
		if(Layer.closeCurrent(this)) {
			if (this.beforeOpen()) {
				this.show();
				if (this.iframeLining) {
					this.iframeLining.show();
				}
				this.isOpen = true;
				Layer.current = this;
				Layer.toggle = false;
				this.afterOpen();
				return true;
			}
		}
		return false;
	},

	close: function(newLayer) {
		if (this.beforeClose(newLayer)) {
			if (this.iframeLining) {
				this.iframeLining.hide();
			}
			this.hide(newLayer);
			this.isOpen = false;
			Layer.current = null;
			this.afterClose(newLayer);
			return true;
		}
		return false;
	},

	toggle: function() {
		if (this.isOpen) {
			this.close();
		} else {
			this.open();
		}
	},

	afterClose: function() {},

	afterOpen: function() {},

	beforeClose: function() {
		return true;
	},

	beforeOpen: function() {
		return true;
	},

	correctIframe: function() {},

	hide: function(newLayer) {},

	show: function() {},

	superSetOffset: function(offset) {
		this.setOffset(offset);
		if (this.iframeLining) {
			this.iframeLining.refresh();
		}
	},

	setOffset: function(offset) {}

}

/* END: "abstract" layer                                            */
/********************************************************************/
/* START: content layer e. g. contact layer                         */

var ContentLayer = Class.create();

ContentLayer.prototype = Object.extend(new Layer, {

	initialize: function(node, trigger) {
		this.initSuper(node, trigger);

		var closeButton = Helper.getCloseButton(this.node);

		if(!closeButton) alert("Implementation Error: no close button found");

		closeButton.observe("click",
			function() {
				this.close();
			}.bindAsEventListener(this)
		);
	},

	afterClose: function(newLayer) {
		if (!Layer.toggle) {
			HeaderAnimation.augment();
		}
	},

	afterOpen: function() {
		HeaderAnimation.diminish();
	},

	beforeClose: function() {
		HeaderAnimation.unregisterLayer();
		return true;
	},

	beforeOpen: function() {
		HeaderAnimation.registerLayer(this);
		return true;
	},

	hide: function() {
		this.node.removeClassName("active-layer");
		this.trigger.up().removeClassName("active");
	},

	show: function() {
		this.node.addClassName("active-layer");
		this.trigger.up().addClassName("active");
		this.trigger.addClassName("clicked"); // avoids hover effect (only for the first time)
		this.trigger.observe("mouseout",
			function(e) {
				var elm = Event.findElement(e, "a");
				elm.removeClassName("clicked");
				elm.stopObserving("mouseout");
			}
		);
	},

	setOffset:function(offset) {
		this.node.style.top = offset + "px";
	}

});

/* END: content layer                                               */
/********************************************************************/
/* START: site explorer                                             */

var SiteExplorer = Class.create();

SiteExplorer.getContent = function() {
	// overwrite this to implement a custom method
	alert("Implementation Error: SiteExplorer.getContent is missing");
}

SiteExplorer.registerEvents = function(contentNode) {
	$A(contentNode.getElementsByTagName("a")).each(function(link) {
		link = $(link);
		if (link.hasClassName("page")) {
			link.observe("click", function(e) {
				SiteExplorer.followLink(link);
			});
		} else {
			link.observe("click", function(e) {
				SiteExplorer.toggleSubtree(link);
			});
		}
	});
}

SiteExplorer.toggleSubtree = function(node) {
	if (node.up().hasClassName("expanded")) {
		SiteExplorer.collapseSubtree(node);
	} else {
		SiteExplorer.expandSubtree(node);
	}
}

SiteExplorer.followLink = function(linkNode) {
	// not implemented
}

SiteExplorer.expandSubtree = function(linkNode) {
	// not implemented
}

SiteExplorer.collapseSubtree = function(linkNode) {
	// not implemented
}

/* END: site explorer                                               */
/********************************************************************/
/* START: site explorer layer                                       */
var SiteExplorerLayer = Class.create();

SiteExplorerLayer.prototype = Object.extend(new Layer, {

	initialize: function(node, trigger) {
		this.initSuper(node, trigger);

		var closeButton = Helper.getCloseButton(this.node);

		closeButton.observe("click",
			function() {
				this.close();
			}.bindAsEventListener(this)
		);

		this.content     = null;
		this.contentNode = $(document.createElement("div"));
		this.node.appendChild(this.contentNode);
	},

	afterClose: function(newLayer) {
		if (!Layer.toggle) {
			HeaderAnimation.augment();
		}
	},

	afterOpen: function() {
		if (Info.browser.isIE) { // correct float bug in all IE versions
			Helper.getCloseButton(this.node).setStyle(
				{
					position: "absolute",
					left: (this.contentNode.getDimensions().width - 20) + "px"
				}
			);
		}
		HeaderAnimation.diminish();
	},

	beforeClose: function() {
		HeaderAnimation.unregisterLayer();
		return true;
	},

	beforeOpen: function() {
		this.getContent();
		HeaderAnimation.registerLayer(this);
		return true;
	},

	hide: function() {
		$("site-explorer").removeClassName("active");
	},

	show: function() {
		$("site-explorer").addClassName("active");
		this.trigger.addClassName("clicked"); // avoids hover effect (only for the first time)
		this.trigger.observe("mouseout",
			function(e) {
				this.trigger.removeClassName("clicked");
				this.trigger.stopObserving("mouseout");
			}.bindAsEventListener(this)
		);
	},

	getContent: function() {
		if (!this.content) {
			this.content = SiteExplorer.getContent();
			this.contentNode.innerHTML = this.content;
			SiteExplorer.registerEvents(this.contentNode);
		}
	}

});

/* END: site explorer layer                                         */
/********************************************************************/
/* START: header zone animation                                     */

var HeaderAnimation = Class.create();

HeaderAnimation.initialize = function() {
	this.layer         = null;
	this.slide         = {}
	this.animate       = true;
	this.augmented     = true;

	if  (pageType == "1" || pageType == "2" || pageType == "entry") {
		if (USE_FLASH_IN_HEADER && Info.os.isMac && !Info.browser.isSafariGte3) {
			// deactivate animation on browsers that have problems with wmode=transparent */
			this.diminishable = false;
		} else {
			this.diminishable = true;
		}
	} else {
		this.diminishable = false;
	}

	this.diminish      = (this.diminishable) ? this.diminish_393 : function() {};
	this.augment       = (this.diminishable) ? this.augment_393 : function() {};

	this.toolbarNode   = $("toolbar-nav");
	this.toolbarHeight = (this.toolbarNode) ? this.toolbarNode.up().getHeight() : 0;
}

HeaderAnimation.augment_393 = function() {
	if (!this.augmented) {
		if (this.animate) {
			this._toggleAnimated([154, 174, 204, 244, 284, 324, 354, 385, 393]);
		} else {
			this._toggle(393);
		}
		this.augmented = true;
	}
}

HeaderAnimation.diminish_393 = function() {
	if (this.augmented) {
		if (this.animate) {
			this._toggleAnimated([363, 313, 263, 213, 183, 163, 152, 144]);
		} else {
			this._toggle(144);
		}
		this.augmented = false;
	}
}

HeaderAnimation.registerLayer = function(layer) {
	this.layer = layer;
	if(this.layer) {
		this.layer.superSetOffset(this.toolbarHeight + Position.cumulativeOffset(this.toolbarNode)[1]);
	}
}

HeaderAnimation.unregisterLayer = function() {
	this.layer = null;
}

HeaderAnimation._toggle = function(offset) {
	this.diminished = !this.diminished;
	this._setOffsets(offset);
}

HeaderAnimation._toggleAnimated = function(offsets) {
	this.slide.offsets = offsets;
	this.slide.length = offsets.length;
	this.slide.index = 1;

	this._toggle(this.slide.offsets[0]);

	new PeriodicalExecuter(function(pe) {
		if (this.slide.index >= this.slide.length) {
			this.diminished = !this.diminished;
			pe.stop();
		} else {
			this._setOffsets(this.slide.offsets[this.slide.index]);
			this.slide.index++;
		}
	}.bind(this), .06);
}

HeaderAnimation._setOffsets = function(offset) {
	$(document.body).style.backgroundPosition = "0 " + (offset - 393) + "px";
	zone.header.style.height = offset + "px";
	if(this.layer) {
		this.layer.superSetOffset(this.toolbarHeight + 1 + offset);
	}
}

/* END: header zone animation                                       */
/********************************************************************/
/* START: iframe to hide select elements in IE<7                    */

var IframeLining = Class.create();

IframeLining.prototype = {

	initialize: function(layer) {
		this.layer = layer;
		this.active = false;
		this.correction = {
			width:  0,
			height: 0,
			left:   0,
			top:    0
		} // since cumulativeOffset doesn't include borders

		this.div = $(document.createElement("div"));
		this.div.innerHTML = '<iframe src="javascript:false" frameborder="0" style="position:absolute; left:0; top:0; width:100%; height:100%; margin:0; padding:0; background:transparent; filter:alpha(opacity=0);"></iframe>';
		this.hide();
		document.body.appendChild(this.div);
	},

	show: function() {
		this.refresh();
		this.div.show();
		this.active = true;
	},

	refresh: function() {
		var dimension = $(this.layer).getDimensions();
		var position  = Position.cumulativeOffset(this.layer);
		this.div.setStyle(
			{
				height: (dimension.height + this.correction.height) + "px",
				left:   (position[0] + this.correction.left)        + "px",
				top:    (position[1] + this.correction.top)         + "px",
				width:  (dimension.width + this.correction.width)   + "px",
				position: "absolute",
				zIndex:   "1"
			}
		);
	},

	setOffset: function(offset) {
		this.div.style.top = offset + "px";
	},

	hide: function() {
		this.div.hide();
		this.active = false;
	}
}

/* END: iframe to hide select elements in IE<7                    */
/********************************************************************/
/* START: misc. helper                                              */

var Location = Class.create();

Location.setMarker = function(id) {
	// not implemented
}

Location.clearMarker = function() {
	// not implemented
}

var Popup = Class.create();

Popup.open = function(url, name, options) {
	options = $H(options).toQueryString().replace(/&/g, ",");
	window.open(url, name, options).focus();
}

var Helper = Class.create();

Helper._uniqueIdInt = 0;

Helper.getUniqueId = function() {
	Helper._uniqueIdInt++;
	return "unique-" + Helper._uniqueIdInt;
}

Helper.getCloseButton = function(layer) {
	var closeButton = layer.down("div.close");
	if (!closeButton) { // could be IE<6
		$A(layer.getElementsByTagName("div")).each(
			function(div) {
				if ($(div).hasClassName("close")) {
					closeButton = $(div);
				}
			}
		);
	}
	return closeButton;
}

// a wrapper to show a nicer function call in the status bar

function submitForm(id) {
	$(id).submit();
}

/* END: misc. helper                                                */
/********************************************************************/

