var 
	music = true,
	musicfocus = true,
	isPlaying = false,
	audio = null,
	reinitializePage = null,
	loadPageAjax = null,
	unbindPageEvents = null,
	commonEventHandlers = null,
	rootUrl = '',
	loaded = false,
	History = window.History,
	State = null,
	$this = null,
	booklearned = false,
	DOMcursor360 = null,
	currentMagazin = '/motorblog/2012/01/',
	apng_supported = false,
	cur_360_active = false;

function OpenMagazinUrl(url) {
	var magazin_window = null;
	if(url == '/motorblog' || url == '/motorblog/')
		url = currentMagazin;
	magazin_window = window.open(url, 'magazin', '');
	magazin_window.moveTo(0,0);
	magazin_window.focus();
}

function OpenMagazin(pageno, month, year){
	var baseUrl = currentMagazin,
		page = 'cover',
		popupMagazin = '',
		magazin_window = null;
	if (typeof(pageno) !== 'undefined'){
		page = 'page' + pageno;
	}
	if (typeof(month) !== 'undefined' && typeof(year) !== 'undefined'){
		baseUrl = '/motorblog/'+ year +'/' + month + '/';
	}
	OpenMagazinUrl(baseUrl + page);
}

function cursor360 (e) {
	if ($('#rotator-container').length){
		if ($.contains($('#rotator-container')[0], e.target)){
			DOMcursor360.css('left', e.clientX).css('top', e.clientY - 20).show();
		}else{
			DOMcursor360.hide();
		}
	}
}

function cursor360activate(){
	DOMcursor360.sprite({fps: 54, no_of_frames: 28, height: 16, width: 54,
	    on_last_frame: function(obj) {
        obj.spStop(); // stop the animation on the last frame
        setTimeout("DOMcursor360.spStart()", 1000);
    }});
	cur_360_active = true;
}

