/// <reference path="/Scripts/jquery-vsdoc.js" />
var slash = "/"; var bslash = "\\"; var squote = "\'"; var dquote = "\"";

// put jQuery into no conflict mode so it doesn't collide with other libraries
jQuery.noConflict();

/*start MCH jQuery Extensions */

(function ($) {

	//for compatibility to jQuery versions before 1.9
	//if there is no browser object, create it.
	/*
	Contains flags for the useragent, read from navigator.userAgent.
	*/
	if (!$.browser) {
		var matched;
		var browser = {};

		$.uaMatch = function (ua) {

			ua = ua.toLowerCase();

			var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
				/(webkit)[ \/]([\w.]+)/.exec(ua) ||
				/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
				/(msie) ([\w.]+)/.exec(ua) ||
				ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
				[];

			return {
				browser: match[1] || "",
				version: match[2] || "0"
			};
		};

		matched = $.uaMatch(navigator.userAgent);

		if (matched.browser) {
			browser[matched.browser] = true;
			browser.version = matched.version;
		}

		// Deprecated, use jQuery.browser.webkit instead
		// Maintained for back-compat only
		if (browser.webkit) {
			browser.safari = true;
		}

		$.browser = browser;
	};

	/*
	jQuery.getCachedScript: Load a JavaScript file from the server using a GET HTTP request, then execute it.
	*/
	$.getCachedScript = function (url, callback) {

		// Allow user to set any option except for dataType, cache, and url
		var options = {
			dataType: "script",
			cache: true,
			url: url,
			success: callback
		};

		return $.ajax(options);
	};
	// jQuery.getLocalScript: Load a JavaScript file from the local server using a GET HTTP request, then execute it.
	$.getLocalScript = function (url, callback) {

		// Allow user to set any option except for dataType, cache, and url
		var options = {
			dataType: "script",
			cache: true,
			url: url,
			crossDomain: true,
			success: callback
		};

		return $.ajax(options);
	};
	// jQuery.removeSpecialCharWCFRequestValue: Removes special characters from a string
	$.removeSpecialCharWCFRequestValue = function (param) {
		if (param != null) {
			//remove the following characters * ? < > & # ' + % / :
			var regExp = new RegExp("([*?<>&#'+%/\:])+", 'g');
			//remove backslash "\"
			//double spaces "  "
			//double dots ".."
			return param.replace(regExp, " ").replace(/\\/g, " ").replace(/[ ]{2,}/g, " ").replace(/[.]{2,}/g, ".");
		}
		return param;
	};
	// jQuery.getCurrentHref: Gets the href of the url without the search part.
	$.getCurrentHref = function () {
		return document.location.href.replace(document.location.search, "").replace(document.location.hash, "");
	};
	//checks the selector, element, or jQuery object and return true if the selector do not match.
	$.fn.extend({
		isEmpty: function () {
			return this.length === 0 ? true : false;
		}
	});
	// jQuery.wait: Blocks the code execution for the specified number of milliseconds.
	$.wait = function (msecs) {
		var start = new Date().getTime();
		var cur = start
		while (cur - start < msecs) {
			cur = new Date().getTime();
		}
	};
})(jQuery);

/*end MCH jQuery Extensions */

/* ---------------------------------------------------------------------------------------
Methods adopted from the file global2.js.
*/

//Google Analytics Information senden
function SendGoogleAnalyticInfo(strAction, strValue) {
	try {
		if (typeof pageTracker != "undefined") {
			var strPath = window.location.pathname;
			if (typeof strPath != "undefined") {
				strPath = strPath + "?action=" + strAction;
				if (typeof strValue != "undefined" && strValue != "") {
					strPath = strPath + "&value=" + strValue.replace("&", "+").replace("&", "+");
				}
				pageTracker._trackPageview(strPath);
			}
		}
	}
	catch (err) {
		//alert("Error: \n\n" + err.description); 
	}
}

//Suche Fehlertext aus Html-Seiten eines WCF-Service
function GetWCFErrorText(strMessage) {
	var iBegin;
	var iEnd;
	var strMsgLower;
	var strMsg;

	strMsgLower = strMessage.toLowerCase();
	iBegin = strMsgLower.indexOf("<p class=\"intro\">")
	if (iBegin > 0) {
		strMsg = strMessage.substr(iBegin + 17);
		strMsgLower = strMsgLower.substr(iBegin + 17);
		iEnd = strMsgLower.indexOf("</p>")

		if (iEnd > 0) {
			return strMsg.substr(0, iEnd);
		}
	}

	strMsgLower = strMessage.toLowerCase();
	iBegin = strMsgLower.indexOf("<p>")
	if (iBegin > 0) {
		strMsg = strMessage.substr(iBegin + 3);
		strMsgLower = strMsgLower.substr(iBegin + 3);
		iEnd = strMsgLower.indexOf("</p>")

		if (iEnd > 0) {
			return strMsg.substr(0, iEnd);
		}
	}

	strMsgLower = strMessage.toLowerCase();
	iBegin = strMsgLower.indexOf("<h1>")
	if (iBegin > 0) {
		strMsg = strMessage.substr(iBegin + 4);
		strMsgLower = strMsgLower.substr(iBegin + 4);
		iEnd = strMsgLower.indexOf("</h1>")

		if (iEnd > 0) {
			return strMsg.substr(0, iEnd);
		}
	}

	strMsgLower = strMessage.toLowerCase();
	iBegin = strMsgLower.indexOf("<h2>")
	if (iBegin > 0) {
		strMsg = strMessage.substr(iBegin + 4);
		strMsgLower = strMsgLower.substr(iBegin + 4);
		iEnd = strMsgLower.indexOf("</h2>")

		if (iEnd > 0) {
			return strMsg.substr(0, iEnd);
		}
	}

	return strMessage;
}

//HtmlEncode
function HTMLEncode(str) {
	var div = document.createElement("div");
	var text = document.createTextNode(str);
	div.appendChild(text);
	return div.innerHTML;
}

// RemoveSpezialCharWCFRequestValue: also available as the jQuery extension method jQuery.removeSpecialCharWCFRequestValue
function RemoveSpezialCharWCFRequestValue(strValue) {
	if (strValue != null) {
		//Lösche * ? < > & # ' + % / :
		var regExp = new RegExp("([*?<>&#'+%/\:])+", 'g');
		//Lösche "\" und doppelte  Space und doppelte "."
		return strValue.replace(regExp, " ").replace(/\\/g, " ").replace(/[ ]{2,}/g, " ").replace(/[.]{2,}/g, ".");
	}
	return strValue;
}
//Wait Function: also available as the jQuery extension method jQuery.wait
function wait(msecs) {
	var start = new Date().getTime();
	var cur = start
	while (cur - start < msecs) {
		cur = new Date().getTime();
	}
}
//GetCurrentHref Function: also available as the jQuery extension method jQuery.getCurrentHref
function GetCurrentHref() {
	var strHref = document.location.href;
	var iPos = strHref.indexOf("?");
	if (iPos > 0)
		strHref = strHref.substr(0, iPos);
	return strHref;
}
//IsNumber Function: could be replaced by jQuery.isNumeric
function IsNumber(input) {
	if (input == null)
		return false;
	return (input - 0) == input && input.length > 0;
}

