var flashBufferSize = 4; // Sekunden
var diff = 132;
var player = null;
var height = 750;
var deviceAgent = navigator.userAgent.toLowerCase();
var isAppleMobileDevice = deviceAgent.match(/(iphone|ipod|ipad)/);
var isOpera = window.opera ? true : false;
var videos = [];
var headlines = [];
var cached = [];
var emergencyheadline = 'HOME';
var page = -1;
var bgTimeOut = -1;
var bgCacheTimeOut = -1;
var loadingCounters = [];
var tempData = '';
var flashPlayer = [];
var fplayerC = [];
var loaded = [];
loaded[1] = true;
var soundState = true; // true = on
var videoWithSoundIsRunning = false;
var dim = {
	w :0,
	h :0
};

// =========================

function piwikReport() {
	try {
		if (piwikTracker != null) {
			piwikTracker.trackPageView(document.title);
		}
	} catch (ex) {
		// ignore
	}
}

function piwikReportSoundState(state) {
	try {
		if (piwikTracker != null) {
			piwikTracker.setCustomUrl(location.href
					+ "/michalsky/sound'+state+'.html");
			piwikTracker.trackPageView('User turned sound ' + state);
		}
	} catch (ex) {
		// ignore
	}
}

function piwikSetUrl(anchor) {
	try {
		if (piwikTracker != null) {
			piwikTracker.setCustomUrl(anchor.href);
		}
	} catch (ex) {
		// ignore
	}
}

function fakeClick(fn) {
	var $a = $('<a href="#" id="fakeClick">0</a>');
	$a.bind("click", function(e) {
		e.preventDefault();
		fn();
	});

	$("body").append($a);

	var evt, el = $("#fakeClick").get(0);

	if (document.createEvent) {
		evt = document.createEvent("MouseEvents");
		if (evt.initMouseEvent) {
			evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
					false, false, false, false, 0, null);
			el.dispatchEvent(evt);
		}
	}

	$(el).remove();
}

function setBackground(el) {
	$('.col_background').html(el.html());
	var c = $('.col_background .css_cont');
	$('.col_background img').each( function(k, v) {
		if (v.getAttribute('src').match("blank.gif$") == "blank.gif") {
			v.setAttribute('alt', '0');
			getImageUrl(v);
		}
	})
	var clazz = c.removeClass('css_cont').attr('class');
	$('.col_background').attr('class',
			'col_background mod_article block innerfade ' + clazz);
}

function getDimension(el) {
	var dim = {
		w :0,
		h :0,
		getWidth : function() {
			return this.w;
		},
		getHeight : function() {
			return this.h;
		},
		setWidth : function(v) {
			this.w = v;
		},
		setHeight : function(v) {
			this.h = v;
		}
	}
	var tmp = $(el);
	var width = 0;
	var height = 0;

	if (window.opera) {
		try {
			width = tmp.innerWidth()
					- (parseInt(tmp.css('padding-right')) || 0)
					- (parseInt(tmp.css('padding-left')) || 0);
			height = tmp.innerHeight()
					- (parseInt(tmp.css('padding-bottom')) || 0)
					- (parseInt(tmp.css('padding-top')) || 0);
		} catch (e) {
			width = tmp.width();
			height = tmp.height();
		}

	} else {
		width = tmp.width();
		height = tmp.height();
	}

	dim.setHeight(height);
	dim.setWidth(width);
	return dim;
}

function nonMenuLink(id, anchor) {
	if ($('.preload_' + id).length == 0) {
		var href = 'xml.php?action=page&tmpl=page&id=' + id;
		$.get(href, function(data) {
			if (data) {
				cacheData($(data));
			}
			anchor.rel = id;
			$(anchor).click(menuclick);
		}, 'xml');
	} else {
		anchor.rel = id;
		$(anchor).click(menuclick);
	}
}

function checkForInternalLinks(container) {
	var anchors = container.find('a[href$=.html]:not([href|="http"])');
	anchors.each( function(k, v) {
		var res = $(v).attr('href').match('(index.php/)*(.*)(\\.html).*');
		if (res != null && res.length >= 2) {
			nonMenuLink(res[res.length - 2], v);
		}
	})

}

function setContent(el) {
	$('.col_main').html('');
	$('.col_main').html(el.html());
	if (el.hasClass('form')) {
		initFormHook($('.col_main form'));
	} else if (el.hasClass('products')) {
		initProdHover();
	}
	$('.col_main').attr('class',
			'col_main mod_article block ' + el.attr('class'));
	checkForInternalLinks($('.col_main'));
}

function initFormHook(form) {
	var id = form.attr('id');
	form.find("input[type='submit']").click(
			function(ev) {
				ev.preventDefault();
				$.post($("#" + id).attr('action'), $("#" + id).serialize(),
						function(data) {
							$("#" + id).html($(data).find("#" + id).html());
							initFormHook($("#" + id));
						});
			})

}

function setEyeCatcher(el) {
	$('.col_eyecatcher').html(el.html());
}