//BIKE Selection Script
function bikeSelection(options) {
	var currentTooltip = null,
		tooltipTop = [-25, -25, -22, -15, -13],
		moveToTimer = null,
		prev_target = null,
		speed = 0,
		i = 0,
		pos = 0,
		hq = new Array(),
		selection_content = $("#selection-content"),

		stopMoving = function () {
			if (moveToTimer) {
				window.clearInterval(moveToTimer);
			}
			moveToTimer = null;
		},
		moveTo = function ($this, frame, hqimage, max_speed, factor) {
			if (frame < 0) {
				frame = 0;
			}
			if (frame >= options.frames) {
				frame = options.frames - 1;
			}
			var settings = $this.data('spritespin').settings,
				moveToStep = function () {
					var d = frame - pos,
						max_speed1 = max_speed + (Math.abs(d) / 50);
					speed = speed + d * factor;
					if (Math.abs(d) < (5 / factor)) {
						speed /= (1 + factor * 6);
					}
					pos += speed;
					var new_frame = Math.round(pos);
					if (speed > max_speed1) {
						speed = max_speed1;
					}
					if (speed < -max_speed1) {
						speed = -max_speed1;
					}
					if ((speed > 0 && new_frame >= frame) || (speed <= 0 && new_frame <= frame)) {
						speed = 0;
						new_frame = pos = frame;
						stopMoving();
						$this.append(hqimage);
					} else {
						$this.find('img.hq').remove();
					}
					if (new_frame !== settings.frame) {
						$this.spritespin("update", new_frame);
					}
				};
			if (prev_target !== frame) {
				stopMoving();
				pos = settings.frame;
				prev_target = frame;
			}
			if (!moveToTimer) {
				moveToStep();
				moveToTimer = window.setInterval(moveToStep, 25);
			}
		},
		posToBike = function (pos) {
			var positions = options.pos;
			for (i = positions.length - 1; i >= 0; i--) {
				if (pos > positions[i]) {
					return i;
				}
			}
			return 0;
		},
		bikeToFrame = function (bike) {
			return options.bframes[bike];
		},
		frameToBike = function (frame) {
			for (i = 0; i < options.bframes.length; i++) {
				if (frame >= options.bframes[i]-1) {
					return i;
				}
			}
			return options.bframes.length-1;
		},
		showTooltip = function (bike) {
			if (isNaN(currentTooltip) || currentTooltip === null) {
				$(options.tooltip).removeClass().addClass('bike' + bike.toString()).children('span.text').text(options.titles[bike]).end().animate({top : tooltipTop[bike], 'opacity': 1}, 'fast', 'easeOutCirc');
				currentTooltip = bike;
			} else if (currentTooltip !== bike) {
				$(options.tooltip)
					.stop()
					.animate({top : tooltipTop[currentTooltip] - 20, 'opacity': 0}, 'fast', 'easeOutCirc', function () {
						$(this).removeClass().addClass('bike' + bike.toString()).children('span.text').text(options.titles[bike])
							.end().animate({top : tooltipTop[bike], 'opacity': 1}, 'fast', 'easeOutCirc');
					});
				currentTooltip = bike;
			}
		},
		hideTooltip = function() {
			$(options.tooltip).stop().animate({top : tooltipTop[currentTooltip] - 20, 'opacity': 0}, 'fast', 'easeOutCirc');
			currentTooltip = null;
		};

	selection_content
		.removeData('spritespin')
		.spritespin({
			animate		: false,
			behavior	: "none",
			width		: options.width,
			height		: options.height,
			frames		: options.frames,
			framesX		: options.framesX,
			image		: options.image,
			onLoad		: options.onLoad,
			frameTime	: 60
		})
		.bind("mousemove", function (e) {
			var x = e.pageX - $(this).offset().left,
				p = posToBike(x),
				frame = bikeToFrame(p);
			moveTo($(this), frame, hq[p], 4, 1 / 10);
			showTooltip(p);
			return true;
		})
		.bind("click", function (e) {
			var x = e.pageX - $(this).offset().left,
				p = posToBike(x);
			History.pushState(null, null, options.pages[p]);
			return false;
		}).bind("mouseout", function (e) {
			if (!speed) {
				return;
			}
			hideTooltip();
		});
	var keyhandler = function (e) {
		var keycode = e.keyCode || e.which;
		var bike = frameToBike(selection_content.data('spritespin').settings.frame);
		switch(keycode) {
		case 37:	// links
			bike = Math.max(bike-1, 0);
			moveTo(selection_content, bikeToFrame(bike), hq[bike], 4, 1 / 10);
			showTooltip(bike);
			return false;
		case 39:	// rechts
			bike = Math.min(bike+1, options.nbikes-1);
			moveTo(selection_content, bikeToFrame(bike), hq[bike], 4, 1 / 10);
			showTooltip(bike);
			return false;
		case 13:	// Enter
		case 38:	// rauf
			History.pushState(null, null, options.pages[bike]);
			return false;
		}
	};
	$(window).bind("keydown", keyhandler);

//   $("#selection-top, #selection-bottom").bind("mousemove", function (e) {
//     selection_content.trigger(e);
//   });

	$(options.tooltip).css('opacity', 0);
	for (i = 0; i < options.hq.length; i += 1) {
		hq[i] = $('<img class="hq" />').attr('src', options.hq[i]);
	}
	$("#selection-content, #selection-top, #selection-bottom").width(options.width + "px").css("background-color", options.color);
	selection_content.spritespin("update", bikeToFrame(2));
	moveTo(selection_content, bikeToFrame(2), hq[2], 4, 1 / 10);
}