//start Datepicker configuration
function GetDatePickerConfig(strLanguageIsoCode, strLangIsoCode) {
	var d = new Date();
	var strYearRange = d.getFullYear().toString() + ":" + (d.getFullYear() + 1).toString();
	var dp = {
		showOn: "button",
		buttonImage: "/Sites/images/common/icons/calendar.gif",
		buttonImageOnly: true,
		changeMonth: true,
		changeYear: true,
		showOtherMonths: true,
		selectOtherMonths: true,
		showWeek: true,
		firstDay: 1,
		showAnim: 'slideDown',
		yearRange: strYearRange,
		dateFormat: "",
		weekHeader: "",
		dayNamesMin: "",
		monthNamesShort: "",
		nextText: "",
		prevText: ""
	};

	if (strLanguageIsoCode) {
		switch (strLanguageIsoCode.toLowerCase()) {
			case "de-ch":
				dp.regional = "de";
				dp.dateFormat = "d. MM yy";
				dp.weekHeader = "Wo";
				dp.dayNamesMin = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
				dp.monthNamesShort = ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
				dp.monthNames = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
				dp.nextText = "Weiter";
				dp.prevText = "Zurück";
				break;

			case "fr-ch":
				dp.regional = "fr-CH";
				dp.dateFormat = "d MM yy";
				dp.weekHeader = "Se";
				dp.dayNamesMin = ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"];
				dp.monthNamesShort = ["Jan", "Fév", "Mar", "Avr", "Mai", "Jun", "Jul", "Aoû", "Sep", "Oct", "Nov", "Déc"];
				dp.monthNames = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
				dp.nextText = "Suivant";
				dp.prevText = "Précédent";
				break;

			case "it-ch":
				dp.regional = "it";
				dp.dateFormat = "d MM yy";
				dp.weekHeader = "Se";
				dp.dayNamesMin = ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa"];
				dp.monthNamesShort = ["Gen", "Feb", "Maz", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"];
				dp.monthNames = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
				dp.nextText = "Avanti";
				dp.prevText = "Indietro";
				break;

			case "en-us":
				dp.regional = "en";
				dp.dateFormat = "d MM yy";
				dp.weekHeader = "Wk";
				dp.dayNamesMin = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
				dp.monthNamesShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
				dp.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
				dp.nextText = "Next";
				dp.prevText = "Back";
				break;

			case "pt-pt":
				dp.regional = "pt-BR";
				dp.dateFormat = "d MM yy";
				dp.weekHeader = "Se";
				dp.dayNamesMin = ["Do", "Sg", "Te", "Qa", "Qi", "Sx", "Sa"];
				dp.monthNamesShort = ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
				dp.monthNames = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
				dp.nextText = "Próximo";
				dp.prevText = "Anterior";
				break;

			case "es-es":
				dp.regional = "es";
				dp.dateFormat = "d MM yy";
				dp.weekHeader = "Se";
				dp.dayNamesMin = ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"];
				dp.monthNamesShort = ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
				dp.monthNames = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
				dp.nextText = "Siguiente";
				dp.prevText = "Anterior";
				break;

			default:
				dp.regional = "de";
				dp.dateFormat = "d MM yy";
				dp.weekHeader = "Wo";
				dp.dayNamesMin = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"];
				dp.monthNamesShort = ["Jan", "Feb", "Mrz", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
				dp.monthNames = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
				dp.nextText = "Weiter";
				dp.prevText = "Zurück";
				break;
		}
	}
	return dp;
}
//end Datepicker configuration

//Gets itemid and language from meta elements
var g_ScId = jQuery("meta[name=scID]").attr("content");
var g_Lang = jQuery("meta[http-equiv=Content-Language]").attr("content");
var g_strSearchParam = "q";
var g_strSearchUrl = "/global/Search.aspx";

jQuery(document).ready(function () {
	if (g_ScId == null || g_ScId == "") {
		g_ScId = jQuery("meta[name=scID]").attr("content");
	}
	if (g_Lang == null || g_Lang == "") {
		g_Lang = jQuery("meta[http-equiv=Content-Language]").attr("content");
	}
});

/*
End adopted Methods.
*/

//#region Webtrekk Information senden
/*start function CMCHWebtrekk()
 */

function CMCHWebtrekk()
{ }

CMCHWebtrekk.prototype.LinkTrackInit = function () {
	try {
		if (typeof (wt) == "object" && typeof (wt.linkTrackInit) == "function") //webtrekk V3
		{
			wt.linkTrackInit();
		}
	}
	catch (err) {//alert("Error: \n\n" + err.description); 
	}
}

CMCHWebtrekk.prototype.SendWebtrekkInfoFlyoutClickAnchor = function (strValue) {
	try {
		if (strValue != "") {
			var regExp = new RegExp('%2f', 'g');
			MCHWebtrekk.SendWebtrekkInfo("Flyout", "ClickAnchor/" + strValue.replace(regExp, "/"));
		}
	}
	catch (err) { //alert("Error: \n\n" + err.description);
	}
}

//strValue sollte ohne "/" beginnen und mit einem "/" enden.
//Die Werte werden mit "/" getrennt und NICHT encodet!
//Webtrekk übernimmt das encoding
CMCHWebtrekk.prototype.SendWebtrekkInfo = function (strModul, strValue) {
	try {
		if (typeof (strModul) == "undefined" || strModul == "") {
			strModul = "undefined";
		}
		strModul = strModul + "/"

		var strVal = "";
		if (typeof (strValue) != "undefined" && strValue != "") {
			strVal = jQuery.trim(strValue);
			if (strVal.length > 1) {
				var regExp = new RegExp('//', 'g');
				strVal = strVal.replace(regExp, "/");
				if (strVal.substr(0, 1) == "/")
					strVal = strVal.substr(1);
				if ((strVal.substr(strVal.length - 1, strVal.length)) != "/")
					strVal += "/";
			}
		}
		strVal = (strVal == "") ? strModul + "ajaxcall/" : strModul + strVal;

		if (typeof (wt) == "object" && typeof (wt.sendinfo) == "function") //webtrekk V3
		{
			wt.sendinfo({ linkId: webtrekk.contentId + strVal, customClickParameter: { 1: strVal } });
		}
		else if (typeof (wt_sendinfo) == "function") //webtrekk V2
		{
			wt_sendinfo(webtrekk.contentId + strVal, "click");
		}
	}
	catch (err) { //alert("Error: \n\n" + err.description);
	}
}

//Ajax PageSearch tracken
CMCHWebtrekk.prototype.SendWebtrekkPageSearch = function (param) {
	try {
		if (typeof (wt) == "object" && typeof (wt.sendinfo) == "function" && typeof (webtrekk) == "object") //webtrekk V3
		{
			if (param != null) {
				//Bein ersten Seitenaufruf soll kein Request abgesetzt werden. Dieser wird schon von der Page gesendet!
				if (webtrekk.internalSearch == null || webtrekk.internalSearch == "") {

					webtrekk.internalSearch = param.searchphrase;
					var wt2 = new webtrekkV3(webtrekk);
					wt2.customParameter = {
						1: param.source,
						2: param.type,
						3: param.page,
						4: param.sort,
						5: param.searchphrase
					};
					wt2.sendinfo();
				}
			}
			webtrekk.internalSearch = ""; //Für den nächsten Ajax-Request ermöglichen
		}
	}
	catch (err) { //alert("Error script.js: \n\n" + err.description);
	}
}

var MCHWebtrekk = new CMCHWebtrekk;

/*end function CMCHWebtrekk()
 */

/*
*********************************************************************************************************************************

because ngn needs, the mch class part has to be seperated into the script source "~\Sites\javascripts\Common\mch.cms.script.js". 

*********************************************************************************************************************************
*/

/* start Windows Phone 8 / Metro Fix */
(function () {
	if (navigator.userAgent.match(/IEMobile\/10\.0/i)) {
		var a = document.createElement("style");
		a.appendChild(document.createTextNode("@-ms-viewport{width: auto !important}"));
		document.head.appendChild(a);
	}
})();
/* end Windows Phone 8 / Metro Fix */

//#region start: Steuerung ScrollUp, Kontakt-SlideIn
(function ($) {
	$(document).ready(function () {
		try {
			// ScrollUp: Hide button while on initial viewport
			$(document).scroll(function () {
				var y = $(this).scrollTop(); // scroll position 
				if (y > 300) {
					$('.scrollup').fadeIn();
				} else {
					$('.scrollup').fadeOut();
				}
			});
			// ScrollUp: Generate clickable element in footer
			$("footer").append("<div class='scrollup'></div>");
			$('.scrollup').hide();
			$(".scrollup").click(function () {
				$('html, body').animate({
					scrollTop: $("body").offset().top
				}, 600, "swing");
			})
		} catch (except) { };

		//Kontakt-SlideIn
		$(".Kontakt-Slidein h3, .Kontakt-Slidein .close").click(function () {
			$(".Kontakt-Slidein").toggleClass("maximized");
		});
	});
})(jQuery);
//#endregion end: Steuerung ScrollUp, Kontakt-SlideIn
var MCH = function () {
	this.iDebugState = 0;
	this.widgets = [];
};

(function ($, prototype) {

	prototype.addWidget = function (widget) {
		//Add the widget to the mch object.
		var className = widget.constructor.name;
		if (className === undefined) {
			//IE Hack: ie doesn't know the name property of the constructor
			var arr = widget.constructor.toString().match(/function\s*(\w+)/);
			if (arr && arr.length == 2) {
				className = arr[1];
			}
		}
		if (className !== undefined) {
			mch[className] = widget;
		}
		//mch[widget.constructor.name] = widget;
		this.widgets.push(widget);
		// trigger init for late widgets
		if (this.inited && $.isFunction(widget.init)) widget.init()
	}

	prototype.trigger = function (event) {
		for (var i = 0, l = this.widgets.length; i < l; i++) {
			var widget = this.widgets[i];
			if ($.isFunction(widget[event])) {
				widget[event].apply(widget, arguments)
			}
		}
	}
	prototype.init = function () {

		// init ie8 fixes
		if ($("html.lt-ie9").length > 0) {
			this.util.isIE8 = true;
		}

		// set current text direction
		if ($("body").attr("dir") == "rtl") {
			this.util.textDirection = "rtl";
			this.util.defaultFloat = "right";
			this.util.oppositeFloat = "left";
		}

		// only init once
		if (this.inited) return;
		// init all widgets
		this.trigger('init');

		// only init once
		this.inited = true;
	}

	prototype.settings = {
		searchUrl: "/global/Search.aspx",
		currentLanguage: $("meta[http-equiv=Content-Language]").attr("content"),
		itemId: $("meta[name=scID]").attr("content")
	}

	prototype.util = {
		isIE8: false,
		textDirection: "ltr",
		defaultFloat: "left",
		oppositeFloat: "right",

		log: function (oArgs) {

			if (mch.iDebugState > 0) {
				var msg = "MCH:: ";
				if (typeof (oArgs) == "object") {
					msg += oArgs.toString();
				}
				else {
					msg += oArgs;
				}

				if (mch.iDebugState === 2) {
					if ($("#logger").length === 0) {
						$("body").append("<ul id='logger' style='position:fixed;top:0;left:0;' />");
					}
					$("<li />").appendTo("#logger").text(msg);
				}
				else if (typeof console == "object") {
					console.log(msg);
				}
			}
		}
	}

})(jQuery, MCH.prototype);

var MCHResponsive = function () {
	this.currentDevice = "xl";
	this.breakpointTimeout = null;
	this.mediaQueryTimeout = null;
};

(function ($, prototype) {

	prototype.init = function () {
		var context = this;
		// init ie8 fixes
		if ($("html.lt-ie9").length > 0) {
			this.util.isIE8 = true;
			this.ie8Polyfills.init();
			this.ie8Background.init();
		}

		// set current text direction
		if ($("body").attr("dir") == "rtl") {
			this.util.textDirection = "rtl";
			this.util.defaultFloat = "right";
			this.util.oppositeFloat = "left";
		}

		// create resize event for all size-specific functionality
		$(window).bind('load resize orientationchange', function () {
			context.handleResize();
		});

		// only init once
		if (this.inited) return;
		// init all widgets
		this.trigger("init");

		// only init once
		this.inited = true;
		// listen to resize event and dispatch layout calls to widgets
		//$(window).on('resize', $.proxy(this.trigger, this, 'layout'))

		// create elements
		this.createElements();

		// check for breakpoint change
		// call layout methods on change
		this.checkBreakPointChange();

		// initialize sitecoreResponsiveImageLoader plugin
		$("img:not(.logo *, .galleryvi img, .langnavimage, #bigPictureSlider *)").sitecoreResponsiveImageLoader();

		// can be removed - just to test the rtl view
		if (this.iDebugState > 0) {
			$(document).on("dblclick", function () {
				if ($("body").attr("dir") === "rtl") {
					$("body").attr("dir", "ltr");
					$("link[href='styles/default-rtl.css']").attr("href", "styles/default.css");

					this.util.textDirection = "ltr";
					this.util.defaultFloat = "left";
					this.util.oppositeFloat = "right";
				}
				else {
					$("body").attr("dir", "rtl");
					$("link[href='styles/default.css']").attr("href", "styles/default-rtl.css");

					this.util.textDirection = "rtl";
					this.util.defaultFloat = "right";
					this.util.oppositeFloat = "left";
				}
			});
		}
	}

	prototype.ie8Polyfills = function () {
		this.init = function () {
			if (!this.util.isIE8) return;

			$("body :last-child").addClass("last-child");
			$("body :nth-child(odd)").addClass("odd");
			$("body :nth-child(even)").addClass("even");
			$("body :nth-child(3n+1)").addClass("pf-3np1");
			$("body :nth-child(3n+3)").addClass("pf-3np3");
			$("body :nth-child(4n+1)").addClass("pf-4np1");
			$("body :nth-child(4n+4)").addClass("pf-4np4");
			$("body :nth-child(6n+1)").addClass("pf-6np1");
			$("body :nth-child(6n+6)").addClass("pf-6np6");
		}
	}

	prototype.ie8Background = function () {
		this.init = function () {
			if (!this.util.isIE8) return;
			$("body").prepend("<div class='ie8-background'></div>").css("background-image", "none").css("filter", "");
		}
	}

	prototype.createElements = function () {
		$("body").append([
			'<div class="visuallyhidden hide-on-all show-on-xxl" />',
			'<div class="visuallyhidden hide-on-all show-on-xl" />',
			'<div class="visuallyhidden hide-on-all show-on-l" />',
			'<div class="visuallyhidden hide-on-all show-on-m" />',
			'<div class="visuallyhidden hide-on-all show-on-s" />'
		].join(''));
	}

	prototype.readDevice = function () {

		var device = "";
		if ($(".show-on-s:visible").length > 0) {
			device = "s";
		}
		else if ($(".show-on-m:visible").length > 0) {
			device = "m";
		}
		else if ($(".show-on-l:visible").length > 0) {
			device = "l";
		}
		else if ($(".show-on-xl:visible").length > 0) {
			device = "xl";
		}
		else {
			device = "xxl";
		}
		return device;
	}

	prototype.checkBreakPointChange = function () {
		var newDevice = mch.readDevice();
		if (this.currentDevice != newDevice) {
			this.util.log("change device from " + this.currentDevice + " to " + newDevice);
			this.currentDevice = newDevice;
			this.handleBreakpoint();
			this.handleResize();
		}
	}

	prototype.handleBreakpoint = function () {
		this.trigger("onBreakpoint", mch.currentDevice);
		//$.observer is in another script source. This condition checks that.
		if ($.observer) {
			$.observer.publish("breakpoint:changed", mch.currentDevice);
		}
	}

	prototype.handleResize = function () {
		var context = this;
		if (this.breakpointTimeout !== null) {
			window.clearTimeout(this.breakpointTimeout);
		}
		mch.breakpointTimeout = window.setTimeout(function () {
			context.util.log("check breakpoint change");
			context.checkBreakPointChange();
		}, 50);

		this.trigger("onResize");
		//$.observer is in another script source. This condition checks that.
		if ($.observer) {
			$.observer.publish("window:resized");
		}
	}

})(jQuery, MCHResponsive.prototype);

// attach to window NS
window.mch = jQuery.extend(new MCH(), new MCHResponsive());

/* start widgets */

/* start widget lightbox*/

(function ($) {

	// object ctor
	function lightbox(el, config) {
		this.iosBugTimeout = 0;
		// dom node
		this.$el = $(el);

		// extend default config
		this.config = $.extend(true, {
			padding: 8,
			type: "image",
			live: false,
			tpl: {
				closeBtn: "<a title='' class='fancybox-item fancybox-close' href='javascript:;'><i class='fa fa-times'></i></a>",
				next: "<a title='' class='fancybox-nav fancybox-next' href='javascript:;'><i class='fa fa-chevron-right'></i></a>",
				prev: "<a title='' class='fancybox-nav fancybox-prev' href='javascript:;'><i class='fa fa-chevron-left'></i></a>"
			},
			helpers: {
				title: {
					type: "inside"
				},
				overlay: {
					locked: false
				}
			},
			beforeLoad: function () {
				// don't open on very small screens
				/*if (BW.currentDevice === "s") {
					return false;
				}*/
			}
		}, config);
	}

	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {
			// rewrite left and right arrow for rtl
			$("body").on("click", ".fancybox-next", function (ev, param) {
				if (mch.util.textDirection === "rtl" && param !== "redirected") {
					$(".fancybox-prev").trigger("click", "redirected");
					return false;
				}
			});
			$("body").on("click", ".fancybox-prev", function (ev, param) {
				if (mch.util.textDirection === "rtl" && param !== "redirected") {
					$(".fancybox-next").trigger("click", "redirected");
					return false;
				}
			});


			// disable open effects for ios - ios 6 has problems with these
			var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false);
			if (iOS) {
				this.config.openEffect = "none";
				this.config.closeEffect = "none";
				this.config.prevEffect = "none";
				this.config.nextEffect = "none";
				/* Dieser Code ist aufgrund von Problemen im OnlineCatalogue deaktiviert. Tests mit iOS 5, 6 und 7. Stefan
				this.config.beforeLoad = function () { clearInterval(this.iosBugTimeout); };
				this.config.beforeClose = function () {
					this.iosBugTimeout = setInterval(function () {
						if ($(".fancybox-overlay").is(":visible")) {
							$.fancybox.close();
							$(".fancybox-overlay").hide();
						}
					}, 400);
				}; */

			}

			$("a.lightbox, a.ico-zoom").fancybox(this.config);
		}

	})(lightbox.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new lightbox())

})(jQuery);