function setSubMenu(id) {
	// return;
	var submenu = $('a[rel="' + id + '"]').parents('.submenu').children(
			'ul.level_2');
	if (submenu.length == 0) {
		var str = $('.preload_' + id).attr('class');
		var arr = str.split(' ');
		for (i = 0; i < arr.length && submenu.length == 0; i++) {
			var m = arr[i].match('preload_([^ ]+)');
			if (m.length == 2) {
				submenu = $('a[rel="' + m[1] + '"]').parents('.submenu')
						.children('ul.level_2');
			}
		}
	}
	$('#submenu')
			.html(
					'<div class="mod_navigation block"><ul id="ajax_smenu"></ul></div>');
	if (submenu.length > 0) {
		submenu.children().each( function(a, b) {
			var res = $(b).clone(true).appendTo('#ajax_smenu');
			res.rel = b.rel;
		})
	}
}

function resizeBGTO(w) {
	resizeBG(w);
	bgCacheTimeOut = setTimeout( function() {
		resizeCache(w)
	}, 4000);
}

function resizeBG(w) {
	$('#supersize img').each( function(k, v) {
		getImageUrl(v);
	});
}

function resizeCache(w) {

	$('#data_cache .background img').each( function(k, v) {
		getImageUrl(v);
	});
}

function showData(id) {
	try {
		readyLoaded(false, 1);
	} catch (ex) {
		// ignore
	}
	$('#video').html('');
	$('.innerfade').show();
	$('#controls').addClass('noVid');
	var container = $('.preload_' + id);
	if (container.length > 0) {
		setBackground(container.children('.background'));
		setContent(container.children('.content'));
		setEyeCatcher(container.children('.eyecatcher'));
		setSubMenu(id);
		if (typeof headlines[id] == 'undefined') {
			$(document)
					.attr('title', emergencyheadline + ' - Michalsky Parfum');
		} else {
			$(document).attr('title', headlines[id] + ' - Michalsky Parfum');
		}

		piwikReport();
		if (videos[id]) {
			$('#video').show();

			if (videos[id].hasAudio) {
				// Audioplayer stummschalten
				muteAudio();
				// Dem Sound-Icon die Stummklasse wegnehmen.
				// $('#sound').removeClass('off');
				videoWithSoundIsRunning = true;
				soundState = true;
			} else {
				videoWithSoundIsRunning = false;
				if (!$('#sound').hasClass('off'))
					unMuteAudio();
			}
			includeVideo(videos[id].video, videos[id].image);
		} else {
			videoWithSoundIsRunning = false;
			if (!$('#sound').hasClass('off'))
				unMuteAudio();
		}
		if ($('.col_background .thin_img').length > 0) {
			$('#supersize').fillViewPort.options.startheight = 419;
			diff = 332;
		} else {
			diff = 132;
			$('#supersize').fillViewPort.options.startheight = 750;
		}
		startFader();
		onResize();
		setTimeout( function() {
			animate($('[rel=' + id + ']'));
		}, 200);
		setTimeout( function() {
			animate($('[rel=' + id + ']'));
		}, 1000);
	}
}

function contactForm(data, id) {
	var tmpl = '<div class="content form">';
	tmpl += data.find('*[type="form"]').text();
	tmpl += '</div>';
	$(tmpl).appendTo('.preload_' + id);
}

function products(data, id) {
	headlines[id] = data.find('products headline').text();
	var tmpl = '<div class="content products"><div class="productCarousel ce_productlist block">'
			+ '<h1>' + headlines[id] + '</h1>' + '<ul class="prodtitle">';
	var tmpl2 = '<ul class="prodimages">';
	var off = 0;
	data
			.find('products > item')
			.each(
					function(k, v) {
						var val = $(v);
						tmpl += '<li id="title_'
								+ val.find('id').text()
								+ '" class="title" style="display: list-item;"><span class="text">'
								+ val.find('title *').text() + '</span></li>';
						tmpl += '<li id="desc_'
								+ val.find('id').text()
								+ '" class="invis desc" style="display: none;"><span class="text">'
								+ val.find('description *').text()
								+ '</span></li>';
						tmpl2 += '<li style="width: '
								+ val.find('width').text() + 'px; left: '
								+ (off) + 'px;" id="PRODUCT_'
								+ val.find('id').text() + '">';
						tmpl2 += '<img style="width: '
								+ val.find('width').text() + 'px; left: '
								+ (off) + 'px;" alt="'
								+ val.find('title *').text() + '" src="'
								+ val.find('img').text() + '">';
						tmpl2 += '<img id="big_' + val.find('id').text()
								+ '" class="invis bigimage" src="'
								+ val.find('enclosure item').text() + '"> '
						tmpl2 += '</li>';
						off = off + parseInt(val.find('width').text()) + 10;
					})
	tmpl += '</ul>' + tmpl2 + '</ul></div>'
	$(tmpl).appendTo('.preload_' + id);

}