//Bike Rotation
function bikeAnimation(options) {
	var rotateTimer = null,
		rotateStep = 0,
		stopEasing = function () {
			if (rotateTimer) {
				window.clearInterval(rotateTimer);
			}
			rotateTimer = null;
			rotateStep = 1;
		},
		hideHqImage = function ($this) {
			if ($.browser.msie) {
				return;
			}
			$this.find('img.hq').remove();
		},
		pad = function (number, length) {
			var str = number.toString();
			while (str.length < length) {
				str = '0' + str;
			}
			return str;
		},
		showHqImage = function ($this, frame) {
			if ($.browser.msie) {
				return;
			}
			hideHqImage($this);
			var s = options.hq;
			s = s.replace('%03d', pad(frame, 3));
			$this.append($('<img class="hq" />').attr('src', s));
		},
		easeOut = function ($this, d, q, delay) {
			var settings = $this.data('spritespin').settings,
				prev_frame = settings.frame,
				max_steps = Math.abs(1500 / (70 * q)),
				rotateEasing = function (v) {
					var t = 0;
					if (v <= delay) {
						t = v;
					} else {
						t = delay;
					}
					t *= 0.1;
					return Math.sqrt(v / 2 * q) * (2 + Math.abs(d / 2000.0) + t) * (d < 0 ? -1 : 1);
				},
				easeStep = function () {
					var new_frame = Math.round(prev_frame + rotateEasing(rotateStep));
					$this.spritespin("update", new_frame);
					new_frame = settings.frame;
					if (rotateStep > max_steps) {
						stopEasing();
						showHqImage($this, new_frame);
						return;
					} else {
						hideHqImage($this);
					}
					rotateStep += 1;
				};
			stopEasing();
			rotateTimer = window.setInterval(easeStep, 25);
		},
		old_pos = null,
		last_move,
		loaded = false,
		clicked = false,
		bike_content = $("#bike-content");
		bike_content.removeData('spritespin');
	bike_content.spritespin({
		animate   : false,
		width     : options.width,
		height    : options.height,
		frames    : options.frames,
		framesX   : options.framesX,
		frame     : options.startFrame,
		image     : options.image,
		onLoad	  : options.onLoad,
		behavior  : "drag",
		frameTime : 60
	}).bind("onLoad", function () {
		loaded = true;
		$this = $(this);
		window.setTimeout(function () {
			var max = 4, count = max;
			var timer = window.setInterval(function() {
				if(!--count)	window.clearInterval(timer);
				easeOut($this, 12000 - (max-count)*1000, 0.4, 2);
			}, 100);
		}, 800);
	}).bind("dblclick", function (e) {
		spritespin.unbind("dblclick.spritespin");	/* Spritespin bindet manchmal seine Event-Handler neu */
		return false;
	}).bind("mousedown", function (e) {
		if (!loaded) {
			return;
		}
		clicked = true;
		stopEasing();
		old_pos = e.clientX;
		return true;
	}).bind("mousemove", function (e) {
		cursor360(e);
		if (!loaded) {
			return;
		}
		if (old_pos) {
			stopEasing();
		}
		last_move = (new Date()).getTime();
		if (clicked) {
			hideHqImage($(this));
		}
		return true;
	}).bind("mouseup", function (e) {
		if (!loaded) {
			return;
		}
		clicked = false;

		var d = e.clientX - old_pos;
		old_pos = null;
		if(Math.abs(d) < 2) {
			if(e.clientX - $(this).offset()['left'] < options.width/2)
				easeOut($(this), -3000, 0.7, 2);
			else
				easeOut($(this), 3000, 0.7, 2);
			return true;
		}

		showHqImage($(this), $(this).data('spritespin').settings.frame);
		if ((new Date()).getTime() - last_move > 50) {
			return true;
		}

		if (d >  200) {
			d =  200;
		}
		if (d < -200) {
			d = -200;
		}
		d *= 10;
		easeOut($(this), d, 1.8, 0);
		return true;
	}).bind("mousewheel", function (e, delta) {
		if (!loaded) {
			return;
		}
		easeOut($(this), delta < 0 ? -3000 : 3000, 0.7, 2);
		return true;
	}).bind("mouseout", function (e) {
		if (!loaded) {
			return;
		}
		clicked = false;
		e.stopImmediatePropagation();
		return true;
	});
	var keyhandler = function (e) {
		var keycode = e.keyCode || e.which;
		if(!loaded)	return;
		switch(keycode) {
		case 37:	// links
			easeOut(bike_content, -3000, 0.7, 2);
			return false;
		case 39:	// rechts
			easeOut(bike_content, 3000, 0.7, 2);
			return false;
		case 40:	// runter
			History.pushState(null, "URBAN MOTOR - Showroom", '/showroom/');
			cursor360(e);
			return false;
		}
	};
	$(window).bind("keydown", keyhandler);

	$("#bike-top, #bike-bottom").bind("mousewheel", function (e, delta) {
		if (!loaded) {
			return;
		}
		bike_content.trigger(e, delta);
	});
	$("#bike").bind("mousedown mousemove mouseup", function (e) {
		if (!loaded) {
			return;
		}
		bike_content.trigger(e);
	});

	$("#bike-content, #bike-top, #bike-bottom").width(options.width + "px").css("background-color", options.color);
	$("#bike-top").height(options.top + "px");
	$("#bike-bottom").height(options.bottom + "px");
	showHqImage(bike_content, bike_content.data('spritespin').settings.frame);
}