/* end widget lightbox*/

/* start widget languageSwitch */

(function ($) {

	// object ctor
	function languageSwitch(el, config) {

		this.mobileVersionCreated = false;
		this.wasOpen = false;
		// dom node
		this.$el = $(el);

		// extend default config
		this.config = $.extend(true, {

			default: 'option'

		}, config);

	}

	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {

			//Replace of the language-switching images
			$(".language-switch img").hover(
				function () {
					this.src = this.src.replace("-link", "-hover");
				},
				function () {
					this.src = this.src.replace("-hover", "-link");
				}
			);
		}

		prototype.onBreakpoint = function () {
			if (!this.mobileVersionCreated) {
				this.mobileVersionCreated = true;

				var $bigVersion = $(".language-switch");
				var $smallVersion = $(".language-switch-mobile");

				$smallVersion.find(".opener").html($bigVersion.find("a.active").html()).on("click", function () {
					$smallVersion.find("ul").slideToggle();
					// click anywhere else on the side should close the language switch
					if (!this.wasOpen) {

						$("body").on("click touchstart", function (e) {
							if (!$(e.target).is(".language-switch-mobile *")) {
								$smallVersion.find("ul").slideUp();
							}
						});

					}
					this.wasOpen = true;

					return false;
				});

				$smallVersion.find("ul").append($bigVersion.find("li:not(.active)").clone());
			}
		}

	})(languageSwitch.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new languageSwitch());

})(jQuery);

/* end widget languageSwitch*/

/* start widget genericNavigation*/
(function ($) {
	// object ctor
	function genericNavigation(el, config) {
		this.isInitialized = false;
	}
	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {
			if (!this.isInitialized) {
				//at first for locking because the multiple events
				this.isInitialized = true;
				$(".generic-navigation > ul").clone().appendTo(jQuery(".generic-navigation-mobile"));
			}
		}
	})(genericNavigation.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new genericNavigation())
})(jQuery);
/* end widget genericNavigation*/

/* start widget forms*/
(function ($) {
	// object ctor
	function forms(el, config) {
		this.isMobileInitialized = false;
	}
	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {
			// handle clicks outside of form-elements to hide softkeyboards
			$(document).bind("touchstart", function (e) {
				if (e.target && !$(e.target).is("input, textarea") && document && document.activeElement && document.activeElement.blur) {
					document.activeElement.blur();
				}
			});

			// handle "enter" of keyboard for all forms contained in a div.form or div.form-portlet
			$(document).bind('keypress', function (event) {
				var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
				var target = event.target.tagName.toLowerCase();
				if (key === 13 && target === "input") {

					var $parentForm = $(event.target).closest('div:has(input[type=submit])');
					var $button = $parentForm.find("input[type=submit].submit");
					if ($button.length === 0) {
						$button = $parentForm.find("input[type=submit]");
					}
					if ($button.length === 0) {
						$button = $parentForm.find("input[type=button]");
					}
					if ($parentForm.length > 0 && $button.length > 0) {
						event.preventDefault();
						$button.trigger("click");
						return false;
					}
				}
			});

			this.placeholderPolyfill();

			// hide validator spans without text
			$(".scfForm span:visible").each(function () {
				if ($(this).html() == "&nbsp;") {
					$(this).hide();
				}
			});
		}

		prototype.placeholderPolyfill = function () {
			// write placeholder if not supported by browser
			if (typeof Modernizr === "object" && !Modernizr.input.placeholder) {
				var inputsWithPlaceholder = $("input[placeholder]");

				if (inputsWithPlaceholder.length > 0) {
					// clear placeholder if field is focused
					inputsWithPlaceholder.bind("focus", function () { // on focus clear field
						if ($(this).val() === "" || $(this).val() === $(this).attr("placeholder")) {
							$(this).removeClass("placeholder").attr("value", "");
						}
					});

					// resets placeholder if field is still empty
					inputsWithPlaceholder.bind("blur", function () { // on blur, rewrite placeholder
						if ($(this).val() === "") {
							$(this).addClass("placeholder").attr("value", $(this).attr("placeholder"));
						}

					});

					// set placeholders on page load
					inputsWithPlaceholder.each(function () {
						if ($(this).val() === "") {
							$(this).addClass("placeholder").attr("value", $(this).attr("placeholder"));
						}
					});
				}

				// clear fields on submit (we don't want to submit placeholder texts
				$("form").submit(function () {
					$(".placeholder").val("");
					return true;
				});
			}
		}

	})(forms.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new forms())
})(jQuery);
/* end widget forms*/

/* start widget mchVideoPlayer*/
(function ($) {
	// object ctor
	function mchVideoPlayer(el, config) {
		this.AudioHeight = 30;
		this.width = "100%";
		this.height = "100%";
		this.aspectratio = "16:9";
		this.VideoJs = "https://lib.messe.ch/ajax/libs/jquery.mch.video/1.0/video.js";
		this.VideoCSS = "https://lib.messe.ch/ajax/libs/jquery.mch.video/1.0/video.css";
		this.IsInit = false;
	}
	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {
			if ($(".mchVideo").length > 0) {
				if (this.IsInit === false) {
					this.IsInit = true;

					if ($('#videocss').length === 0) {
						$('head').append('<link id="videocss" rel="stylesheet" type="text/css" href="' + this.VideoCSS + '">');
					}
					$.ajax({
						type: "GET",
						url: this.VideoJs,
						success: this.prepareVideos,
						dataType: "script",
						cache: true,
						context: this
					});
				}
			}
		}
		// called by MCH on resize
		prototype.onResize = function () {
			var context = this;
			$(".mchVideo").each(function () {
				if ($(this).data("mmtype") === "audio") {
					$(this).css("height", context.AudioHeight);
				}
				else {
					$(this).css("height", parseInt($(this).width() / $(this).data("aspectration")));
				}
			});
		}
		prototype.prepareVideos = function () {
			var context = this;
			var width;
			var height;

			$(".mchVideo").each(function () {
				if (typeof ($(this).data("videorun")) === "undefined") {
					$(this).data("videorun", "1");
					width = context.width;
					height = context.height;
					//Audio nur 30Pixel hoch
					if ($(this).data("mmtype") === "audio") {
						height = context.AudioHeight;
						var strWidth = $.trim($(this).data("width"));
						if (IsNumber(strWidth)) {
							width = strWidth;
						}
					}

					$(this).MchVideo({
						AudioVideoUrl: $(this).find("a").attr("href"),
						Width: width,
						Height: height,
						AspectRatio: $(this).data("aspectratio"),
						AspectRatioN: $(this).data("aspectration"),
						ImageUrl: $(this).find(".mchVideoImg").attr("src")
					});
				}
			});
		}
	})(mchVideoPlayer.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new mchVideoPlayer())
})(jQuery);
/* end widget mchVideoPlayer*/