function handleMain(data, id) {
	if (data.find('products').length > 0) {
		products(data, id);
	} else if (data.find('*[type="form"]').length > 0) {
		contactForm(data, id);
	} else {
		var cssclass = data.find('css').text();
		var headline = data.find('*[type="headline"]');

		value = headline.find('value');
		if (value.text().length) {
			headlines[id] = value.text();
		}
		var tmpl = '<div class="content ' + cssclass
				+ '"><h1 class="ce_headline">' + value.text() + '</h1>';
		var texte = data.find('*[type="text"]');
		texte
				.each( function(k, v) {
					tmpl += '<div class="ce_text block">' + $(v).find('text')
							.text() + '</div>';
				});
		$(tmpl + '</div>').appendTo('.preload_' + id);
	}
}

function handleEyeCatcher(data, id) {

	var src = data.find('singlesrc').text();

	var cssclass = data.find('image cssid item').text();
	cssclass += data.find('css').text();
	var tmpl = '<div class="eyecatcher">';
	if (src.length > 0) {
		tmpl += '<img class="' + cssclass + '" src="' + src + '"/>';
	}
	tmpl += '</div>';
	$(tmpl).appendTo('.preload_' + id);
}

function handleBackground(data, id) {
	var src = data.find('[type="image"] singlesrc');
	var tmpl = '<div class="background">';
	var css = data.find('css').text();
	tmpl += '<div style="display:none" class="css_cont ' + css + '"></div>';
	src.each( function(k, v) {
		var imageSrc = $(v).text();
		if (imageSrc.indexOf('/tl_files') > 0) {
			parts = imageSrc.split('/tl_files');
			imageSrc = '';
			for (i = 1; i < parts.length; i++) {
				imageSrc = imageSrc + '/tl_files' + parts[i];
			}
		}
		tmpl += '<a><img src="blank.gif" class="' + css + '" rel="' + imageSrc
				+ '"></a>';
	});
	$(tmpl + '</div>').appendTo('.preload_' + id);
	var w = 1200;
	var dim = getDimension(window);
	if (css == 'thin_img') {
		w = dim.getWidth();
	} else {
		w = dim.getWidth() * (dim.getHeight() - diff) / 419;
	}

	$('.preload_' + id + ' .background img').each( function(k, v) {
		getImageUrl(v, true);
	});
	var vids = data.find('[type="videofilm"]');
	vids.each( function(k, v) {
		var video = {};
		video.video = $(v).find('videosrc').text();
		video.image = $(v).find('imagesrc').text();
		video.hasAudio = $(v).find('hasaudio').text() == 'true';
		videos[id] = video;
	})
}

function cacheData(data) {
	try {
		var datacache = $('#data_cache');
		if (datacache.length == 0) {
			$('<div id="data_cache" style="display:none;"></div>').appendTo(
					'body');
			datacache = $('#data_cache');
		}
		var dataid = data.attr('id');
		if (typeof dataid == 'undefined') {
			data = data.find('page');
			dataid = data.attr('id');
		}
		var pl = $('.preload_' + dataid);
		if (pl.length == 0) {
			$('<div class="preload_' + dataid + '"></div>').appendTo(datacache);
			handleMain(data.find('#main'), dataid);
			handleEyeCatcher(data.find('#eyecatcher'), dataid);
			handleBackground(data.find('#background'), dataid);
			pl = $('.preload_' + dataid);
			cached[dataid] = true;
		}
		var af = data.attr('askedfor');
		if (typeof af != 'undefined') {
			af = af.split(',');
			for (i = 0; i < af.length; i++) {
				if (!pl.hasClass('preload_' + af[i])) {
					pl.addClass('preload_' + af[i]);
					cached[af[i]] = true;
				}
			}
		}
		if (!pl.hasClass('preload_' + dataid)) {
			pl.addClass('preload_' + dataid);
			cached[dataid] = true;
		}
	} catch (ex) {
		console.log(ex);
	}
}

function cacheMultiData(data) {
	$(data).find('pages > page').each( function(k, v) {
		cacheData($(v));
	});
}

function leadingSpaces(val, num) {
	var v = '' + val;
	while (v.length < num) {
		v = ' ' + v;
	}
	return v;
}

function incReadyCounter() {
	if (isAppleMobileDevice)
		return;
	loadingCounters[0]++;
	updateView();
}
function incStartCounter() {
	if (isAppleMobileDevice)
		return;
	loadingCounters[1]++;
	updateView();
}

function updateView() {
	if (isAppleMobileDevice)
		return;
	if (loadingCounters[1] > 0) {
		val = loadingCounters[0] / loadingCounters[1] * 100;
		if (val >= 100) {
			clearTimeout(loadingCounters[2]);
			loadingCounters[2] = setTimeout(loaderReady, 1500);
		}
	}
}