function bike_common(width, height, frames, framesX, image, hq, startFrame) {
	if (cur_360_active) {
		DOMcursor360.spStart();
	}
	$('#bike-content, #content-bottom').css('opacity', 0).show();
	$('#loader').css('opacity', 0).show().fadeTo(500, 1);
	loaded = false;
	bikeAnimation({
		color   : "#000",
		top     : 0,
		bottom  : 0,
		width   : width,
		height  : height,
		frames  : frames,
		framesX : framesX,
		image   : image,
		hq      : hq,
		startFrame : startFrame,
		onLoad: function () {
			$('#loader').stop().fadeTo(1000, 0, function () {
				$('#bike-content, #content-bottom').fadeTo(1000, 1, function () {
					$('#loader').hide();
				});
			});
		}
	});
}

function bike_earl_grey() {
	bike_common(943, 530, 167, 13, "/resources/img/videos/earl_grey.jpg", "/resources/img/videos/earl_grey-%03d.jpg", 25);
}

function bike_guzzi() {
	bike_common(943, 510, 166, 13, "/resources/img/videos/guzzi.jpg", "/resources/img/videos/guzzi-%03d.jpg", 15);
}

function bike_wr() {
	bike_common(943, 530, 166, 13, "/resources/img/videos/wr.jpg", "/resources/img/videos/wr-%03d.jpg", 17);
}

function bike_mcqueen() {
	bike_common(943, 560, 167, 13, "/resources/img/videos/mcqueen.jpg", "/resources/img/videos/mcqueen-%03d.jpg", 30);
}

function bike_black_pearl() {
	bike_common(943, 530, 164, 13, "/resources/img/videos/black_pearl.jpg", "/resources/img/videos/black_pearl-%03d.jpg", 28);
}


function resizeWindow() {
	//horizonte Scrollbar nur anzeigen wenn Viewport kleiner als 960px
	if ($(window).width() >= 960) {
		$('body').css('overflow-x', 'hidden');
		$('footer').width('100%').children('#footer-wrapper-container').css('margin', '0 auto');
	} else {
		$('body').css('overflow-x', 'scroll');
		$('footer').width($(document).width()).children('#footer-wrapper-container').css('margin', '0');
	}

	if ($('#content-wrapper').hasClass("vertical")) {
		var calcedHeight = $('body').outerHeight() - ($('footer').height()),
			minHeight = parseInt($('#content-wrapper').css('min-height'), 10) - $('header').height();
		if (minHeight < calcedHeight) {
			$('#content-wrapper').css('height', $('body').outerHeight() - ($('footer').height() + $('header').height()));
		} else {
			$('#content-wrapper').css({
				'height'	:	minHeight
			});
		}
	}

	//Footer unter den content-wrapper schieben
    if (($('#content-wrapper').outerHeight()) >= $('body').outerHeight()) {
        $('footer').css("top", $('#content-wrapper').outerHeight());
    } else {
        $('footer').css("top", "inherit");
    }
}

function home() {
    var arrowAnimation = false,
	arrowAnimationActive = false;
    $('#company-teaser-container')
		.hover(
			function () {
				$('#company-teaser-container-over').stop().fadeTo('normal', 1);
				$(this).children('p').stop().animate({ color: "#ffffff" });
			},
			function () {
				$('#company-teaser-container-over').stop().fadeTo('normal', 0);
				$(this).children('p').stop().animate({ color: "#737373" });
			}
	    )
		.click(function () {
			History.pushState(null, "URBAN MOTOR - Company", '/company/');
			return false;
		});
    $('#motorblog-teaser-container')
		.hover(
            function () {
                $('#motorblog-teaser-container-over').stop().fadeTo('normal', 1);
                $(this).children('p').stop().animate({ color: "#ffffff" });
            },
            function () {
                $('#motorblog-teaser-container-over').stop().fadeTo('normal', 0);
                $(this).children('p').stop().animate({ color: "#737373" });
            }
        )
        .click(function () {
        	OpenMagazin();
			return false;
		});

	$("#main-showroom-teaser")
		.hover(
			function () {
				$(this).children('p').stop().animate({ color: "#ffffff" });
				$('#main-showroom-teaser-over').stop().fadeTo('slow', 1);
					if ($('#pfeil-animated').hasClass('isSprite')){
						$('#pfeil-animated').spStart();
						arrowAnimationActive = true;
					}else{
						try {
						delete $._spritely.instances['pfeil-animated'];
						}catch (e) {}
						$('#pfeil-animated').sprite({fps: 24, no_of_frames: 24, height: 80, width: 533, bgdirection : 'vertical',
							on_last_frame: function(obj) {
					        $(obj).spStop();
							arrowAnimationActive = false;
						},
						on_first_frame: function(obj) {
							$('#pfeil-animated').addClass('isSprite');
							arrowAnimationActive = true;
						}
						});
					}
			},
			function () {
				$(this).children('p').stop().animate({ color: "#737373" });
				$('#main-showroom-teaser-over').stop().fadeTo('slow', 0);
			}
		)
        .click(function () {
			History.pushState(null, "URBAN MOTOR - Showroom", '/showroom/');
			return false;
        });
}