/* start widget mchSlider*/
//Das PluginIn ist in Sites/javascripts/Common/plugins.js
(function (jQuery) {
	// object ctor
	function mchSlider(el, config) {
		this.ScriptLoad = false;
		this.BannerList = []; //Liste aller Banner die gerendert werden
		this.BannerRegList = []; //Liste aller Banner die mit InlineJS eingefügt wurden
		this.ButtonCloseClass = "SliderClose";
		this.DebugMode = false;
		this.Device = null; //EDevice.Desktop;
		this.BannerDeviceRendered = null; //In welchem Device sind die Banner aktuell gerendert
		this.IsTouchDevice = false;
		this.VideoFallBackImage = "//media.messe.ch/multimedia/DefaultVideoImage.jpg";
		this.KeyVisualRotatorList = [];
		this.FadeTime = 1000;
		this.VideoDelayAutoplayFadeTime = 1000;
		this.IOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false);
	}

	// declare methods
	(function (prototype) {

		//#region Banner DatenObjekte
		function BannerImage() { //Bilder der Banner
			this.Class = null;
			this.Title = null;
			this.Url = null;
			this.Target = null;
			this.UrlClass = null;
			this.Desktop = null;
			this.Tablet = null;
			this.Mobile = null;
		};

		//Objekt um die Banner zu sichern
		function BannerObject() {
			this.cssClass = null; //CSS-Klasse des Banner			
			this.position = null; //Position des Banner gemäss EPosition
			this.HeightDesktop = null; //Höhe der Banner- oder Skyscraper- Bilder für Desktop
			this.HeightTablet = null;
			this.HeightMobile = null;
			this.WidthDesktop = null;
			this.WidthTablet = null;
			this.WidthMobile = null;
			this.Images = []; //Bilder
		};
		function BannerReg() { cssClass = null; }; //Banner
		//var EPosition = { none: "none", header: "header", skyscraper: "skyscraper", footer: "footer", portlet: "portlet" };
		var EDevice = { XL: "XL", L: "L", M: "M", S: "S", XS: "XS" };
		var EKeyVisualNavigation = { ThumbsHorTop: "ThumbsHorTop", ThumbsHorBottom: "ThumbsHorBottom", ThumbsVerLeft: "ThumbsVerLeft", ThumbsVerRight: "ThumbsVerRight", Bullets: "Bullets", ThumbsOnly: "ThumbsOnly", ThumbsAndBullet: "ThumbsAndBullet", ThumbsNone: "ThumbsNone" };
		function KeyVisualRotatorObject() {
			this.cssClass = null;
			this.Slider = null;
			this.SliderData = null;
			this.Navigation = EKeyVisualNavigation.Bullets;
			this.Length = 0;
			this.Html = null;
			this.AttrClass = null;
			this.AttrStyle = null;
			this.AttrDevices = null;
			this.HasVideo = false;
			this.FirstMediaHeight = 0;
			this.FirstMediaWidth = 0;
			this.ServerMinMediaHeight = 0;
			this.ServerFirstMediaHeight = 0;
			this.Html5VideoPlayToEnd = false;
			this.ContentHeight = 0;
			this.SliderHeight = 0;
			this.CurrSlideId = 0;
			this.DeviceRendered = null; //In welchem Device ist der KeyVisual aktuell gerendert
			this.Animation = "slide";
			this.SliderType = null;
		};
		//#endregion BannerObjekte

		//#region init breakpoint
		prototype.init = function () {
			var context = this;
			try {

				//Banner und KeyVisualRotator verzögert starten. -> Device ist korrekt und block von 3en Skripten
				setTimeout(function () {
					var strDebug = jQuery.getQueryParam("dbg");
					context.DebugMode = (strDebug == "1" || strDebug == "true") ? true : false;
					context.Device = getCurrentDevice();
					context.BannerDeviceRendered = context.Device;
					//context.ScriptLoad = true;
					if (typeof Modernizr === "object") { context.IsTouchDevice = Modernizr.touch };

					//Banner in Array hinzufügen. Wurden mit JS-InlineCode in die Liste BannerRegList eingefügt

					context.BannerRegList.forEach(function (objBannerDataReg) {
						var bannerData = getBannerObject(context, objBannerDataReg.cssClass);
						if (bannerData) {
							context.BannerList.push(bannerData);
							if (renderBanner(context, bannerData)) {
								eval("init" + bannerData.cssClass + "()");
								SetBannerEvents(context, bannerData);
							}
						}
					});

					//KeyVisualRotator
					//Muss verzögert sein beim ersten Seitenaufruf
					context.KeyVisualRotatorList.forEach(function (objKeyVisualRotator) {
						//console.log("prototype.init()  Init:" + objKeyVisualRotator.cssClass);
						onBreakpointPrepareKeyVisualRotator(context, objKeyVisualRotator);
						SetEventsAfterBreakPoint(context, objKeyVisualRotator, true);
					});
					context.ScriptLoad = true;//Muss verzögert sein
				}, 200);
			}
			catch (exept) { console.log("Error Slider prototype.init(): " + exept.message); context.ScriptLoad = false; }
		}

		prototype.onBreakpoint = function () {
			//console.log('KeyVisual breakpoint: ' + mch.currentDevice);
			var context = this;
			context.Device = getCurrentDevice();
			//if (context.ScriptLoad && context.BannerDeviceRendered != context.Device) {
			if (context.ScriptLoad) {
				context.BannerDeviceRendered = context.Device;

				if (context.BannerList && context.BannerList.length > 0) {
					onBreakpointPrepareBanner(context);
				}

				if (context.KeyVisualRotatorList.length > 0) {
					context.KeyVisualRotatorList.forEach(function (objKeyVisualRotator) {
						var bSliderNewRestart = onBreakpointPrepareKeyVisualRotator(context, objKeyVisualRotator);
						SetEventsAfterBreakPoint(context, objKeyVisualRotator, bSliderNewRestart);
					});
				}
			}
		}


		prototype.onAjax = function () {
			//console.log('KeyVisual onAjax: ' + mch.currentDevice);
			var context = this;
			context.Device = getCurrentDevice();
			if (context.ScriptLoad) {
				if (context.KeyVisualRotatorList.length > 0) {
					context.KeyVisualRotatorList.forEach(function (objKeyVisualRotator) {
						var bSliderNewRestart = onBreakpointPrepareKeyVisualRotator(context, objKeyVisualRotator);
						SetEventsAfterBreakPoint(context, objKeyVisualRotator, bSliderNewRestart);
					});
				}
			}
		};
		//#endregion init breakpoint

		//function that starts lazy loaded sliders
		prototype.startSlider = function (sliderId) {
			var context = this;
			context.Device = getCurrentDevice();
			if (context.KeyVisualRotatorList.length > 0) {
				var sliderObject = jQuery.grep(context.KeyVisualRotatorList, function (objKeyVisualRotator) {
					if (objKeyVisualRotator.cssClass == sliderId) {
						//reset the slider object
						objKeyVisualRotator.DeviceRendered = undefined;
						return objKeyVisualRotator;
					}
				});
				if (sliderObject && sliderObject.length == 1) {
					//if DeviceRendered is undefined, the slider should be started.
					if (!sliderObject[0].DeviceRendered) {
						var bSliderNewRestart = onBreakpointPrepareKeyVisualRotator(context, sliderObject[0]);
						SetEventsAfterBreakPoint(context, sliderObject[0], bSliderNewRestart);
					}
				}
			}
		};


		//#region KeyVisual
		prototype.regKeyVisual = function (cssClass, strNavigationType) {
			var result = jQuery.grep(this.KeyVisualRotatorList, function (keyVisualRotator) {
				return keyVisualRotator.cssClass == cssClass;
			});
			if (!result.length == 1) {
				var $elem = jQuery('.' + cssClass);
				var keyVisualDataReg = new KeyVisualRotatorObject();
				keyVisualDataReg.cssClass = cssClass;
				keyVisualDataReg.Navigation = GetNavigationType(strNavigationType);
				keyVisualDataReg.Length = $elem.find(".rsContent").length;
				keyVisualDataReg.Html = $elem.html();
				keyVisualDataReg.AttrClass = $elem.attr("class");
				keyVisualDataReg.AttrStyle = $elem.attr("style");
				keyVisualDataReg.AttrDevices = $elem.attr("data-visible-devices");
				keyVisualDataReg.HasVideo = keyVisualDataReg.Html.indexOf('KeyVisualMediaVideo') > -1 ? true : false;
				keyVisualDataReg.ContentHeight = Math.max.apply(null, jQuery("." + cssClass).find(".rsContentBox").map(function () {
					return Math.round(jQuery(this).height());
				}).get()); //z.B. für Content unterhalb des Bild

				keyVisualDataReg.ServerMinMediaHeight = $elem.attr("data-minImgHeight");
				keyVisualDataReg.ServerFirstMediaHeight = $elem.attr("data-firstimgheight");
				keyVisualDataReg.Html5VideoPlayToEnd = $elem.attr("data-html5videoplaytoend").toLowerCase() == "true" ? true : false;
				keyVisualDataReg.SliderHeight = 0;
				keyVisualDataReg.DeviceRendered = null;

				if ($elem.hasClass("rsAnimationfade")) {
					keyVisualDataReg.Animation = "fade";
				}
				if ($elem.hasClass("rsSliderKeyVisual")) {
					keyVisualDataReg.SliderType = "keyvisual";
				}
				else { keyVisualDataReg.SliderType = "portlet"; }

				this.KeyVisualRotatorList.push(keyVisualDataReg);
			}
		};

		function GetNavigationType(strNavigationType) {
			if (strNavigationType) {
				for (var key in EKeyVisualNavigation) {
					if (strNavigationType == key) { return key };
				}
			}
			return EKeyVisualNavigation.Bullets;
		};


		function playVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData) {
			try {
				var $holder = $sliderData.currSlide.holder;
				if (typeof $holder === "object") {
					StopAndHideHtml5Video(objKeyVisualRotator, $holder); //Eventuell ist das Video von der vorherigen Navigation noch aktiv

					//Wenn die Videos eine Toolbar haben, werden die  Buttons nach oben verschoben, und der Fullscreen-Button ausgeblendet
					if ($sliderData.currSlide.content.context.classList && $sliderData.currSlide.content.context.classList.contains("rsVideoToolbar")) {
						jQuery($slider).find(".rsFullscreenBtn").hide();
						jQuery($slider).find(".rsBullets").addClass("rsBulletsRelocate");
					}
					else {
						jQuery($slider).find(".rsBullets").removeClass("rsBulletsRelocate");
						jQuery($slider).find(".rsFullscreenBtn").show();
					}

					//Ist der 1. Slide angezeigt und hat der ein Video mit autoplay -> stopAutoplay()
					if (objKeyVisualRotator.Html5VideoPlayToEnd === true && $sliderData.currSlideId === 0) {
						var html4Video = $sliderData.slides[0].content.find(".rsHtml4Video");
						if (html4Video && html4Video.length === 1 && jQuery(html4Video).attr("data-autoplay") === "autoplay") {
							$sliderData.stopAutoPlay(); //Video vom ersten Slide zu ende spielen
						}
					}

					ShowHtml5Video(context, objKeyVisualRotator, $sliderData, $holder, false);

					var video = $holder.find(".rsVideo"); //youtube/vimeo
					if (video && video.length == 1) {
						if (jQuery(video).attr("data-autoplay")) {
							var iDelay = parseInt(jQuery(video).attr("data-delayautoplay"));
							if (iDelay === "NaN" || iDelay < 100) { iDelay = 0; }
							setTimeout(function () {
								try {
									//$sliderData.ev.on('rsVideoPlay', function () {
									//	console.log("youtube play");
									//});
									//$sliderData.ev.on('rsVideoStop', function () {
									//	console.log("youtube stop");										
									//});
									$slider.royalSlider('playVideo'); //youtube/vimeo automatisch starten
								}
								catch (exept) {
									console.log("Error Slider playVideoKeyVisualRotator():" + exept.message);
								}
							}, iDelay);
						}
					}
				}
			}
			catch (exept) { console.log("Error Slider playVideoKeyVisualRotator():" + exept.message); }
		}


		function onBreakpointPrepareKeyVisualRotator(context, objKeyVisualRotator) {
			var bRemoveSlider = false;
			var $slider = jQuery('.' + objKeyVisualRotator.cssClass);

			if (typeof $slider != "object" || $slider.length == 0) {
				return bRemoveSlider; //AJAX
			}

			var bIsMobileDevice = IsDeviceMobile(context);
			var $sliderData = $slider.data("royalSlider");

			if (objKeyVisualRotator.DeviceRendered === context.Device && typeof $sliderData === "object") {// gleiches Device und banner läuft schon!!
				return false;
			}

			//if (objKeyVisualRotator.HasVideo && typeof $sliderData === "object" && $sliderData != null) {
			//	location.reload(); //Videoplayer funktioniert nicht immer! Seite neu laden.
			//	return;
			//}

			objKeyVisualRotator.CurrSlideId = 0;
			//Bei Video Slider neue laden
			if (typeof $sliderData === "object" && $sliderData !== null && objKeyVisualRotator.HasVideo) {
				objKeyVisualRotator.CurrSlideId = $sliderData.currSlideId;
				$sliderData.destroy(); //Slider zerstören, Html neu laden
				jQuery('.' + objKeyVisualRotator.cssClass).html('');
				jQuery('.' + objKeyVisualRotator.cssClass).attr("class", objKeyVisualRotator.AttrClass);
				jQuery('.' + objKeyVisualRotator.cssClass).attr("style", " " + objKeyVisualRotator.AttrStyle);
				jQuery('.' + objKeyVisualRotator.cssClass).attr("data-visible-devices", " " + objKeyVisualRotator.AttrDevices);
				jQuery('.' + objKeyVisualRotator.cssClass).html(objKeyVisualRotator.Html);
				bRemoveSlider = true;
			}

			jQuery('.' + objKeyVisualRotator.cssClass + ' .rsContent').each(function () {
				//im KeyVisual ist nur der erste Slide im gerenderten-HTML sichtbar: itemControl.Attributes.Add("style", "display:none;");
				jQuery(this).removeAttr("style");
				//Breakpoint S und XS keine Video anzeigen, sondern Bildgallerie
				var strAttrStyle = jQuery(this).attr("data-visible-devices");
				if (strAttrStyle && strAttrStyle.length > 0) {

					//S XS
					if (bIsMobileDevice && strAttrStyle.indexOf("S") === -1) {
						jQuery(this).remove();
						return true;
					}
					//M L XL
					if (bIsMobileDevice == false && strAttrStyle.indexOf("M") === -1 && strAttrStyle.indexOf("L") === -1) {
						jQuery(this).remove();
						return true;
					}
				}

				//Reihenfolge von Bild und Text/Link
				var strMedia = jQuery(this).find(".rsMediaHolder").html();
				var strContent = jQuery(this).find(".rsContentBox").html();

				if (bIsMobileDevice) //S Content vor dem Bild
					jQuery(this).find(".rsContentBox").insertBefore(jQuery(this).find(".rsMediaHolder"));
				else //Bild vor Content
					jQuery(this).find(".rsMediaHolder").insertBefore(jQuery(this).find(".rsContentBox"));

			});

			//console.log('KeyVisual breakpoint change layout neu: ' + context.Device + ', alt: ' + objKeyVisualRotator.DeviceRendered);
			objKeyVisualRotator.DeviceRendered = context.Device;

			if (bIsMobileDevice && objKeyVisualRotator.Navigation != EKeyVisualNavigation.ThumbsOnly
				&& objKeyVisualRotator.Navigation != EKeyVisualNavigation.ThumbsAndBullet) {
				$slider.find(".rsThumbMediaHolder").each(function () {
					jQuery(this).remove();
				});
			}

			//HintergrundVideos im KeyVisual ausblenden dafür Standbild anzeigen
			if (objKeyVisualRotator.HasVideo) {
				//VideoSlider
				$slider.find(".rsTypeVideoSlider .rsMediaHolder").each(function () {
					if (bIsMobileDevice) {
						jQuery(this).find("[id$='KeyVisualMediaVideoEx']").remove(); //youtube
						jQuery(this).find(".rsBtnCenterer").remove(); //MP4 PlayButton
					}
					else {
						var divConfig = jQuery(this).find(".rsHtml4Video");
						if (divConfig && divConfig.length === 1) {
							//jQuery(this).find(".rsMobileImage").hide(); //HTML5-Video Bild für Mobile ausblenden, wird bei Overflow eingeblendet
						}
						else {
							jQuery(this).find(".rsMobileImage").remove(); //Youtube/Vimeo Bild entfernen -> sonst kann der Player nicht starten
						}
					}
				});

				//VideoPortlet
				$slider.find(".rsTypeVideoPortletSlider .rsMediaHolder").each(function () {
					if (jQuery(this).find(".rsHtml4Video").length === 1) { //TODO SS kein Video!!
						//jQuery(this).find(".rsMobileImage").hide(); //HTML5-Video Bild für Mobile ausblenden
					}
					else {
						jQuery(this).find(".rsMobileImage").remove(); //Youtube/Vimeo Bild entfernen -> sonst kann der Player nicht starten
					}
				});
			}

			//console.log('KeyVisual breakpoint navigation: ' + strNavigation + objKeyVisualRotator.Navigation);
			eval(GetInitSliderString(bIsMobileDevice, objKeyVisualRotator));

			//Titel und Alt bei Bilder 
			setTimeout(function () {
				jQuery(".royalSlider .rsMediaHolder").each(function () {
					var media = this;

					var alt = jQuery(media).attr("data-alt");
					if (alt.length > 0)
						jQuery(media).find("img").attr("alt", alt);

					var title = jQuery(media).attr("data-title");
					if (title.length > 0)
						jQuery(media).find("img").attr("title", title);
				});
			}, 1000);

			//Bei nur Thumb wird im Breakpoint S der 1. Slide nicht ganz angezeigt
			if (objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsOnly
				|| objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsAndBullet) {
				$sliderData = $slider.data("royalSlider");
				if (typeof $sliderData === "object" && $sliderData.numSlides > 1) {
					$sliderData.goTo(2);
					$sliderData.goTo(1);
				}
			}

			//Bei ThumbsAndBullet die Bullets generieren
			if (objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsAndBullet) {
				var bClickNavigation = false; //Verriegelung Bullets-Click mit Pfeilen und Drap-Drop
				$sliderData = $slider.data("royalSlider");
				var html = "<div class=\"rsNav rsBullets rsThumbBullets\">";
				for (var i = 0; i < $sliderData.numSlides; i++) {
					if (i == $sliderData.currSlideId) {
						html += "<div class=\"rsNavItem rsBullet rsNavSelected rsThumbBullets-" + i + "\"><span></span></div>";
					}
					else {
						html += "<div class=\"rsNavItem rsBullet rsThumbBullets-" + i + "\"><span></span></div>";
					}
				}
				$slider.find(".rsNav").append(html + "</div>");

				//$slider.find(".rsThumbBullets div").click(function () { //Navigation wird von RS ausgeführt
				//	$sliderData.goTo(jQuery(this).attr('rel'));
				//	$slider.find(".rsThumbBullets div").removeClass("rsNavSelected");
				//	jQuery(this).addClass("rsNavSelected");
				//	return false;
				//});

				jQuery($slider.find(".rsBullet")).click(function () {
					bClickNavigation = true;
					setTimeout(function () {
						bClickNavigation = false;
					}, 2000);
				});

				$sliderData.ev.on('rsDragRelease', function (event) {
					setTimeout(function () {
						if (bClickNavigation == false) {
							$slider.find(".rsThumbBullets div").removeClass("rsNavSelected");
							var sliderLeft = $slider.offset().left;
							jQuery($slider.find(".rsThumb")).each(function (index) {
								if (jQuery(this).offset().left > sliderLeft) {
									$slider.find(".rsThumbBullets-" + index).addClass("rsNavSelected");
									return false;
								}
							});
						}
					}, 1000);
				});

				$sliderData.ev.on("rsBeforeAnimStart", function (event) {
					$slider.find(".rsThumbBullets div").removeClass("rsNavSelected");
					$slider.find(".rsThumbBullets-" + $sliderData.currSlideId).addClass("rsNavSelected");
				});
			}

			return bRemoveSlider;
		}

		function SetEventsAfterBreakPoint(context, objKeyVisualRotator, bSliderNewRestart) {
			var $slider = jQuery('.' + objKeyVisualRotator.cssClass);
			var $sliderData = $slider.data("royalSlider");

			if ($sliderData === null || typeof $sliderData !== "object" || typeof $slider !== "object" || $slider.length === 0 || $sliderData.slides === null) {
				return;
			}

			//1. Slide einblenden //Bug im IE Slide werden auch im overflow ganz kurz angezeigt
			$sliderData.slides[0].content.find(".rsMediaHolderHidden").removeClass("rsMediaHolderHidden");
			$sliderData.slides[0].content.find(".rsContentBoxHidden").removeClass("rsContentBoxHidden");

			//nächsten Slide bei Bedarf einblenden //Bug im IE Slide werden auch im overflow ganz kurz angezeigt
			$sliderData.ev.on('rsBeforeAnimStart', function (e, slideObject) {
				$sliderData.currSlide.holder.find(".rsMediaHolderHidden").removeClass("rsMediaHolderHidden");
				$sliderData.currSlide.holder.find(".rsContentBoxHidden").removeClass("rsContentBoxHidden");

				if (objKeyVisualRotator.Html5VideoPlayToEnd === true && objKeyVisualRotator.HasVideo) {
					var html4Video = $sliderData.currSlide.holder.find(".rsHtml4Video");
					if (html4Video && html4Video.length === 1 && jQuery(html4Video).attr("data-autoplay") === "autoplay") {
						$sliderData.stopAutoPlay(); //Video zu ende spielen
					}
					else {
						$sliderData.startAutoPlay(); //Bilder gemäss Animmation
					}
				}
			});

			setTimeout(function () {
				GetKeyVisualHeight(objKeyVisualRotator);
				ResizeKeyVisualRotator(context, objKeyVisualRotator);
			}, 100);

			if (bSliderNewRestart) {
				SetEventsAfterNewRestart(context, objKeyVisualRotator, $slider, $sliderData);
			}

			FixNavigationKeyVisual(context, objKeyVisualRotator, $slider, $sliderData);
		}

		//FF braucht sehr lange umd das Video zu starten
		function TryStartPlayVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData, count) {
			if (objKeyVisualRotator.HasVideo === false)
				return;

			if (typeof count !== "number")
				count = 0;

			if (count > 100)
				return;

			var $holder = $sliderData.currSlide.holder;
			if ($holder !== null && typeof $holder === "object") {
				if ($holder.find(".rsPreloader").length > 0) {
					//Slider noch nicht geladen warten auf RS
					setTimeout(function () {
						console.log("Slider found '.rsPreloader' nr. " + count);
						count++;
						TryStartPlayVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData, count);
					}, 100);
				}
				else {
					if ($holder.find(".rsHtml4Video").length > 0) {
						//Slider geladen und HTML4 Video vorhanden
						playVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData);
					}
				}
			}
		}

		function SetEventsAfterNewRestart(context, objKeyVisualRotator, $slider, $sliderData) {
			jQuery(window).resize(function () {
				setTimeout(function () {
					GetKeyVisualHeight(objKeyVisualRotator);
					ResizeKeyVisualRotator(context, objKeyVisualRotator);
				}, 150);
			});


			setTimeout(function () {
				if (jQuery("." + objKeyVisualRotator.cssClass).data('royalSlider') != null) {
					jQuery("." + objKeyVisualRotator.cssClass).data('royalSlider').ev.on('rsAfterContentSet', function (e, slideObject) {
						ResizeKeyVisualRotator(context, objKeyVisualRotator);
					});
				}
			}, 100);


			TryStartPlayVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData, 0);

			$sliderData.ev.on('rsAfterSlideChange', function (event) {
				//nächster Slide
				playVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData); //neuer Slide Video starten
			});

			$sliderData.ev.on('rsBeforeMove', function (event, type, userAction) {
				//alter Slide
				try {
					var $holder = $sliderData.currSlide.holder;
					StopAndHideHtml5Video(objKeyVisualRotator, $holder);
				}
				catch (exept) { console.log("Error Slider rsBeforeMove(): " + exept.message); }
			});

			$sliderData.ev.on('rsEnterFullscreen', function (event, originalEvent) {
				//Videos höhe anpassen
				setTimeout(function () {
					GetKeyVisualHeight(objKeyVisualRotator);
					ResizeKeyVisualRotator(context, objKeyVisualRotator);
					playVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData);
				}, 100);
			});

			$sliderData.ev.on('rsExitFullscreen', function (event, originalEvent) {
				//Videos anpassen
				setTimeout(function () {
					GetKeyVisualHeight(objKeyVisualRotator);
					ResizeKeyVisualRotator(context, objKeyVisualRotator);
					playVideoKeyVisualRotator(context, objKeyVisualRotator, $slider, $sliderData);
				}, 100);
			});
		}


		function FixNavigationKeyVisual(context, objKeyVisualRotator, $slider, $sliderData) {
			if ((IsDeviceMobile(context) === false) &&
				(objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsHorTop
					|| objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsVerLeft)) {
				$slider.prepend($slider.find('.rsNav'));
			}
		}

		function GetKeyVisualHeight(objKeyVisualRotator) {
			var $slider = jQuery("." + objKeyVisualRotator.cssClass);
			objKeyVisualRotator.FirstMediaHeight = jQuery($slider).find(".rsMediaHolder:first").height();
			objKeyVisualRotator.FirstMediaWidth = jQuery($slider).find(".rsMediaHolder:first").width();
			objKeyVisualRotator.SliderHeight = jQuery($slider).height();
		}

		function ResizeKeyVisualRotator(context, objKeyVisualRotator) {
			var bIsMobileDevice = IsDeviceMobile(context);
			var $slider = jQuery("." + objKeyVisualRotator.cssClass);

			if (bIsMobileDevice == false) {
				jQuery($slider).find("video").css("width", objKeyVisualRotator.FirstMediaWidth + "px");
				//.isFullscreen funktioniert leider nicht
				if (typeof jQuery($slider).attr("class") != "undefined" && jQuery($slider).attr("class").indexOf("rsFullscreen") === -1) {
					jQuery($slider).find(".rsOverflow").css("height", objKeyVisualRotator.SliderHeight + "px");
				}
			}

			//Bei ThumbsOnly oder ThumbsAndBullet den grossen Bereich entfernen
			if (objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsOnly
				|| objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsAndBullet) {
				$slider.find(".rsOverflow").remove();
				$slider.css("height", "");
			}
		}

		function GetInitSliderString(bIsMobileDevice, objKeyVisualRotator) {
			var strNavigation = "()";
			if (bIsMobileDevice && objKeyVisualRotator.Navigation != EKeyVisualNavigation.ThumbsOnly
				&& objKeyVisualRotator.Navigation != EKeyVisualNavigation.ThumbsAndBullet) {
				if (objKeyVisualRotator.Navigation === EKeyVisualNavigation.ThumbsNone || objKeyVisualRotator.Length > 30) {
					strNavigation = "('none')";
				}
				else {
					strNavigation = "('bullets')";
				}
			}
			return "init" + objKeyVisualRotator.cssClass + strNavigation;
		}
		//#endregion KeyVisual

		//#region Banner		
		prototype.regBanner = function (cssClass) {
			var bannerDataReg = new BannerReg();
			bannerDataReg.cssClass = cssClass;
			this.BannerRegList.push(bannerDataReg);
		}

		function getBannerObject(context, cssClass) {
			var bannerData = null;
			var $slider = jQuery(".config" + cssClass);

			if ($slider.length == 1) {
				bannerData = new BannerObject();
				bannerData.cssClass = cssClass;
				bannerData.position = jQuery($slider).attr("data-position");
				bannerData.WidthDesktop = jQuery($slider).attr("data-width-desktop");
				bannerData.WidthTablet = jQuery($slider).attr("data-width-tablet");
				bannerData.WidthMobile = jQuery($slider).attr("data-width-mobile");
				bannerData.HeightDesktop = jQuery($slider).attr("data-height-desktop");
				bannerData.HeightTablet = jQuery($slider).attr("data-height-tablet");
				bannerData.HeightMobile = jQuery($slider).attr("data-height-mobile");

				jQuery($slider).find("div").each(function () {
					var image = new BannerImage();
					image.Class = jQuery(this).attr("class");
					image.Title = jQuery(this).attr("data-title");
					image.Url = jQuery(this).attr("data-url");
					if (jQuery(this).attr("data-url-target")) {
						image.Target = jQuery(this).attr("data-url-target");
					}
					if (jQuery(this).attr("data-url-class")) {
						image.UrlClass = jQuery(this).attr("data-url-class");
					}
					image.Desktop = jQuery(this).attr("data-src-desktop");
					image.Tablet = jQuery(this).attr("data-src-tablet");
					image.Mobile = jQuery(this).attr("data-src-mobile");
					bannerData.Images.push(image);
				});
			}
			return bannerData;
		}

		function renderBanner(context, bannerData) {
			var bReturn = false;
			if (bannerData && bannerData.Images.length > 0) {
				var strStyle = null;

				switch (context.Device) {
					case EDevice.M:
						strStyle = " style=\"width:" + bannerData.WidthTablet.toString() + "px;height:" + bannerData.HeightTablet.toString() + "px;\"";
						break;
					case EDevice.S:
					case EDevice.XS:
						strStyle = " style=\"width:" + bannerData.WidthMobile.toString() + "px;height:" + bannerData.HeightMobile.toString() + "px;\"";
						break;
					default:
						strStyle = " style=\"width:" + bannerData.WidthDesktop.toString() + "px;height:" + bannerData.HeightDesktop.toString() + "px;\"";
						break;
				};
				var $wrapper = jQuery("<div class=\"SliderContent BannerContent royalSlider " + bannerData.cssClass + "\"" + strStyle + ">");

				var iAnzBanner = RenderBannerImage(context, bannerData, $wrapper);
				if (iAnzBanner > 0) {
					bReturn = true;
					if (iAnzBanner === 2) //BUG in Slider: mit 2 Slides kein Loop
					{
						RenderBannerImage(context, bannerData, $wrapper);
					}
				}
				if (bReturn) {
					jQuery($wrapper).insertAfter(jQuery(".config" + bannerData.cssClass));
				}
			}
			return bReturn;
		}

		function RenderBannerImage(context, bannerData, $wrapper) {
			var iCount = 0;
			bannerData.Images.forEach(function (bannerImage) {
				var strSrc = null;
				switch (context.Device) {
					case EDevice.M:
						strSrc = bannerImage.Tablet;
						break;
					case EDevice.S:
					case EDevice.XS:
						strSrc = bannerImage.Mobile;
						break;
					default:
						strSrc = bannerImage.Desktop;
						break;
				};

				if (strSrc && strSrc.length > 0) {
					var $divBanner = jQuery("<div class=\"rsBanner rsId" + bannerImage.Class + " " + bannerImage.UrlClass + "\">").appendTo($wrapper);
					var $image;
					if (bannerImage.Url && bannerImage.Url.length > 0) {
						$image = jQuery("<img>", {
							class: "rsImg rsImgBanner rsImgBannerHidden rsImgBannerLink",
							src: strSrc,
							alt: bannerImage.Title,
							title: bannerImage.Title,
							onclick: "mch.mchSlider.bannerclick('" + bannerImage.Url + "', '" + bannerImage.Target + "')"
						});
					} else {
						$image = jQuery("<img>", {
							class: "rsImg rsImgBanner rsImgBannerHidden",
							src: strSrc,
							alt: bannerImage.Title,
							title: bannerImage.Title
						});
					}
					$image.appendTo($divBanner);
					iCount = ++iCount;
				}
			});
			return iCount;
		}

		prototype.bannerclick = function (strUrl, strTarget) {
			if (strUrl && strUrl.length > 0) {
				MCHWebtrekk.SendWebtrekkInfo('BannerClick', strUrl);
				setTimeout(function () { //Warten bis Webtrekk gesendet
					if (strTarget === "_blank") {
						try { console.log("target:" + strTarget); window.open(strUrl, strTarget); }
						catch (err) { document.location = strUrl; }
					} else { document.location = strUrl; }
				}, 500);
			}
			return true;
		}

		function onBreakpointPrepareBanner(context) {
			context.BannerList.forEach(function (bannerData) {
				var strSlector = "." + bannerData.cssClass;
				var $slider = jQuery(strSlector).data('royalSlider');
				if ($slider != null && typeof $slider == "object") {
					$slider.destroy(); //aktiven Slider stoppen, zerstören und das HTML entfernen
				}
				jQuery(strSlector).remove();

				if (renderBanner(context, bannerData)) {
					eval("init" + bannerData.cssClass + "()");
					SetBannerEvents(context, bannerData);
				}
			});
		}

		function SetBannerEvents(context, bannerData) {
			var $slider = jQuery('.' + bannerData.cssClass);
			var $sliderData = $slider.data("royalSlider");

			if (typeof $sliderData != "object" || typeof $slider != "object" || $slider.length == 0) {
				return;
			}

			////1. Slide einblenden //Bug im IE Slide werden auch im overflow ganz kurz angezeigt
			$sliderData.slides[0].content.find(".rsImgBannerHidden").removeClass("rsImgBannerHidden");

			////nächsten Slide bei Bedarf einblenden //Bug im IE Slide werden auch im overflow ganz kurz angezeigt
			$sliderData.ev.on('rsBeforeAnimStart', function (e, slideObject) {
				$sliderData.currSlide.holder.find(".rsImgBannerHidden").removeClass("rsImgBannerHidden");
			});
		}
		//#endregion Banner

		//#region Video und Helper

		//Click auf Button Video starten
		prototype.playclick = function (sliderId) {
			try {
				var objKeyVisualRotator = null;
				if (this.KeyVisualRotatorList) {
					this.KeyVisualRotatorList.forEach(function (obj) {
						if (obj.cssClass && obj.cssClass === sliderId) {
							objKeyVisualRotator = obj;
						}
					});
				}

				var $sliderData = jQuery('.' + sliderId).data("royalSlider");
				var $holder = $sliderData.currSlide.holder;
				if (typeof $holder == "object") {
					ShowHtml5Video(this, objKeyVisualRotator, $sliderData, $holder, true);
				}
			}
			catch (exept) { console.log("Error Slider playclick(): " + exept.message); }
			return true;
		}


		function StopAndHideHtml5Video(objKeyVisualRotator, $holder) {
			//console.log("HideVideo. " + $holder.find("div").attr("class"));			
			var video = $holder.find("video"); //Video-Tag
			var html4Video = $holder.find(".rsHtml4Video");
			var bVideoAutoplay = false;

			if (video != null && video.length === 1) {
				//console.log("PauseVideo : " + objKeyVisualRotator.Animation);
				video[0].pause();
				//video[0].currentTime = 0;
			}

			if (html4Video && html4Video.length === 1 && jQuery(html4Video).attr("data-autoplay") === "autoplay") {
				bVideoAutoplay = true;
			}

			if (objKeyVisualRotator.Animation != "fade" || bVideoAutoplay == false) {
				//console.log("RemoveVideo : " + objKeyVisualRotator.Animation);
				$holder.find(".rsMainSlideImage").show();
				$holder.find(".rsBtnCenterer").show();
				$holder.find(".rsContentBox").show();
				var video = $holder.find("video"); //Video-Tag
				if (video != null && video.length === 1) {
					video[0].pause();
					video.hide();
					video.remove();
					//console.log("RemoveVideo" + video.html());
				}
			}
		}


		//bStart -> Video sofort starten
		function ShowHtml5Video(context, objKeyVisualRotator, $sliderData, $holder, bStart) {
			//console.log("ShowHtml5Video. " + $sliderData.currSlide.holder.find("div").attr("class"));

			var html4Video = $holder.find(".rsHtml4Video");
			var video = $holder.find("video");
			//Video-Config ist vorhanden		
			if (html4Video && html4Video.length === 1) {

				//Manuel Start mit Button-Click oder Video ist im autoplay
				if (bStart || jQuery(html4Video).attr("data-autoplay") === "autoplay") { //Video autostart

					//Videos im Breakpoint S nur bei PortletVideos starten
					if (jQuery(html4Video).attr("data-type") === "VideoPortletSlider"
						|| context === null || IsDeviceMobile(context) === false) {

						if (video === null || video.length === 0) {
							//noch kein Video-Tag vorhanden, ein neues erstellen
							RenderVideoTag(context, objKeyVisualRotator, $sliderData, $holder, bStart, html4Video);
						}
						else {
							//video[0].currentTime = 0;
							video[0].play();
						}
					}
				}
			}
		}

		function RenderVideoTag(context, objKeyVisualRotator, $sliderData, $holder, bStart, html4Video) {
			var strSupport = jQuery(html4Video).attr("data-error");
			var strConf = " ";
			//console.log("IS iOS: " + mch.mchSlider.IOS);

			if ((jQuery(html4Video).attr("data-controls") === "controls") || mch.mchSlider.IOS) {
				strConf = "controls ";
			}

			if (bStart) { //Ton ein wenn manuel Start mit Button
				strConf += (jQuery(html4Video).attr("data-muted") === "muted") ? " muted " : "";
			}
			else {  //Video immer ohne Ton -> preload Video//Video wird noch ausgeblendet
				strConf += " muted style=\"display:none;\" ";
			}

			//loop=\"loop\"
			html4Video.after("<video  preload=\"auto\" autoplay=\"autoplay\" " + strConf + ">"
				+ "<source type=\"video/mp4\" src=\"" + jQuery(html4Video).attr("data-video") + "\" />"
				+ "<div class=\"rsVideoError\">"
				+ "<img class=\"rsThumbMedia constrain rsPortrait\" src=\"" + jQuery(html4Video).attr("data-img") + "\" "
				+ " alt=\"" + strSupport + "\" title=\"" + strSupport + "\" />"
				+ "<span>" + strSupport + "</span></div>"
				+ "</video>");

			if (bStart) { //Click Button Start Bilder ausblenden -> Video läuft schon
				$holder.find(".rsBtnCenterer").fadeOut(mch.mchSlider.FadeTime);
				$holder.find(".rsMainSlideImage").fadeOut(mch.mchSlider.FadeTime);
				$holder.find(".rsContentBox").fadeOut(mch.mchSlider.FadeTime);

				var video = $holder.find("video"); //Video-Tag

				video[0].addEventListener("ended", function () {
					StartHtml5Video($sliderData, objKeyVisualRotator, video[0]);
				});
			}
			else { //Autostart -> Video einblenden und auf Position 0 stellen
				var iDelay = parseInt(jQuery(html4Video).attr("data-delayautoplay"));
				if (iDelay === "NaN" || iDelay < 0) { iDelay = 0; }
				setTimeout(function () {
					var video = $holder.find("video"); //Video-Tag

					if (video != null && video.length === 1) {
						StartVideo(objKeyVisualRotator, $sliderData, $holder, html4Video, video);
					}
				}, iDelay);
			}
		}

		function StartVideo(objKeyVisualRotator, $sliderData, $holder, html4Video, video) {
			try {
				if (video != null) {
					var buffer = video[0].buffered;
					if (buffer && buffer.length > 0 && buffer.end(0) > 0) {
						//console.log("start video buffer: " + buffer.end(0));
						$holder.find(".rsPreloader").remove();
						$holder.find(".rsMainSlideImage").fadeOut(mch.mchSlider.VideoDelayAutoplayFadeTime);
						$holder.find(".rsContentBox").fadeOut(mch.mchSlider.VideoDelayAutoplayFadeTime);
						if (video[0].currentTime > 0) { video[0].currentTime = 0; } //Achtung IE
						if (jQuery(html4Video).attr("data-muted") != "muted") {
							video.prop("muted", false); //mute
						}

						video.fadeIn(mch.mchSlider.VideoDelayAutoplayFadeTime);

						video[0].addEventListener("ended", function () {
							StartHtml5Video($sliderData, objKeyVisualRotator, video[0]);
						});
					}
					else {
						html4Video.after("<div class=\"rsPreloader\"></div>");
						//console.log("wait video buffer. Type:" + typeof buffer); console.log("wait video buffer. length:" + typeof buffer.length);
						setTimeout(StartVideo, 1000, objKeyVisualRotator, $sliderData, $holder, html4Video, video);
					}
				}
			}
			catch (exept) {
				console.log("Error Slider StartVideo():" + exept.message);
			}
		};

		function StartHtml5Video($sliderData, objKeyVisualRotator, video) {
			if (video && typeof video === "object") {
				if ($sliderData.numSlides === 1) {
					video.currentTime = 0;
					video.play();
				}
				else if ($sliderData.numSlides === $sliderData.currSlideId + 1) {
					$sliderData.goTo(0)
				}
				else {
					$sliderData.next();
				}
			}
		}

		function IsDeviceMobile(context) {
			return (context.Device === EDevice.XS || context.Device === EDevice.S) ? true : false;
		}

		function getCurrentDevice() {
			if (mch.currentDevice === "xs")
				return EDevice.XS;
			else if (mch.currentDevice === "s")
				return EDevice.S;
			else if (mch.currentDevice === "m")
				return EDevice.M;
			else
				return EDevice.L;
		}

		function changeVideoImgUrl(context, strVideoItemId, strVideoUrl) {
			if (strVideoItemId && strVideoUrl) {
				if (strVideoUrl.match(/(\/\/youtu\.be\/)|(\/\/www\.youtube\.com\/watch)/)) {
					var strVideoId = null;
					var strYoutubeUrl = strVideoUrl.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
					if (strYoutubeUrl[2] !== undefined) {
						var aryValue = strYoutubeUrl[2].split(/[^0-9a-z_]/i);
						strVideoId = aryValue[0];
					}
					else {
						strVideoId = strYoutubeUrl;
					}
					setVideoImg(strVideoItemId, strVideoUrl, "//i2.ytimg.com/vi/" + strVideoId + "/hqdefault.jpg");
				}
				else if (strVideoUrl.match(/.vimeo.com\/(\d+)($|\/)/)) {
					var aryValue = strVideoUrl.split('/');
					if (aryValue.length > 2) {
						setVimeoImgUrl(context, strVideoItemId, strVideoUrl, strVideoUrl.split('/')[aryValue.length - 1]);
					}
				} else if (strVideoUrl.match(/.vimeo.com\/channels\/\d+/)) {
					var aryValue = strVideoUrl.split('/');
					if (aryValue.length > 3) {
						setVimeoImgUrl(context, strVideoItemId, strVideoUrl, strVideoUrl.split('/')[aryValue.length - 1]);
					}
				} else if (strVideoUrl.match(/.vimeo.com\/channels\/staffpicks\/\d+/)) {
					var aryValue = strVideoUrl.split('/');
					if (aryValue.length > 4) {
						setVimeoImgUrl(context, strVideoItemId, strVideoUrl, strVideoUrl.split('/')[aryValue.length - 1]);
					}
				}
			}
		}

		function setVimeoImgUrl(context, strVideoItemId, strVideoUrl, strVideoId) {
			if (strVideoId) {
				var strUrl = "http://vimeo.com/api/v2/video/" + strVideoId + ".json?callback=?";
				jQuery.getJSON(strUrl, {
					format: "json"
				}, function (data) {
				})
					.success(function (data, status, xmlHttp) {
						setVideoImg(strVideoItemId, strVideoUrl, data[0].thumbnail_medium)
					})
					.error(function (xmlHttp, status, error) {
						if (context.DebugMode) {
							console.log("Error vimeo thumbnail: Status" + status + ",\n\nErrorText:\n\n " + xmlHttp.responseText);
						}
					})
					.complete(function (xmlHttp, status) {
						//alert(data[0].thumbnail_medium);
					});
			}
		}

		function setVideoImg(strVideoItemId, strVideoUrl, strImageUrl) {
			jQuery("." + strVideoItemId).find("img").attr("src", strImageUrl);
		}
		//#endregion Video und Helper

	})(mchSlider.prototype);

	mch.addWidget(new mchSlider())
})(jQuery);
/* end widget mchSlider*/