function updateView_old() {
	var val = 0;
	if (loadingCounters[1] > 0) {
		val = loadingCounters[0] / loadingCounters[1] * 100;
		if (flashPlayer && flashPlayer.length > 0) {
			val = val / (fplayerC.length + 1);
			for (fpl = 0; fpl < flashPlayer.length; fpl++) {
				val = val + (flashPlayer[fpl] / fplayerC.length + 1);
			}
		}
		val = Math.ceil(val);
		if (val >= 100) {
			clearTimeout(loadingCounters[2]);
			loadingCounters[2] = setTimeout(loaderReady, 1500);
		}
	}

	if (val > 100)
		val = 100;
	val = leadingSpaces(val, 3);
	// console.log(new Date(),val);
	for (i = 0; i < val.length; i++) {
		if (val.charAt(i) == ' ') {
			$('.z' + i).css('visibility', 'hidden');
		} else {
			var pos = (parseInt(val.charAt(i)) + 1) * -36;
			$('.z' + i).css( {
				'visibility' :'visible',
				'background-position' :'-5px ' + pos + 'px'
			});
		}

	}
}
function loaderReady() {
	if (isAppleMobileDevice)
		return;

	$('body').trigger('loaderReady');
}

function initLoader() {
	if (isAppleMobileDevice)
		return;
	if ($('#loader').length == 0) {
		var str = '';
		// '<div id="loader" style="display:none;"><div class="z0"></div><div
		// class="z1"></div><div class="z2"></div></div>';

		// str += "<style>#loader { left: 50%; top:25%; margin-left: -33px;
		// background-color: black; position: relative; width: 66px; height:
		// 28px;
		// background-position: 66px 0px; background-repeat: no-repeat;}#loader
		// .z0,#loader .z1,#loader .z2 {float: left;width: 22px;height:
		// 28px;background-image:
		// url('tl_files/michalsky/style/counter.gif');visibility: hidden;
		// }#loader
		// .z2 {visibility:visible;background-position: -5px -36px;}</style>"
		str = '<img id="loader" style="display:none;left:50%;top:25%;margin-left:-24px;position:relative;" src="tl_files/michalsky/video/loading.gif"/>';
		$('#overlay').append(str);
	}
	var loader = $('#loader');
	if (loader.css('display') == 'none') {
		loadingCounters[0] = 0;
		loadingCounters[1] = 0;
		loadingCounters[2] = -1;
		updateView();
		loader.show();
	}
	$('body').bind('loaderReady', function(e) {
		readyLoaded(e, 2);
	});
}

function getImageUrl(image, loader) {
	if (loader === true) {

	}
	var url = image.getAttribute('rel');
	if (!url) {
		image.setAttribute('rel', image.getAttribute('src'));
	}
	var h = 750;
	var pridiff = 122;
	if ($(image).hasClass('thin_img')
			|| $(image).parent().parent().hasClass('thin_img')) {
		h = 419;
		pridiff = 332
	}
	if (!$('#supersize').hasClass('init')) {
		$('#supersize').resizenow();
	}
	var res = calcSuperSize(getDimension('#supersize'), h / 1200, pridiff)
	if (image.getAttribute('alt') != res.w2) {
		image.alt = res.w2;
		url = image.getAttribute('rel');
		var request = $(image).data('request');
		if (request) {
			request.abort();
		}
		var loc = 'image.php?image=' + url + '&w=' + res.w2 + '&return=json';
		request = $.get(loc, function(data) {
			if (data && !data.error && image.src != data.image) {
				$(image).load( function() {
					$(image).unbind();
					if (loader === true) {
						incReadyCounter();
					}
					setTimeout( function() {
						if (!isAppleMobileDevice && !isOpera) {
							var d1 = getDimension(image);
							var d2 = getDimension('#supersize');
							if (d1.getWidth() >= d2.getWidth()) {
								$(image).removeClass('maxImg');
							}
						}
					}, 1000)
				}).error( function() {
					$(image).unbind();
					if (loader === true) {
						incReadyCounter();
					}
				});
				if (loader === true) {
					incStartCounter();
				}

				image.src = data.image;
			}
		}, 'json');
		$(image).data('request', request);
	}
}

function getData(id, show) {
	var href = $('#PAGE_' + id)[0].href;
	$.get(href + '&tmpl=page', function(data) {
		cacheData($(data).find('page'));
		if (show) {
			showData(id);
		}
	}, 'xml');
}

function getMultiData(query) {
	$.get(query, function(data) {
		cacheMultiData($(data));
	}, 'xml');
}

function changeContent(tgt) {
	var id = tgt.rel;
	if (!$('.preload_' + id).length > 0 || !cached[id]) {
		getData(id, true);
	} else {
		showData(id);
	}
	$('.active, .trail').removeClass('trail').removeClass('active');
	var par = $('[rel="' + id + '"]').parents('li');
	if (par.length > 0) {
		par.addClass('active');
	}
	var ajax_menu = $('#ajax_smenu');
	if (ajax_menu.children('.active').length == 0) {
		var children = ajax_menu.children();
		if (children.length > 0) {
			$(children[0]).addClass('active');
		}
	}
	ajax_menu = $('#menu ul li.active ul');
	if (ajax_menu.children('.active').length == 0) {
		var children = ajax_menu.children();
		if (children.length > 0) {
			$(children[0]).addClass('active');
		}
	}

}