function shop() {
        initShop();

    }
function showroom() {
	$('#selection, #content-header').css('opacity', 0).show();
	$('#loader').css('opacity', 0).show().fadeTo(500, 1);
    bikeSelection({
		nbikes  : 5,
		color   : "transparent",
		width   : 1200,
		height  : 410,
		frames  : 56,
		framesX : 8,
		bframes : [56, 42, 28, 14, 0],
		image   : "/resources/img/videos/auswahl.jpg",
		pos     : [260, 330, 530, 750, 900],
		hq      : ["/resources/img/videos/auswahl-000.jpg", "/resources/img/videos/auswahl-014.jpg", "/resources/img/videos/auswahl-028.jpg", "/resources/img/videos/auswahl-042.jpg", "/resources/img/videos/auswahl-056.jpg"],
		pages   : ["/showroom/wr", "/showroom/mcqueen", "/showroom/black-pearl", "/showroom/earl-grey", "/showroom/guzzi"],
		titles  : ["Werkstattrenner", "McQueen", "Black Pearl", "Earl Grey", "Scoro"],
		tooltip : "#krad-title-tooltip",
		onLoad	: function () {
			$('#loader').stop().fadeTo(1000, 0, function () {
				$('#loader').hide();
				$('#selection, #content-header').fadeTo(2000, 1);
			});
		}
    });
}

//Musicplayer

function playMusic() {
	if (typeof(audio[0].currentTime) == 'number') {
		try {
		audio[0].currentTime = $.cookie('audiotime');
		} catch (err) {}
		audio[0].play();
	}
}

function pauseMusic() {
	if (audio.length) {
		$.cookie('audiotime', audio[0].currentTime);
		audio[0].pause();
	}
}

function muteMusic() {
	if (audio.length) {
		$('#muteButton').addClass('inactive');
		$.cookie('audiomute', '1');
		if (audio.length) {
			audio[0].pause();
		}
	}
}
function unMuteMusic() {
	if (audio.length) {
		$('#muteButton').removeClass('inactive');
		$.cookie('audiomute', '0');
		playMusic();
	}
}

function initMusic() {
	audio = $('<audio />', {
		'loop'		: 'loop',
		'autoplay'	: 'autoplay'
	});
  try {
  	if (!(audio[0].canPlayType('audio/mpeg') || audio[0].canPlayType('audio/ogg'))){
  		$('#muteButton').addClass('inactive');
  		return;
  	}
  }
  catch(err) {
  		$('#muteButton').addClass('inactive');
  		return;
  		}
  {
  //Handle errors here
  }
	if (audio[0].canPlayType('audio/mpeg')){
		$('<source />', {
			'src'	: '/resources/audio/urbanmotor.mp3',
			'type'	: 'audio/mpeg'
		}).appendTo(audio);
	}
	if (audio[0].canPlayType('audio/ogg')){
		$('<source />', {
			'src'	: '/resources/audio/urbanmotor.ogg',
			'type'	: 'audio/ogg'
		}).appendTo(audio);
	}
	audio.appendTo('body');
	audio.one("canplay", function () {
		audio[0].currentTime = $.cookie('audiotime'), 10;
		if ($.cookie('audiomute') == '1') {
			muteMusic();
		}else{
			unMuteMusic();
		}
	});

	audio.bind('play', function () {
		audio.unbind("timeupdate").bind("timeupdate", function () {
			if (audio[0].currentTime !== 0) {
				$.cookie('audiotime', audio[0].currentTime);
			}
		});
	});

	audio.bind('ended', function () {
		audio[0].currentTime = 0;
		audio[0].play();
	});
	$('#muteButton').bind('click', function () {
		if ($.cookie('audiomute') == '0'){
			muteMusic();
		}else{
			unMuteMusic();
		}
	});
	if (musicfocus) {
		$(document).bind('focusin, focus', function () {
			if ($.cookie('audiomute') == 1) {
				muteMusic();
			}else{
				unMuteMusic();
			}
		});
	}
}