/* start widget responsiveTables*/

(function ($) {

	// object ctor
	function responsiveTables(el, config) {

		/* taken from zurb-foundation */
		this.switched = false;
	}

	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {
			this.updateTables();
		}

		// called by MCH on resize
		prototype.onResize = function () {
			this.updateTables();
		}

		prototype.updateTables = function () {
			if ((mch.currentDevice === "s" || mch.currentDevice === "m") && !this.switched) {
				this.switched = true;
				var context = this;
				$("table.responsive").each(function (i, element) {
					context.splitTable($(element));
				});
				return true;
			}
			else if (this.switched && !(mch.currentDevice === "s" || mch.currentDevice === "m")) {
				this.switched = false;
				var context = this;
				$("table.responsive").each(function (i, element) {
					context.unsplitTable($(element));
				});
			}
		}

		prototype.splitTable = function (original) {
			original.wrap("<div class='table-wrapper' />");

			var copy = original.clone();
			copy.find("td:not(:first-child), th:not(:first-child)").css("display", "none");
			copy.removeClass("responsive");

			original.closest(".table-wrapper").append(copy);
			copy.wrap("<div class='pinned' />");
			original.wrap("<div class='scrollable' />");

			this.setCellHeights(original, copy);
		}

		prototype.unsplitTable = function (original) {
			original.closest(".table-wrapper").find(".pinned").remove();
			original.unwrap();
			original.unwrap();
		}

		prototype.setCellHeights = function (original, copy) {
			var tr = original.find('tr');
			var tr_copy = copy.find('tr');
			var heights = [];

			tr.each(function (index) {
				var self = $(this);
				var tx = self.find('th, td');

				tx.each(function () {
					var height = $(this).outerHeight(true);
					heights[index] = heights[index] || 0;
					if (height > heights[index]) heights[index] = height;
				});

			});

			tr_copy.each(function (index) {
				$(this).height(heights[index]);
			});
		}

	})(responsiveTables.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new responsiveTables())

})(jQuery);