function resized(data) {
	// console.log('resized');
	var wd = getDimension(window);
	// console.log(data,tempData, dim.w,wd.getWidth(),dim.h,wd.getHeight(), data
	// != tempData && dim.w != wd.getWidth());
	if (data != tempData && dim.w != wd.getWidth()) {
		if (!isAppleMobileDevice) {

			clearTimeout(bgTimeOut);
			clearTimeout(bgCacheTimeOut);
			var sup = $('#supersize img');
			if (!sup.hasClass('maximg'))
				sup.addClass('maxImg');
			bgTimeOut = setTimeout( function() {
				resizeBGTO(data)
			}, 1000);
		}
	}
	tempData = data;
	dim.w = wd.getWidth();
	dim.h = wd.getHeight();
}

function orientationChange() {
	onResize();
}

function muteAudio() {
	if (isAppleMobileDevice) {
		return;
	}
	var snd = $('#sound');
	var player = document.getElementById('flashaudio');
	if (player != null && player.sendEvent) {
		player.sendEvent("MUTE", 'true');
	}
}

function unMuteAudio() {
	if (isAppleMobileDevice) {
		return;
	}
	var snd = $('#sound');
	var player = document.getElementById('flashaudio');
	if (player != null && player.sendEvent) {
		// player.sendEvent("MUTE",(soundState&&!videoWithSoundIsRunning)?'false':'true');
		player.sendEvent("MUTE", (soundState) ? 'false' : 'true');
	}
}

function handleControls(result, className) {
	var controls = $('#controls');
	if (result) {
		controls.removeClass(className);
		$('.innerfade').hide();
	} else {
		if (!controls.hasClass(className)) {
			controls.addClass('noVid');
		}
		$('.innerfade').show();
	}
}

function includeVideo(file, img) {
	/*
	 * var videoWidth = getDimension('#video').getWidth(); if (videoWidth % 16 >
	 * 0) { videoWidth = videoWidth - (videoWidth % 16) + 16; } var viewHeight =
	 * getDimension('#video').getHeight(); var aspect = 1200.0 / 614.0; var
	 * videoHeight = Math.floor(videoWidth / aspect); videoHeight = videoHeight +
	 * (videoHeight % 2); if (videoHeight < viewHeight) { videoHeight =
	 * viewHeight + (viewHeight % 2); videoWidth = Math.floor(videoHeight *
	 * aspect); if (videoWidth % 16 > 0) { videoWidth = videoWidth - (videoWidth %
	 * 16) + 16; } videoHeight = Math.floor(videoWidth / aspect); videoHeight =
	 * videoHeight + (videoHeight % 2); }
	 * 
	 * var width = videoWidth; var height = videoHeight;
	 * 
	 * if (width < 1024) { width = 1024; } if (width > 1920) { width = 1920; }
	 */
	var width = 1024;

	/*
	 * var basepath = file.substring(0, file.lastIndexOf("/")) + "/rendered/";
	 * var basename = file.substring(file.lastIndexOf("/") + 1,
	 * file.lastIndexOf(".")); var suffix = ".flv"; file = basepath + basename +
	 * '_' + width + suffix;
	 */
	if (!isAppleMobileDevice) {
		;
		$('#overlay').css('opacity', '0.99999');
		$('#overlay').css('background-color', 'black');
		$('#loader').show();
	}
	var result = includeJWPlayer('video', "100%", "100%", file, img);
	var controls = $('#controls');
	if (!result && !controls.hasClass('noVid')) {
		controls.addClass('noVid');
	}

	if (result) {
		$('.innerfade').hide();
	}
	return result;
}

function includeAudio(file) {
	var result = includeJWPlayer('audio', '1', '1', file);
	var controls = $('#controls');
	if (!result && !controls.hasClass('noAud')) {
		controls.addClass('noAud');
	}
	return result;
}

function readyLoaded(e, id) {
	if (isAppleMobileDevice)
		return;
	loaded[id] = true;
	if (e && e.data) {
		if (e.data.id == 'flashvideo' && id == 1) {
			var controls = $('#controls');
			className = 'noVid';
			controls.removeClass(className);
		} else if (e.data.id == 'flashaudio' && id == 1) {
			var controls = $('#controls');
			className = 'noAud';
			controls.removeClass(className);
		}
	}
	if (loaded[1] && loaded[2]) {
		if (e && e.data && e.data.id) {
			var player = document.getElementById(e.data.id);
			if (player != null) {
				player.sendEvent('PLAY', 'true');
			}
		} else {
			var player = document.getElementById('flashvideo');
			if (player != null) {
				player.sendEvent('PLAY', 'true');
			}
			var player2 = document.getElementById('flashaudio');
			if (player2 != null) {
				player2.sendEvent('PLAY', 'true');
			}

		}
		$('#supersize img').each( function(k, v) {
			if (v.getAttribute('src').match("blank.gif$") == "blank.gif") {
				v.setAttribute('alt', '0');
				getImageUrl(v);
			}
		});
		$('#loader').hide();
		$('#overlay').css('background-color', 'transparent');

	}

}

function flashReset() {
	if (isAppleMobileDevice)
		return;
	if (!$('#controls').hasClass('noVid')) {
		$('#controls').addClass('noVid');
	}
	loaded[1] = false;
	flashPlayer = [];
	fplayerC = [];
}