function enableFlipPage(){
	$.data(document.getElementById('flipPage'), 'count', 1);
	$('#flipPage').sprite({fps: 51, no_of_frames: 51, speed:500, height: 56, width: 90
		,
		 on_first_frame: function(obj) {
		if ($("#left-side").filter(':visible').length != 0 || booklearned == true)
			obj.spStop(); // stop the animation on the first frame
       	}, 
	    on_last_frame: function(obj) {
	        if ($("#left-side").filter(':visible').length != 0) {
		        obj.spStop(); // stop the animation on the last frame
	        }else{
	        	if ($.data(document.getElementById('flipPage'), 'count') == 3){
		       		$.data(document.getElementById('flipPage'), 'count', 0);
			        obj.spStop(); // stop the animation on the last frame
	        		setTimeout("$('#flipPage').spStart()", 3000);
	        	}
	        	$.data(document.getElementById('flipPage'), 'count', $.data(document.getElementById('flipPage'), 'count') + 1);
	        }
    } });

}

function normalizeURL(url, current) {
	if ((url[0] !== '/') && (url.indexOf('://') === -1)) {
		/* relative URL zu absoluter URL umwandeln (ohne Hostnamen) */
		current = current.match(/https?:\/\/[^\/]+(\/.*)/)[1];
		current = current.split('/');
		current.pop();
		current = current.join('/');
		result = (current + '/' + url).split('/');
		url = new Array();
		var i;
		for (i = 0; i < result.length; i += 1) {
			if (result[i] === '' || result[i] === '.') {
				/* nix */
			} else if (result[i] === '..') {
				url.pop();
			} else {
				url.push(result[i]);
			}
		}
		url = '/' + url.join('/');
	}
	return url;
}