/* end widget responsiveTables*/

/* start widget collapsible*/
(function ($) {

	// object ctor
	function collapsible(el, config) {
	}

	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {
			$(document).on("click", ".expand", function () {
				$(this).nextAll(".expandablecontent").slideToggle();
				return false;
			});

			$(document).on("click", ".switch > a", function () {
				mch.util.log("click on switch");
				if ($(this).is(".open")) {
					mch.util.log("switch is .open => slideup all and removeclass open");
					$(this).parent().parent().find(".expandablecontent").slideUp();
				}
				else {
					mch.util.log("switch is NOT .open => slidedown all and addclass open");
					$(this).parent().parent().find(".expandablecontent").slideDown();
				}
				return false;
			});
		}

	})(collapsible.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new collapsible())

})(jQuery);
/* end widget collapsible*/

/* start widget mchAnythingSliderCollection */
(function (jQuery) {

	// object ctor
	function mchAnythingSliderCollection(el, config) {
		this.sliders = [];
	}

	// declare methods
	(function (prototype) {

		// called by MCH on dom load
		prototype.init = function () {
			this.initMchAnythingSliderHelper();
			// only init once
			this.inited = true;
		}

		prototype.addSlider = function (anythingSlider) {
			this.sliders.push(anythingSlider);
			// trigger init for late widgets
			if (this.inited)
				this.initMchAnythingSliderHelper();
		}

		prototype.initMchAnythingSliderHelper = function () {

			if (this.sliders.length == 0) {
				return;
			}

			if (typeof mchAnythingSliderHelper != 'object') {

				jQuery.getLocalScript('/Sites/javascripts/Common/mchAnythingSlider.js', function () {
					mch.mchAnythingSliderHelper.initAnythingSliders();
				});
			}
			else {
				mch.mchAnythingSliderHelper.initAnythingSliders();
			}
		}
	})(mchAnythingSliderCollection.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new mchAnythingSliderCollection())

})(jQuery);
/* end widget mchAnythingSliderCollection*/