function includeJWPlayer(id, w, h, file, img) {
	$('body').bind('flashReady', {
		'id' :'flash' + id
	}, function(e) {
		readyLoaded(e, 1);
	});

	var timestamp = new Date().getTime();
	var so = new SWFObject('plugins/jwplayer/player.swf?' + timestamp,
			'flash' + id, w, h, '9');
	so.addParam('allowfullscreen', 'false');
	so.addParam('allowscriptaccess', 'always');
	so.addParam('wmode', 'opaque');
	so.addVariable('bufferlength', flashBufferSize);
	so.addVariable('autostart', 'true');
	so.addVariable('icons', 'false');
	so.addVariable('playerready', 'playerReadyCallback');
	so.addVariable('repeat', 'always');
	so.addVariable('volume', '25');
	so.addVariable('stretching', 'fill');
	so.addVariable('smoothing', 'false');
	so.addVariable('mute', 'true');
	so.addVariable('controlbar', 'none');
	so.addVariable('file', file);
	if (img) {
		so.addVariable('image', img);
	}
	var result = so.write(id);
	if (result) {
		loaded[1] = false;
	}
	return result;
}

function checkForScrollBars() {
	var wnd = getDimension(window);
	var body = getDimension('body');

	// Aktivate overflow if window smaller than body
	if (wnd.getWidth() < body.getWidth() || wnd.getHeight() < body.getHeight()) {
		$('html').css('overflow', 'auto');
	} else {
		$('html').css('overflow', 'visible');
	}
}

function onResize() {
	if (!$('#supersize img').hasClass('maxImg')) {
		$('#supersize img').addClass('maxImg');
	}

	var bdy = $('body, html');
	var wnd = getDimension(window);
	
	checkForScrollBars();
	
	// bdy.css('width', wnd.getWidth() + 'px');
	// bdy.css('height', (wnd.getHeight()) + 'px');
	$('#supersize').resizenow();
}

function startFader() {

	$('#supersize div').innerfade( {
		speed :1800,
		timeout :8000,
		children :'a'
	});
}

( function($) {

	// Resize image on ready or resize
	$.fn.fillViewPort = function() {
		$.inAnimation = false;
		$.paused = false;
		var options = $.extend($.fn.fillViewPort.defaults,
				$.fn.fillViewPort.options);

		$.fn.fillViewPort.defaults = {
			startwidth :4,
			startheight :3,
			vertical_center :1,
			slideshow :1,
			slide_interval :5000
		};

		$(window).bind("resize", function() {
			onResize();
		});

		// Adjust image size
		$.fn.resizenow = function() {
			var options = $.extend($.fn.fillViewPort.defaults,
					$.fn.fillViewPort.options);
			return this.each( function() {

				// Define image ratio
					var ratio = options.startheight / options.startwidth;
					var contDimension = getDimension(this);
					result = calcSuperSize(contDimension, ratio, diff);

					var sup = $(this);

					sup.css('height', result.h1);
					sup.css('width', result.w1);
					sup.children().css('height', result.h2);
					sup.children().css('width', result.w2);

					options.callback(result.w1);

					var all = sup.children();

					var center = sup.children(':not(.bgbottom, .bgtop)');
					var bottom = sup.children('.bgbottom');
					var top = sup.children('.bgtop');

					contDimension = getDimension(this);

					all.css('left', (result.w3 - contDimension.getWidth()) / 2);
					center.css('top',
							(result.h3 - contDimension.getHeight()) / 2);
					bottom.css('top', (result.h3 - contDimension.getHeight()));
					top.css('top', 0);
					if (!sup.hasClass('init')) {
						sup.addClass('init');
					}

					return false;
				});
		};

		$(document).ready( function() {
			startFader();
			$('#supersize').resizenow();
		});

	}
})(jQuery);

// so.write('video');

function buffer(param) {
	flashPlayer[param.id] = Math.ceil(param.percentage);
	var temp = 0;
	var count = fplayerC.length;
	for (i = 0; i < count; i++) {
		if (param.id == 'flashvideo') {
			temp = temp + flashPlayer[fplayerC[i]] * 10;
		} else {
			temp = temp + flashPlayer[fplayerC[i]];
		}
	}

	if (temp >= 99 * count && (!loaded[1])) {
		$('body').trigger('flashReady');
		var player = document.getElementById(param.id);
		if (player != null) {
			player.removeModelListener("BUFFER", 'buffer');
		}
	}
}

function playerReadyCallback(obj) {
	fplayerC[fplayerC.length] = obj.id;
	flashPlayer[obj.id] = 0;
	var player = document.getElementById(obj.id);
	if (player != null) {
		player.sendEvent("PLAY", 'false');
		player.addModelListener("BUFFER", 'buffer');

	}

	if (obj.id == 'flashvideo') {
		if (player != null) {
			player.sendEvent("MUTE", ($('#sound').hasClass('off') ? 'true'
					: 'false'));
		}
	}

	var mute = ($('#sound').hasClass('off') || $('#sound').hasClass('auto_off')) ? 'true'
			: 'false';
	if (obj.id == 'flashaudio') {
		if (player != null) {
			player.sendEvent("MUTE", mute);
		}
	}
}