$(document).ready(function () {
	if(location.hash) {
		/* wenn wir von außen über eine Hash-URL aufgerufen werden, zur richtigen Seite weiterleiten */
		var hash = location.hash;
		if(hash[0] == '#')	hash = hash.substr(1);
		location.href = normalizeURL(hash, location.protocol+'//'+location.host+location.pathname);
		return;
	}

	window.onresize = resizeWindow;
	var $body = $(document.body),
		selector = '#content-wrapper',
		rscript = null,
		rootUrl = History.getRootUrl();
		
		    var s = window.location.search.substring(1).split('&');

    if(!s.length) return;

    window.$_GET = {};

    for(var i  = 0; i < s.length; i++) {

        var parts = s[i].split('=');

        window.$_GET[unescape(parts[0])] = unescape(parts[1]);

    }
	function __loadPageAjax(url) {
		if ($('#flipPage').length){
			$('#flipPage').destroy('flipPage');
		}
		$('#loader').fadeTo(500, 0);
		if (cur_360_active) {
			DOMcursor360.spStop();
		}
		$.ajax({
			url: url,
			type: 'GET',
			dataType: "html",
			// Success callback (responseText is used internally)
			success: function (responseText, status,  jqXHR) {
				$(selector).stop().fadeTo(300, 0, function () {
					$('footer').css('position', 'absolute');
					rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
					// Store the response as specified by the jqXHR object
					responseText = jqXHR.responseText;
					// If successful, inject the HTML into all the matched elements
					if (jqXHR.isResolved()) {
						// #4825: Get the actual response in case
						// a dataFilter is present in ajaxSettings
						jqXHR.done(function (r) {
							responseText = r;
						});
						var response = $("<div>").append(responseText.replace(rscript, ""));
						/* Wenn man hier detach() aufruft, ist der Teilbaum nicht mehr mit dem document
						   assoziiert, für das vorher document.createElement('section') aufgerufen worden ist.
						   Deswegen werden dann im IE<9 die sections nicht erkannt. */
						$(selector)./*detach().*/empty().html(
								response
								// Locate the specified elements
								.find(selector).html()
							).css('opacity', 0).appendTo('#main-wrapper');
						document.title = response.find('#ajaxTitle').val();
						if (response.find(selector).hasClass('vertical')) {
							$(selector).addClass('vertical');
						} else {
							$(selector).removeClass('vertical').css('height', 'auto');
						}
						$('body').removeClass().addClass(response.find('#bodyclass').val());
						$('#top-navigation a').removeClass('active');
						$('#' + response.find('#navbutton').val()).addClass('active');
						resizeWindow();
						__reinitializePage(response.find('#ajaxscript').val());
						$(selector  + ' a').click(function () {
							History.pushState(null, null, $(this).attr('href'));
						    return false;
						});
					}

					/* wenn es Bilder zu laden gibt, warten */
					var images = $(selector).find('img');
					var first_time = true;
					var ready = function() {
						if(!first_time)	return;
						first_time = false;
						$(selector).fadeTo(1000, 1);
					};
					if(images.length) {
						images.load(ready);
						var all_complete = true;
						images.each(function() {
							if(!this.complete) all_complete = false;
						});
						if(all_complete) $(this).trigger('load');
					} else
						ready();
				});
			}
		});
	}
	

	function __reinitializePage(ajaxScript) {
		__unbindPageEvents();
		closed();
		if ($(".custom-select").length) {
			$(".custom-select").selectbox({effect: "fade"});
		}
		if ($('.custom-checkbox input').length){
			$('.custom-checkbox input').customInput();
		}
		if (History.enabled) {
			$(window).bind('statechange', function () {
				// Prepare Variables
				var
					State = History.getState(),
					url = State.url;
				loadPageAjax(url);
			});
			$('a:internal').click(function (event) {
				if($(this).attr('target') == '_blank') {
					return true;
				}
				if (typeof ($(this).attr('href')) !== 'undefined') {
					if ($(this).attr('href').substring(0, 1) === '#') {
						return true;
					}
					if ($(this).attr('href').substring(0, 7) === 'mailto:') {
						return true;
					}
					if ($(this).attr('href').substring(0, 10) === '/motorblog') {
						OpenMagazinUrl($(this).attr('href'));
						return false;
					}
					
				} else {
					return true;
				}
				State = History.getState();
				History.pushState(null, State.title, $(this).attr('href'));
				event.preventDefault();
				return false;
			});
		}
		__commonEventHandlers();

		/* Intervalle löschen */
		if (typeof(moveToTimer) != 'undefined') {
			window.clearInterval(moveToTimer);
		}
		if (typeof(rotateTimer) != 'undefined') {
			window.clearInterval(rotateTimer);
		}
		if (typeof(renderInterval) != 'undefined') {
			window.clearInterval(renderInterval);
		}
		
		ajaxScript = (typeof (ajaxScript) === 'undefined') ? $('#ajaxscript').val() : ajaxScript;
		switch (ajaxScript) {
		case "home()":
			home();
			break;
		case "shop()":
			shop();
			break;
		case "bike_earl_grey()":
			bike_earl_grey();
			break;
		case "bike_guzzi()":
			bike_guzzi();
			break;
		case "bike_mcqueen()":
			bike_mcqueen();
			break;
		case "bike_wr()":
			bike_wr();
			break;
		case "bike_black_pearl()":
			bike_black_pearl();
			break;
		case "showroom()":
			showroom();
			break;
		case "pageflip()":
			pageflip();
			setTimeout(enableFlipPage, 1000);
			break;
		}
	}

	function __commonEventHandlers() {
		$('.newsletter', 'footer').fancybox({
			padding         : 0,
			margin		: 0,
			href		: '#newsletter_layer',
			overlayColor	: '#000000',
			onStart		: function() {
				$('#newsletter_name, #newsletter_email').val('').setDefaultValue();
				$('#newsletter_layer').removeClass('newsletter_success');
				$('#newsletter_form').show();
				$('#newsletter_success').hide();
			}
		}).attr('href', '#');
		$('.kontakt', 'footer').fancybox({
			padding         : 0,
			margin		: 0,
			href		: '#contact_layer',
			overlayColor	: '#000000'
		}).attr('href', '#');
		
		$('.impressum', 'footer').fancybox({
			padding         : 0,
			margin		: 0,
			href		: '#impressum_layer',
			overlayColor	: '#000000'
		}).attr('href', '#');
		
		$('#impressum_layer_slider').slider({
			orientation: 'vertical',
			value: 0,
			min:	- ($('.content',"#impressum_layer_content").height() - $("#impressum_layer_content").height()),
			max: 0,
		    animate: false,
		    change: handleSliderChange,
		    slide: handleSliderSlide
		});
		function handleSliderChange(e, ui)
		{
		  $('.content',"#impressum_layer_content").css({top: ui.value + 'px'});
		}

		function handleSliderSlide(e, ui)
		{
			  $('.content',"#impressum_layer_content").css({top: ui.value + 'px'});
		}
		$('#fancybox-close').bind('click', function () {
			$.fancybox.close();
		});

		$('#newsletter_submit').parent().bind('submit', function () {
			if ($('#newsletter_name').val() === $('#newsletter_name').attr('title')) {
				$('#newsletter_name').val('');
			}
			$.ajax({
				url: '/newsletter/',
				type: 'POST',
				dataType: 'text',
				data: $('#newsletter_form').serialize(),
				success: function (data) {
					if (data === '1') {
						$('#newsletter_layer').addClass('newsletter_success');
						$('#newsletter_form').fadeOut();
						$('#newsletter_success').fadeIn();
					} else {
						$('#newsletter_email').css('outline', '2px solid red');
					}
				}
			});
			return false;
		});
	}

	function __unbindPageEvents() {
		$(window).unbind('statechange');
		$(window).unbind("keydown");
		$('a:internal').unbind('click');
		$(selector + ' a').unbind('click');
	}
	$('footer').css('position','absolute');

	DOMcursor360 = $('#cursor360');
	apng_support(cursor360activate);

	
    $('body').bind('mousemove', cursor360);

	loadPageAjax = __loadPageAjax;
	reinitializePage = __reinitializePage;
	unbindPageEvents = __unbindPageEvents;
	commonEventHandlers = __commonEventHandlers;

	__reinitializePage();

	if (music === true) {
		initMusic();
	}

	resizeWindow();
	
	$('#newsletter_name').setDefaultValue();
	$('#newsletter_email').setDefaultValue();
	
	if ($_GET['showContact'] == '1'){
    showContact();
  }
});