/* start widget menu*/
(function ($) {

	// object ctor
	function menu(el, config) {
		this.isMobileIos = false;
		this.firstLevelMenuItems = null;
		this.menuItems = null;
		this.activeMenuItem = null;
		this.closeButton = null;
		this.activeMobileMenuItem = null;
		this.mobileMenuWasOpen = false;
		this.isMobileInitialized = false;
		this.currentDevice = "xl";
		this.oldDevice = "xl";
		this.mobileNavOffsetTop = 0;

		// dom node
		this.$el = $(el);

		// extend default config
		this.config = $.extend(true, {

			default: 'option'

		}, config);

	}

	// declare methods
	(function (prototype) {
		// called by MCH on dom load
		prototype.init = function () {
			var context = this;
			this.isMobileIos = this.isIos();
			//Get all firstlevel items.
			this.firstLevelMenuItems = $(".main-nav > ul > li");
			//Get all firstlevel items that haven't a fly_no_submenu class.
			this.menuItems = this.firstLevelMenuItems.not(".fly_no_submenu");

			this.menuItems.each(function () {
				var $menuItem = $(this);
				$menuItem.bind((context.isMobileIos) ? "touchstart" : "click", function (event) {
					//if another menu is expanded 
					if (context.activeMenuItem != null) {
						context.close();
					}
					//add the css class "open" to the clicked firstlevel item
					$menuItem.addClass("open");
					$(".close", this).unbind((context.isMobileIos) ? "touchstart" : "click");
					//unbind the document click event that was resgistered at the end of the function
					$(document).unbind((context.isMobileIos) ? "touchstart" : "click");
					//Check if the submenu is available
					if (context.hasSubmenu(this) == false) {
						//if not..., get it
						context.loadSubmenu(this);
						return false;
					};
					//show the menu
					context.activeMenuItem = $("ul", this).show();
					//close at fly_closenav click
					$(".close", this).bind((context.isMobileIos) ? "touchstart" : "click", function (event) {
						context.close();
						return false;
					});
					//close at document click
					$(document).one((context.isMobileIos) ? "touchstart" : "click", function (event) {
						if (event.button == 'undefined' || event.button != 2) {
							context.close();
							return false;
						}
					});
					//Exit at keycode 27
					$(document).keydown(function (e) {
						var code = (e.keyCode ? e.keyCode : e.which);
						if (code == 27) {
							context.close();
							event.stopPropagation();
						}
					});

					event.stopPropagation();
				});
			});

			// init mobile nav if needed
			this.currentDevice = mch.currentDevice;
		}

		//A ngn extension. Selects and highlights the "FirstLevel" navigation item.
		prototype.selectMenu = function (menuId) {
			var items = this.menuItems
			if (items) {
				menuId = "." + menuId;
				items.find(menuId).addBack(menuId).filter(function () {
					$(this).addClass("parent");
				})
			}
		}

		prototype.onBreakpoint = function () {
			var args = (1 <= arguments.length) ? Array.prototype.slice.call(arguments, 0) : [];
			if (args.length > 1) {
				this.oldDevice = this.currentDevice;
				this.currentDevice = args[1];
			}

			if (!this.isMobileInitialized && this.isMobileActive) {

				var context = this;
				//at first for locking because the multiple events
				this.isMobileInitialized = true;
				this.mobilenav = $(".main-nav-mobile");
				$("<ul>").appendTo(this.mobilenav.find(".nav-holder")).append(this.firstLevelMenuItems.clone());
				this.mobilenav.find("li:has(a.submn)").addClass("has-children");
				this.mobilenav.find(".menu-opener").on((this.isMobileIos) ? "touchstart" : "click", function () {
					context.mobilenav.find(".nav-holder").toggle();
					context.showChildrenOf(null);

					if (!context.mobileMenuWasOpen) {
						$("body").on("click touchstart", function (e) {
							if (!$(e.target).is(".main-nav-mobile *")) {
								context.mobilenav.find(".nav-holder").hide();
								context.showChildrenOf(null);
								context.mobileMenuWasOpen = false;
							}
						});
					}

					context.mobileMenuWasOpen = true;
				});

				this.mobilenav.find("> .back").on((this.isMobileIos) ? "touchstart" : "click", function () {
					mch.util.log("click on back");
					if (context.activeMobileMenuItem === null || context.activeMobileMenuItem.parent().closest("li").length === 0) {
						mch.util.log("context.showChildrenOf(null)");
						context.showChildrenOf(null);
					}
					else {
						mch.util.log("context.showChildrenOf(context.activeMobileMenuItem.parent().closest()");
						context.showChildrenOf(context.activeMobileMenuItem.parent().closest("li"));
					}
					return false;
				});

				var mobileSubItems = this.mobilenav.find(".nav-holder ul").find("> li").not(".fly_no_submenu");
				mobileSubItems.each(function () {
					var $menuItem = $(this);
					$menuItem.bind((context.isMobileIos) ? "touchstart" : "click", function (event) {
						if (context.hasPreloadedSubmenu(this) == false) {
							var submenu = context.prepareMobileSubMenu($(this).find("> ul"));


							submenu.find("a").bind((this.isMobileIos) ? "touchstart" : "click", function (event) {
								if ($(this).parent("li").is(".has-children")) {
									context.showChildrenOf($(this).parent("li"));
									return false;
								}
								event.stopPropagation();
							});

							context.showChildrenOf($(this));
							return false;
						}

						if (context.hasSubmenu(this) == false) {
							context.loadMobileSubMenu(this);
							return false;
						}
						context.showChildrenOf($menuItem);
						event.stopPropagation();
					});
				});
			}
		}

		prototype.onResize = function () {
			if (this.isMobileActive() && this.isMobileInitialized) {
				this.mobileNavOffsetTop = $("body header").outerHeight();
			}
		}

		prototype.isIos = function () {
			var iPhone = "iphone";
			var iPod = "ipod";
			var iPad = "ipad";
			var userAgent = navigator.userAgent.toLowerCase();
			var aIPhoneUserAgent = [iPhone, iPod, iPad];
			return $.inArray(userAgent, aIPhoneUserAgent) != -1 ? true : false;
			//return aIPhoneUserAgent.contains(userAgent);
		}

		prototype.close = function () {
			if (this.menuItems != null) {
				//Remove a "open" css class from a firstlevel item
				this.menuItems.filter(".open").removeClass("open");
				this.menuItems.find("ul").hide();
			}
		}

		prototype.hasSubmenu = function (firstLevelItem) {
			var $firstLevelItem = $(firstLevelItem);
			return $firstLevelItem.find("> ul").length == 0 ? false : true;
		}

		prototype.hasPreloadedSubmenu = function (menuItem) {
			return $(menuItem).find("> ul li.close").length == 1 ? false : true;
		}

		prototype.loadMobileSubMenu = function (firstLevelItem) {
			var context = this;
			var $firstLevelItem = $(firstLevelItem);
			var $source = $firstLevelItem.find("a.submn");
			if ($source.length != 0) {
				var href = $source.attr("href");
				$("#loaderMessage").ajaxStart(function () {
					var $loader = $(this);
					$firstLevelItem.append($loader);
					var left = ($firstLevelItem.offset().left + ($firstLevelItem.outerWidth(true) / 2) - ($loader.outerWidth(true) / 2)) + "px";
					var top = ($firstLevelItem.position().top + ($firstLevelItem.outerHeight(true) / 2) - ($loader.outerHeight(true) / 2)) + "px";
					$loader.css({
						position: 'absolute',
						zIndex: 5000,
						left: left,
						top: top
					}).show();
				});
				$("#loaderMessage").ajaxStop(function () {
					var $loader = $(this);
					$loader.hide();
				});
				$source.load(href, function () {
					var subMenu = $(this).find("> ul").clone();

					subMenu = context.prepareMobileSubMenu(subMenu);
					subMenu.find("a").bind((this.isMobileIos) ? "touchstart" : "click", function (event) {
						if ($(this).parent("li").is(".has-children")) {
							context.showChildrenOf($(this).parent("li"));
							return false;
						}
						event.stopPropagation();
					});

					$firstLevelItem.append(subMenu);
					$source.replaceWith(subMenu);
					context.showChildrenOf($firstLevelItem);
				});
			};
		}

		prototype.prepareMobileSubMenu = function (subMenu) {

			subMenu.find(".close").remove();
			subMenu.find("li:has(ul)").addClass("has-children");

			//https://jira.messe.ch/browse/DIDPP-100 Item zur Strukturierung der Hauptnavigation
			//if the first node of a .has-children's li...
			subMenu.find(".has-children:has(> .navigation-folder)").each(function () {
				var span = $(this).children(":first");
				//create an hyperlink
				var a = $("<a></a>");
				a.addClass("navigation-folder").attr("style", "cursor: pointer").text(span.text());
				//and replace the span with the hyperlink.
				span.replaceWith(a);
			});

			subMenu.find(".has-children:has(> a)").each(function () {
				$(this).children("ul").prepend($(this).clone().addClass("previous-level").removeClass("has-children"));
			});

			return subMenu;
		}

		prototype.loadSubmenu = function (firstLevelItem) {
			var $firstLevelItem = $(firstLevelItem);
			var $source = $firstLevelItem.find("a.submn");
			if ($source.length != 0) {
				var href = $source.attr("href");
				$("#loaderMessage").ajaxStart(function () {
					var $loader = $(this);
					var left = ($firstLevelItem.offset().left + ($firstLevelItem.outerWidth(true) / 2) - ($loader.outerWidth(true) / 2)) + "px";
					var top = ($firstLevelItem.offset().top + ($firstLevelItem.outerHeight(true) / 2) - ($loader.outerHeight(true) / 2)) + "px";
					$loader.css({
						position: 'absolute',
						zIndex: 5000,
						left: left,
						top: top
					}).show();
				});
				$("#loaderMessage").ajaxStop(function () {
					var $loader = $(this);
					$loader.hide();
				});
				$source.load(href, function () {
					var subMenu = $(this).find("> ul").detach().hide();
					//an extension for ngn. If the navigation should run in a remote environment. All possible navigation items should be found.
					//Through a href compare the current item will be detected and activated.
					subMenu.find(".external-link").filter(function () {
						var $link = $(this);
						$link.removeClass("fly_active");
						var loc = window.location.href;
						if (loc.indexOf($link.attr("href")) != -1) {
							$link.addClass("fly_active");
						}
					});

					$source.replaceWith(subMenu);
					$firstLevelItem.trigger((this.isMobileIos) ? "touchstart" : "click");
				});
			};
		}

		prototype.showChildrenOf = function (elem) {
			this.activeMobileMenuItem = elem;
			var buttonHeight = this.mobilenav.find(".menu-opener").outerHeight();
			if (elem !== null) { // otherwise we're on root
				//reset parent's height and overflow
				$(elem).parent("ul").css({ "height": "auto", "overflow-y": "", "overflow-x": "" });
				$(elem).siblings().children("ul").hide();
				//reset height and overflow
				$(elem).children("ul").show();

				this.mobilenav.find("> .back").hide();
				this.mobilenav.find(".nav-holder").css({ "left": "-" + (this.getLevel(elem) + 1) + "00%" });
				if ((this.getLevel(elem) + 1) > 0) {
					this.mobilenav.find("> .back").show();
				}
				var itemsHeight = $(elem).children("ul").outerHeight();
				var navigationTop = this.mobilenav.position().top - $(window).scrollTop();
				var windowHeight = $(window).height();
				if (((navigationTop + itemsHeight) > windowHeight)) {
					$(elem).children("ul").css({
						"height": windowHeight - (navigationTop + buttonHeight + 40) + "px",
						"overflow-y": "scroll",
						"overflow-x": "hidden"
					});
				}
				this.mobilenav.css("height", ($(elem).children("ul").outerHeight() + buttonHeight) + "px");
			}
			else {
				this.mobilenav.find("> .back").hide();
				this.mobilenav.find(".nav-holder").css("left", "0%");
				this.mobilenav.css("height", (this.mobilenav.find(".nav-holder").children("ul").height() + buttonHeight) + "px");
			}
		}

		/* only for mobile */
		prototype.getLevel = function (elem) {
			return ($(elem).parentsUntil(this.mobilenav, "ul").length - 1);
		}

		prototype.isMobileActive = function () {
			return (this.currentDevice == "s" || this.currentDevice == "m");
		}

	})(menu.prototype);

	// no need to wrap inside dom load event
	// since ctor does not access anything and
	// we always will only have one instance
	// wait for init event to setup everything
	mch.addWidget(new menu())

})(jQuery);

/* end widget menu*/


/* end widgets */