function registerOnLoad() {
	$(window)
			.load(
					function() {
						$('#supersize a').show();
						if (!isAppleMobileDevice) {
							var querystring = 'xml.php?tmpl=multipage&action=multipage';
							$(
									'#menu .mod_navigation a:not(.link_redirect, .hide, .invisible)')
									.each(
											function(key, value) {
												if (value.rel) {
													querystring += '&id[]=' + value.rel;
												} else {
												}
											})
							// Fake loading to prevent caching
							// getMultiData(querystring);
							incStartCounter();
							incReadyCounter();
							// End Fake Loading
						} else {
							$('#supersize').resizenow();
						}
					})
}

function makeSmall() {
	var dim = getDimension('#page');
	$('#page').css( {
		'height' :(dim.getHeight() - 1) + 'px',
		'margin-bottom' :'0px'
	})
	$('.anim').animate( {
		'margin-top' :'-362px',
		'height' :'362px'
	}, 500, 'swing', function() {
		if ($('.anim').hasClass('big')) {
			$('.anim').removeClass('big').addClass('small');
		}

		$('#page').css( {
			'height' :'100%',
			'margin-bottom' :'0px'
		})
	})

}

function makeBig() {
	var dim = getDimension('#page');
	$('#page').css( {
		'height' :(dim.getHeight() - 1) + 'px',
		'margin-bottom' :'0px'
	})

	$('.anim').animate( {
		'margin-top' :'-561px',
		'height' :'561px'
	}, 500, 'linear', function() {
		if ($('.anim').hasClass('small')) {
			$('.anim').removeClass('small').addClass('big');
		}
		$('#page').css( {
			'height' :'100%',
			'margin-bottom' :'0px'
		})
	})

}

function animate(el) {
	if (el.hasClass('toSmall')) {
		makeSmall(1);

	} else if (el.hasClass('toBig')) {

		makeBig(1);

	}

}

function afterAnim() {
	$('.anim .bottom').addClass('big2');
}

function animate2(el) {
	if (el.hasClass('toSmall')) {
		$('.anim').switchClass('big', 'small');

	} else if (el.hasClass('toBig')) {
		$('.anim').switchClass('small', 'big');

	}

}

function registerMenu() {
	if (!isAppleMobileDevice) {
		$('li.submenu').mouseover( function(ev) {
			var tgt = ev.target;
			if (tgt.tagName != 'LI') {
				tgt = $(tgt).parent('li')[0];
			}
			var ul = $(tgt).children('ul');
			if (!$(tgt).hasClass('mo')) {
				$(tgt).addClass('mo');
			}
		})
		$('li.submenu').mouseout( function(ev) {
			var tgt = ev.target;
			if (tgt.tagName != 'LI') {
				tgt = $(tgt).parent('li')[0];
			}
			$(tgt).removeClass('mo');
		})
		$(
				'#menu .mod_navigation a:not(.link_redirect), #controls .kontakt, #controls .contact, #submenu a:not(.link_redirect)')
				.click(menuclick);
	}
}

function menuclick(event) {
	if (isAppleMobileDevice)
		return true;
	// $('#submenu *').hide();
	// flashReset();
	event.preventDefault();
	var tgt = event.target;

	if (tgt.tagName != 'A') {
		tgt = $(tgt).parent('a')[0];
	}
	if (tgt.rel && tgt.rel != page) {
		piwikSetUrl(tgt);
		$('body').trigger('flashReady');
		flashReset();
		$('#flashvideo').hide();

		page = tgt.rel;
		$('.bigimage').hide();
		$('.desc').hide();
		$('.title').show();
		$('.title').removeClass('strong');

		emergencyheadline = tgt.title;
		if (!emergencyheadline) {
			emergencyheadline = 'HOME';
		}
		emergencyheadline = emergencyheadline.toUpperCase();
		changeContent(tgt);
		animate($(tgt));
	}
	// return false;
}

function registerControls() {
	$('#sound')
			.click(
					function() {
						if (!$('#sound').hasClass('auto_off')) {
							var tog = $('#sound').toggleClass('off').hasClass(
									'off') ? 'true' : 'false';
							vplayer = document.getElementById('flashvideo');
							if (vplayer != null && vplayer.sendEvent) {
								vplayer.sendEvent("MUTE", tog);
							}
							if (!videoWithSoundIsRunning) {
								aplayer = document.getElementById('flashaudio');
								if (aplayer != null && aplayer.sendEvent) {
									aplayer.sendEvent("MUTE", tog);
								}
							}
							piwikReportSoundState(tog == 'true' ? 'off' : 'on');
							if ($('#htmlaudio').length > 0) {
								var htmlplayer = $('#htmlaudio').get(0);
								if (tog == 'true') {
									htmlplayer.pause()
								} else {
									htmlplayer.play()
								}
							}
							soundState = tog != 'true';
						}
					});

	$('#pause').click( function() {
		var play = $('#pause').hasClass('play');
		if (play) {
			if ($('#video').is(':hidden')) {
				changeContent($('[rel=' + page + ']')[0]);
			}
		} else {
			player = document.getElementById('flashvideo');
			if (player != null) {
				player.sendEvent("STOP");
			}
			$('#video').hide();
			$('.innerfade').show();
		}
		$('#pause').toggleClass('play');
	});
}