/**
 * @author Alexander Farkas
 * v. 1.22
 */

function showContact(){
	$('.kontakt', 'footer').trigger('click');
}

(function($) {
	if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
		var oldCurCSS = $.curCSS;
		$.curCSS = function(elem, name, force){
			if(name === 'background-position'){
				name = 'backgroundPosition';
			}
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
	
	var oldAnim = $.fn.animate;
	$.fn.animate = function(prop){
		if('background-position' in prop){
			prop.backgroundPosition = prop['background-position'];
			delete prop['background-position'];
		}
		if('backgroundPosition' in prop){
			prop.backgroundPosition = '('+ prop.backgroundPosition;
		}
		return oldAnim.apply(this, arguments);
	};
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			var start = $.curCSS(fx.elem,'backgroundPosition');
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			fx.start = [start[0],start[2]];
			var end = toArray(fx.end);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		//return;
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);

function apng_support(callback) {
	"use strict";
	var apngTest = new Image();  
	try {
		var ctx = document.createElement("canvas").getContext("2d");
	} catch (e) {
		callback();
		return;
	}
	apngTest.onload = function () {
		ctx.drawImage(apngTest, 0, 0);
		self.apng_supported = ctx.getImageData(0, 0, 1, 1).data[3] === 0;
		if (self.apng_supported !== true)
		callback();
	};
	apngTest.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACGFjVEwAAAABAAAAAcMq2TYAAAANSURBVAiZY2BgYPgPAAEEAQB9ssjfAAAAGmZjVEwAAAAAAAAAAQAAAAEAAAAAAAAAAAD6A+gBAbNU+2sAAAARZmRBVAAAAAEImWNgYGBgAAAABQAB6MzFdgAAAABJRU5ErkJggg==";

	// frame 1 (skipped on apng-supporting browsers): [0, 0, 0, 255]
	// frame 2: [0, 0, 0, 0]
};

function closed() {
	if ($('#closed').length) {
		$('#closed').delay(1500).animate({
			'margin-top' : 0
		}, 1000, 'swing');
	}
}