function calcSuperSize(contDimension, ratio, privDiff) {

	var wnd = getDimension('body');
	var browserwidth = wnd.getWidth();
	var browserheight = wnd.getHeight() - privDiff;
	
	result = {
		h3 :browserheight,
		w3 :browserwidth
	};

	if ((browserheight / browserwidth) > ratio) {
		var rW = Math.ceil(browserheight / ratio);
		result.h1 = browserheight;
		result.w1 = rW;
		result.h2 = browserheight;
		result.w2 = rW;
	} else {
		var rW = Math.ceil(browserwidth * ratio);
		result.h1 = rW;
		result.w1 = browserwidth;
		result.h2 = rW;
		result.w2 = browserwidth;
	}
	return result;
}

function initProdHover() {

	$('.bigimage').appendTo('body');
	$('.bigimage').mouseout( function() {
		$('.bigimage').hide();
		$('.desc').hide();
		$('.title').show();
		$('.title').removeClass('strong');
	});
	$('.bigimage').css('position', 'absolute');
	$('.prodimages li')
			.mouseover(
					function(ev) {
						var target = ev.currentTarget;
						var id = target.id.substr(8);
						var target = $(target);
						var off = target.offset();

						$('.prodtitle li').removeClass('strong');
						$('.desc').hide();
						$('.title').hide();
						$('#desc_' + id).show();
						$('#title_' + id).addClass('strong');
						$('#title_' + id).show();
						$('.bigimage').hide();
						var pdiff = (getDimension('#big_' + id).getWidth() / 2 - getDimension(
								target).getWidth() / 2);
						$('#big_' + id).css('left', off.left - pdiff);
						$('#big_' + id).css('bottom', 0);
						$('#big_' + id).show();
					});
}

// =================
$(document).ready(
		function() {
			
			checkForScrollBars();

			if (!isAppleMobileDevice) {
				var act = $('#menu .active a:visible');
				if (act.length > 0) {
					page = $('#menu .active a:visible').get(0).rel;
				} else {
					page = 0;
				}
				$('#overlay').css('background-color', 'black');
				initLoader();
			} else {
				var audio = $('<audio></audio>', {
					id :'htmlaudio',
					autoPlay :'autoPlay',
					loop :'loop'
				});
				addSource(audio, 'tl_files/michalsky/audio/loop.mp3');
				audio.appendTo('#controls');
				function addSource(elem, path) {
					$('<source></source>').attr('src', path).appendTo(elem);
				}
				var au = $("#htmlaudio").get(0);

				fakeClick( function() {
					au.play();
				});

			}
			$('#video').height(getDimension(window).getHeight() - (diff));
			$(window).resize( function() {
				$('#video').height(getDimension(window).getHeight() - (diff));
			})
			$('#supersize a').hide();
			var sup = $('#supersize');
			if (isOpera || isAppleMobileDevice)
				if (!sup.hasClass('maximg'))
					sup.addClass('maxImg');
			registerOnLoad();
			registerMenu();
			includeAudio('tl_files/michalsky/audio/loop.mp3');
			registerControls();
			initProdHover();
			$('.en #controls #en').click( function(e) {
				e.preventDefault();
			});
			$('.de #controls #de').click( function(e) {
				e.preventDefault();
			});

			$('.produktbild_gross').addClass('fresh');

			$('.produktbild').mouseover(
					function() {
						$('.produktbild').hide();
						if ($('.produktbild_gross').hasClass('fresh')) {
							$('.produktbild_gross').appendTo(
									$('.produktbild_gross').parent().parent());
							$('.produktbild_gross').removeClass('fresh');
						}
						$('.produktbild_gross').show();
					})

			$('.produktbild_gross').mouseout( function() {
				$('.produktbild').show();
				$('.produktbild_gross').hide();
			})

			if ($('.thin_img').length > 0) {
				height = 419;
				diff = 332;
			}

			$.fn.fillViewPort.options = {
				startwidth :1200,
				startheight :height,
				vertical_center :1,
				slideshow :1,
				navigation :0,
				transition :1, // 0-None, 1-Fade, 2-slide top, 3-slide right,
				// 4-slide bottom, 5-slide left
				pause_hover :0,
				slide_counter :0,
				slide_captions :0,
				slide_interval :6000,
				callback : function(data) {
					if (typeof resized == 'function')
						resized(data);
				}
			};

			if ($('#supersize').children('div').children('a').length <= 1) {
				$.fn.fillViewPort.options.slideshow = 0;
			}
			$('#supersize').fillViewPort();

			if ($('.col_main').length == 0) {
				$('<div class="col_main mod_article block"></div>').appendTo(
						'.content');

			}

		})
