/* Global variables */
var lb_default_content = '#content_left';
var mobileOS = (navigator.userAgent.match(/iPad/i) !== null || navigator.userAgent.match(/iPhone/i) !== null || navigator.userAgent.match(/iPod/i) !== null || navigator.userAgent.match(/Android/i) !== null);

/* Document ready . Start */
$(document).ready(function() {
	// Remove: noscript tag
	$('div.c005').remove();

	// Init: Stage
	if ($('#stage').length > 0) {
		$.stage();
	}

	// Init: Teaser rotation
	if ($('ul.teaser_rotation').length > 0) {
		$('ul.teaser_rotation').teaserrotation();
	}

	// Init: Sliding teaser
	$('span.slide_button').slidingteaser();

    // Init: Map trigger
	$('#map_trigger').click(function() {
	$(this).parent().parent().parent().find('span.slide_button').trigger('click');
	return false;
        });

	// Init: Subnavigation
	$('.subnavigation').subnavigation();

	// Init: External Links
	$.externallink();

	// Check: Border radius support
	supported_borderRadius();

	// Bind: Lightbox forms
	// Important: We have to bind the "submit"-event first because of IE BUG!!
	$('body').find('form.lb_form').live('submit', function() {
		// Variables
		var elem = $(this);
		// Call: Lightbox
		$.lightbox({
			e: elem,
			e_url: elem.attr('action'),
			e_type: 'POST'
		});
		// Avoid: Redirect
		return false;
	});

	// Bind: Lightbox links
	$('body').find('a[rel=lightbox]').live('click', function() {
		// Variables
		var elem = $(this);
		// Call: Lightbox
		$.lightbox({
			e_url: elem.attr('href')
		});
		// Avoid: Redirect
		return false;
	});

	// Init: Automatic content loader (Lightboxes, Pages)
	autoload();

	// Init: Location search
	if ($('#location_search').length > 0) {
		$('#location_search').location_search();
	}

	// Init: Print function
	$('.print').live('click', function(event) {
        // Prevent: Default event
        event.preventDefault();
		// Call: Page print
		page_print();
	});

	// Init: Font size selector
	$('.fsize_value', '.font_selector').live('mouseover mouseout', function(event) {
		// Variables
		var e = $(this);
		var e_parent = e.parent();
		var e_index = e.index();
		// Set: Hover classes
		if (event.type === 'mouseover') {
			e_parent.addClass('font_selector_' + e_index + '_hover');
		} else {
			e_parent.removeClass('font_selector_' + e_index + '_hover');
		}
	});

	/* IE6 */
	if ($.browser.msie && parseInt($.browser.version) < 7) {
		// Navigation :hover
		$('#navigation a.main').parent().not('.first, #clientLogin').hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		);
		// Share Icon :hover
		$('#share_icon').hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		);
		// Stage selector :hover
		$('p', '#stage_selector').hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		);
		// Buttons :hover
		$('button.submit').live('mouseover mouseout', function(event) {
			if (event.type === 'mouseover') {
				$(this).addClass('hover');
			} else {
				$(this).removeClass('hover');
			}
		});
		// Lighbox . Close :hover
		$('#lightbox_close').live('mouseover mouseout', function(event) {
			if (event.type === 'mouseover') {
				$(this).addClass('hover');
			} else {
				$(this).removeClass('hover');
			}
		});
	}

	/* Mobile OS */
	if (mobileOS) {
		// Init: Show/Hide sharing flyout
		sharing();

		// Function: Show/Hide sharing flyout
		function sharing() {
			// Variables
			var d = document;
			var s_icon = d.getElementById('share_icon');

			// Remove: Element highlighting
			s_icon.style.webkitTapHighlightColor = 'rgba(0,0,0,0)';

			// Init
			if (s_icon) {
				share_hide();
			}

			// Function: Show sharing flyout
			function share_show() {
				s_icon.removeEventListener('touchstart', share_show, false);
				s_icon.className = 'hover';
				s_icon.addEventListener('touchstart', share_hide, false);
				d.addEventListener('touchstart', share_hide, true);
			}

			// Function: Hide sharing flyout
			function share_hide() {
				d.removeEventListener('touchstart', share_hide, true);
				s_icon.removeEventListener('touchstart', share_hide, false);
				s_icon.className = '';
				s_icon.addEventListener('touchstart', share_show, false);
			}
		}
	}





	/*
	// Dummy function: Search -> Remove in Typo3!! 
	$('#global_search_form').submit(function(event) {
        // Prevent: Default
        event.preventDefault();
		// Redirect
		if ($('#fe_global_search_query').val().length > 2) {
			window.location.href = 'page_searchresult.html';
		} else {
			window.location.href = 'page_searchresult_empty.html';			
		}
	});
	*/

});
/* Document ready . End */

/* Init: Cufon */
Cufon.replace('#navigation a.main', { fontFamily: 'Audi Type Extended' });
Cufon.replace('h1.c_h1', { fontFamily: 'Audi Type Extended' });
Cufon.replace('h2', { fontFamily: 'Audi Type Extended', hover: true });
Cufon.replace('h3', { fontFamily: 'Audi Type Extended' });
Cufon.replace('.emergency_call', { fontFamily: 'Audi Type Extended' });


/* PlugIn: Stage */
$.stage = function(settings) {
	// Initialize: Default parameter
	var defaults = {
		item_fade_speed: 800,
		class_active: 'active',
		class_lastactive: 'last-active',
		selector_speed: 600,
		selector_easing: 'easeOutExpo',
		selector_hide_delay: 1000,
		selector_init_timeout: 2500,
		rotation: true,
		rotation_interval: 6000
	};
	// Build: Settings object
	var settings = $.extend(defaults, settings);

	// Variables
	var stage = $('#stage_container');
	var stage_obj = stage.find('li');
	var selector = $('#stage_selector');
	var selector_list = selector.find('ul');
	var selector_obj = selector_list.find('li');
	var initial_timeout = 0;
	var item_interval = 0;
	var item_current = selector_list.find('li.active').index();

	// Remove: Stage preloader
	$('#stage').css('background-image', 'none');

	// Init: If we have more than one selector object...
	if (selector_obj.length > 1) {
		// Show: Stage selector
		selector.css('display', 'block');

		// Store: Selector list width
		var selector_list_offPos = (parseInt(selector_list.width()) * -1) + 'px';

		// Hide: Selector after timeout
		initial_timeout = window.setTimeout(hideSelector, settings.selector_init_timeout);

		// Bind: Selector function
		selector_clicker();

		// Init: Rotation
		if (settings.rotation) {
			rotation();
		}

		// Show/Hide: Selector
		selector.hover(
			function() {
				// Reset: Timeout
				if (initial_timeout !== undefined && initial_timeout !== 0) {
					resetInitialTimeout();
				}
				// Move: Selector inside
				$(this).dequeue().stop().animate({left: '0'}, settings.selector_speed, settings.selector_easing);
			}, function() {
				// Move: Selector outside
				if ($(this).is(':animated')) {
					$(this).stop().animate({left: selector_list_offPos}, settings.selector_speed, settings.selector_easing);
				} else {
					$(this).delay(settings.selector_hide_delay).animate({left: selector_list_offPos}, settings.selector_speed, settings.selector_easing);
				}
			}
		);
	}

	// Function: Hide selector
	function hideSelector() {
		if (initial_timeout !== undefined && initial_timeout !== 0) {
			// Reset: Initial timeout
			resetInitialTimeout();
			// Move: Selector outside
			selector.stop().animate({left: selector_list_offPos}, settings.selector_speed, settings.selector_easing);
		}
	}

	// Function: Bind click event to selector
	function selector_clicker() {
		selector_obj.bind('click', function() {
			// Reset: Rotation interval
			resetRotationInterval();
			// Call: Switcher
			switcher($(this));
		});
	}

	// Function: Reset initial timeout
	function resetInitialTimeout() {
		if (initial_timeout !== undefined) {
			// Clear: Initial timeout
			clearTimeout(initial_timeout);
			// Reset: Initial timeout
			initial_timeout = 0;
		}
	}

	// Function: Reset rotation interval
	function resetRotationInterval() {
		if (item_interval !== undefined) {
			// Clear: Rotation interval
			window.clearInterval(item_interval);
			// Reset: Rotation interval
			item_interval = 0;
		}
	}

	// Function: Switcher
	function switcher(elem) {
		// If element is not active...
		if (!elem.hasClass(settings.class_active)) {
			// Unbind: Click event from selector
			selector_obj.unbind('click');
			// Store: Current item
			item_current = elem.index();
			// Set: Selector classes
			selector.find('li.' + settings.class_active).removeClass(settings.class_active);
			elem.addClass(settings.class_active);
			// Get: Active stage element
			var active = stage.find('li.' + settings.class_active);
			if (active.length === 0) {
				active = stage.find('li:last');
			}
			// Get: Next element
			var next = stage.find('li:eq(' + item_current + ')');
			// Fade: Between elements
			active
				.addClass(settings.class_lastactive);
			next
				.css('opacity', '0')
				.addClass(settings.class_active)
				.animate({opacity: '1'}, settings.item_fade_speed);
			active
				.animate({opacity: '0'}, settings.item_fade_speed, function() {
					// Remove: Classes
					active.removeClass(settings.class_active + ' ' + settings.class_lastactive);
					// ReBind: Selector function
					selector_clicker();
					// ReInit: Rotation
					if (settings.rotation) {
						rotation();
					}
			});
		} else {
			// ReInit: Rotation
			if (settings.rotation) {
				rotation();
			}
		}
	}

	// Function: Rotation
	function rotation() {
		// Set: Rotation interval
		item_interval = window.setInterval(triggerRotation, settings.rotation_interval);
	}

	// Function: Trigger rotation
	function triggerRotation() {
		// Update: item_current
		if (item_current === (selector_obj.length-1)) {
			item_current = 0;
		} else {
			item_current++;
		}
		// Fake: User click
		selector_list.find('li:eq(' + item_current + ')').trigger('click');
	}
};

/* Function: Teaser rotation */
(function($) {
	$.fn.teaserrotation = function(options) {
		// Settings
		var settings = $.extend({}, {
			class_active: 'active',
			class_lastactive: 'last-active',
			fade_speed: 2000,
			fade_interval: 6000
		}, options);

		return this.each(function() {
			// Variables
			var elem = $(this);
			var elem_height = 0;
			var max_height = 0;

			// Update: CSS and get max element height
			elem
				.css({'padding-right': '0', 'padding-left': '1px' })
				.find('li.teaser_rotation_obj').each(function() {
					// Get: Element height
					elem_height = $(this).height();
					// Set: CSS position
					$(this).css('position', 'absolute');
					// Update: max_height
					if (elem_height >= max_height) {
						max_height = elem_height;
					}
					// Set: Element height
					elem.css('height', max_height + 'px');
				});

			// Init: Fade elements if we have more than one element
			if (elem.find('li').length > 1) {
				cnt = window.setInterval(fading, settings.fade_interval);
			}

			// Function: Fade in/out
			function fading() {
				// Get: Active element
				var active = elem.find('li.' + settings.class_active);
				if (active.length === 0) {
					active = elem.find('li:last');
				}
				// Get: Next element
				var next = active.next().length ? active.next() : elem.find('li:first');
				// Fade: Between elements
				active
					.addClass(settings.class_lastactive);
				next
					.css('opacity', '0')
					.addClass(settings.class_active)
					.animate({opacity: '1'}, settings.fade_speed);
				active
					.animate({opacity: '0'}, settings.fade_speed, function() {
						active.removeClass(settings.class_active + ' ' + settings.class_lastactive);
					});
			}
		});
	};
})(jQuery);

/* Function: Sliding teaser */
(function($) {
	$.fn.slidingteaser = function(options) {
		// Settings
		var settings = $.extend({}, {
			slide_speed: 620,
			slide_easing: 'easeOutExpo'
		}, options);

		return this.each(function() {
			// Variables
			var e = $(this);
			var e_front, e_front_height, e_front_pos, e_back, e_back_height, e_close, panel_pos;

			// Show: Button and bind click event
			e.css('display', 'block').bind('click', slideup);

			// Function: Slide up
			function slideup() {
				// Variables
				e_parent = e.parent();
				e_front = e_parent.find('div.slide_teaser_front');
				e_front_height = ($('.teaserPanel_mid').height() - parseInt(e_parent.css('padding-top')) - parseInt(e_parent.css('padding-bottom')));
				e_front_pos = e_front.parent().position();
				e_back = $('#' + e.metadata().target);
				e_back_height = e_back.height();
				e_close = e_back.find('span.slide_button_close');
				panel_pos = $('div.teaserPanel').position();

				// Calculate: Bottom position
				var e_calc_bottom = parseInt($('#wrapper').outerHeight(true)) - (parseInt(panel_pos.top) + e_front_height) - 1;

				// Unbind: Click event from button
				e.unbind('click');

				// Set: Teaser height
				e_parent.css('height', e_front_height + 'px');

				// Show: Slider (back)
				e_back
					.css({bottom: e_calc_bottom + 'px', height: e_front_height + 'px', left: e_front_pos.left + 'px', display: 'block'})
					.animate({
						height: e_back_height + 'px'
					}, settings.slide_speed, settings.slide_easing, function() {
						// Bind: Click event to close button
						e_close.bind('click', slidedown);
					});
			}

			// Function: Slide down
			function slidedown() {
				// Unbind: Click event from close button
				e_close.unbind('click');

				// Hide: Slider (front)
				e_back
					.animate({
						height: e_front_height + 'px'
					}, settings.slide_speed, settings.slide_easing, function() {
						e_back.animate({opacity: 0}, 160, function() {
							// Reset: Slider (back) styles
							$(this).css({left: '-6000px', height: 'auto', display: 'none', opacity: 1});
							// Reset: Teaser height
							e_parent.css('height', 'auto');
							// ReBind: Click event to button
							e.bind('click', slideup);
						});
					});
			}
		});
	};
})(jQuery);

/* Function: Location search */
(function($) {
	$.fn.location_search = function(options) {
		// Settings
		var settings = $.extend({}, {
			default_value: 'Ihre Postleitzahl'
		}, options);

		return this.each(function() {
			$(this)
				.find('#fe_location_selector')
				.focus(function() {
					var current_value = $(this).val();
					if (current_value === settings.default_value) {
						$(this).val('');
					}
				})
				.end()
				.find('button.submit')
				.click(function() {
					$('#slide_teaser_location_selector')
						.find('span.slide_button_close')
						.trigger('click');
				});
		});
	};
})(jQuery);

/* Function: Subnavigation */
(function($) {
	$.fn.subnavigation = function(options) {
		// Settings
		var settings = $.extend({}, {
			item_slide_speed: 400
		}, options);

		return this.each(function() {
			// Variables
			var elem = $(this);
			var links = elem.find('a');

			// Bind: Click function to link elements
			links.click(function() {
				// Variables
				var link = $(this)
				var link_href = $(this).attr('href');
				var link_li = link.parent();
				var link_ul = link_li.parent();

				// Handle: URL
				handleURL('page', link_href);

				// Init: Slide navigation
				slide_navigation();

				// Load: Page
				load_page();

				// Function: Load page
				function load_page() {
					// Check: If we have a valid element href
					if (link_href !== '#') {
						// Load: Content by Ajax
						$.ajax({
							url: link_href,
							cache: false,
							success: function(data) {
								// Get: Page title
								var page_title = data.search(/<title>(.*)<\/title>/);

								// Set: New page title
								document.title = RegExp.$1;

								// Remove: Teaser from #col1_content
								$('#col1_content').find('div.teaserBox').remove();
								$('#col1_content').find('div.teaser_plain').remove();

								// Load: #col1_content
								var col1_content = $('#col1_content', data);

								// Remove: Subnavigation from #col1_content
								col1_content.find('div.subnavigation').replaceWith('');

								// Get: Contents from #col1_content
								col1_content = col1_content.contents();

								// Append: Content to #col1_content
								$('#col1_content').append(col1_content);

								// Load: #col2_content
								var col2_content = $('#col2_content', data);

								// Replace: Loaded content with existing #col2_content
								$('#col2').html(col2_content);
								// Show: Stage
								$('#stage_content').css('visibility', 'visible');
								// Load: Javascript
								loadScript(data);

								// Refresh: Cufon
								Cufon.refresh();

								// ReInit: External links
								$.externallink();
							}
						});
					}					
				}

				// Function: Slide navigation
				function slide_navigation() {
					// Show/Hide: Navigation elements
					if (link_ul.hasClass('level_one')) {
						// Hide: Opened 3rd level lists
						link_ul.find('ul.level_three').slideUp(settings.item_slide_speed, function() {
							$(this).removeClass('active');
						});
						// Handle: 2rd level
						if (!link_li.is('.current')) {
							// Hide: Opened 2nd level lists
							link_ul.find('ul.level_two').slideUp(settings.item_slide_speed, function() {
								$(this).removeClass('active');
							});
							// Show: 2nd level list
							link_li.find('ul.level_two').slideDown(settings.item_slide_speed, function() {
								$(this).addClass('active');
							});
						}
						// Remove: Current class from all 1st, 2nd and 3rd level list elements
						link_ul.find('li').removeClass('current');
						// Add: Current class to selected list element
						link_li.addClass('current');
					} else if (link_ul.hasClass('level_two')) {
						// Handle: 3rd level
						if (!link_li.is('.current')) {
							// Hide: Opened 3rd level lists
							if (link_li.find('ul').length === 0 || link_li.find('ul').css('display') === 'none') {
								link_ul.find('ul').slideUp(settings.item_slide_speed, function() {
									$(this).removeClass('active');
								});
							}
							// Show: 3rd level list
							link_li.find('ul').slideDown(settings.item_slide_speed, function() {
								$(this).addClass('active');
							});
						}
						// Remove: Current class from all 2nd and 3rd level list elements
						link_ul.find('li').removeClass('current');
						// Add: Current class to selected list element
						link_li.addClass('current');
					} else if (link_ul.hasClass('level_three')) {
						// Remove: Current class from all 2nd and 3rd level list elements
						link_ul.parent().parent().find('li').removeClass('current');
						// Add: Current class to selected list element
						link_li.addClass('current');
					}
				}

				// Avoid: Redirect
				return false;
			});
		});
	};
})(jQuery);

/* PlugIn: External links */
$.externallink = function(settings) {
	// Initialize: Default parameter
	var defaults = {
		additional_text: ' (externer Link)'
	};
	// Build: Settings object
	var settings = $.extend(defaults, settings);
	// Get: External links, set target and extend their title
	$('body').find('a[rel=external]').each(function() {
		// Variables
		var elem = $(this);
		var elem_title = elem.attr('title');
		// Set: Target
		elem.attr('target', '_blank');
		// Add: Additional link text
		if (elem_title !== '' && elem_title.indexOf(settings.additional_text) === -1) {
			elem.attr('title', elem_title + '' + settings.additional_text);
		}
	});
};

/* Function: Check border radius support */
function supported_borderRadius() {
	$(function() {
		$.support.borderRadius = false;
		$.each(['borderRadius','BorderRadius','MozBorderRadius','WebkitBorderRadius','OBorderRadius','KhtmlBorderRadius'], function() {
			if (document.body.style[this] !== undefined) {
				$.support.borderRadius = true;
			}
			return (!$.support.borderRadius);
		});
	});
}

/* Function: Load Flash Movie */
function loadMovie(e_id, f_url, f_id, f_width, f_height, f_vars) {
	// Set: Flash version
	var majorVersion = '10.0.0';
	// Handle: Flash vars
	if (typeof f_vars !== undefined) {
		var flashvars = f_vars;
	} else {
		var flashvars = false;
	}
	// Set: Flash parameter
	var params = {
		allowFullscreen: true,
		allowScriptAccess: 'sameDomain',
		bgcolor: '#999999',
		menu: 'false',
		play: true,
		quality: 'high',
		scale: 'noscale',
		wmode: 'opaque'
	};
	// Set: Flash attributes
	var attributes = {
		id: f_id
	};
	// Create: Flash movie
	swfobject.embedSWF(f_url, e_id, f_width, f_height, majorVersion, false, flashvars, params, attributes);
}

/* Function: Load Script (for Ajax-Requests) */
function loadScript(A) {
	var B = A.match(/<script(.|\s)*?\/script>/g);
	if (!B) {
		return;
	}
	if (B !== null && B.length) {
		$.each(B, function() {
			var C = this + '';
			var D = $(C).attr('src');
			if (!D) {
				$('body').append($(C));
			}
		});
	}
}

/* Function: Print */
function page_print() {
	// Print: Window
    window.print();
}

/* PlugIn: Lightbox */
$.lightbox = function(settings) {
	// Initialize: Default parameter
	var defaults = {
		e: '',
		e_url: '',
		e_type: 'GET',
		e_get: lb_default_content,
		e_width: 0,
		e_callback: null,
		lb_id: 'lightbox',
		lb_container: 'lightbox_container',
		lb_content: 'lightbox_content',
		lb_overlay: 'overlay',
		lb_overlay_speed: 400,
		lb_overlay_opacity: 0.80,
		lb_overlay_preload: 'preload',
		lb_close: 'lightbox_close',
		lb_vSpace: 40,
		lb_hSpace: 40,
		lb_border: 20,
		lb_maxWidth: parseInt($('#wrapper').outerWidth()),
		lb_elements_speed: 800,
		close_icon: true,
		close_overlay: false,
		print_file: 'fileadmin/templates/1/designvorlage/css/print_lightbox.css'
	};
	// Build: Settings object
	var settings = $.extend(defaults, settings);

/*
console.log(settings.e_url);
console.log(settings.e_type);
console.log(settings.e_get);
console.log(settings.e_width);
console.log(settings.e_callback);
*/

	// Variables
	var html, body, close, container, content, lightbox, overlay;
	var serialized_data = '';

	// Handle: Form data
	if (settings.e !== undefined && settings.e !== '' && typeof settings.e === 'object' && settings.e_type !== undefined && settings.e_type !== '' && settings.e_type === 'POST') {
		// Serialize: Form data
		serialized_data = settings.e.serialize();
	}

	// Handle: URL
	handleURL('lightbox', settings.e_url);

	// Load: Print CSS
	if ($('head').find('link[href=' + settings.print_file + ']').length <= 0) {
		$('<link>', {
			rel: 'stylesheet',
			type: 'text/css',
			href: settings.print_file,
			media: 'print'
		}).appendTo('head');
	}

	if (settings.e_url !== '' && settings.e_url !== '#') {
		// Fix: IE6
		if ($.browser.msie && parseInt($.browser.version) < 7) {
			$('html, body').animate({scrollTop: 0}, 0);
			$('select').css('visibility', 'hidden');
		}

		// Store: DOM-Elements
		html = $('html');
		body = $('body');

		// Hide: Scrollbars
		hide_scrollbars();

		// Calculate: Max width
		var calc_maxWidth = (settings.lb_maxWidth - (settings.lb_border*2) - (settings.lb_hSpace*2));

		// Remove: Existing lightbox
		lightbox_container_remove();

		// Create: Lightbox
		lightbox_create();

		// Create: Overlay
		lightbox_overlay_create();

		// Show: Overlay and create lightbox content
		lightbox_show();

		// Return: false
		return false;
	}

	// Function: Hide scrollbars
	function hide_scrollbars() {
		if ($.browser.msie) {
			html.css({
				'overflow': 'hidden',
				'overflow-x': 'hidden'
			});
		} else {
			body.css('overflow', 'hidden');
		}
	}

	// Function: Remove existing lightbox container
	function lightbox_container_remove() {
		var c = $('#' + settings.lb_container);
		if (c.length > 0) {
			c.remove();
		}
	}

	// Function: Create lightbox
	function lightbox_create() {
		if ($('#' + settings.lb_id).length === 0) {
			body.append('<div id="' + settings.lb_id + '"></div>\n');
		}
		// Store: DOM-Elements
		lightbox = $('#' + settings.lb_id);
		// Fix: IE6
		if ($.browser.msie && parseInt($.browser.version) < 7) {
			lightbox.css('height', $(window).height());
		}
	}

	// Function: Create overlay
	function lightbox_overlay_create() {
		if ($('#' + settings.lb_overlay).length > 0) {
			// Add: Preloader class
			$('#' + settings.lb_overlay).addClass(settings.lb_overlay_preload).css('height', '100%');
		} else {
			// Append: Overlay
			if (lightbox.length > 0) {
				lightbox.append('\n\t<div id="' + settings.lb_overlay + '" class="' + settings.lb_overlay_preload + '"></div>\n');
			} else {
				lightbox_close();
			}
		}
		// Store: DOM-Elements
		overlay = $('#' + settings.lb_overlay);
		// Fix: IE6
		if ($.browser.msie && parseInt($.browser.version) < 7) {
			overlay.css('height', $(window).height());
		}
	}

	// Function: Show lightbox
	function lightbox_show() {
		if (overlay.length > 0) {
			overlay.fadeTo(settings.lb_overlay_speed, settings.lb_overlay_opacity, function() {
				// Create: Lightbox container
				lightbox_create_container();
			});
		} else {
			lightbox_close();
		}
	}

	// Function: Create lightbox container
	function lightbox_create_container() {
		if (lightbox.length > 0) {
			// Variables
			var tmp_html = '';

			// Create: Container HTML
			tmp_html += '\t<div id="' + settings.lb_container + '" class="clearfix">\n';
			if (settings.close_icon) {
				tmp_html += '\t\t<div id="' + settings.lb_close + '" title="Schließen">Schließen</div>\n';
			}
			if (($.support.borderRadius === undefined || ($.support.borderRadius !== undefined && !$.support.borderRadius))) {
				tmp_html += '\t\t<div id="lb_top" class="clearfix">\n';
				tmp_html += '\t\t\t<div id="lb_top_left" class="lb_outerBox"></div>\n';
				tmp_html += '\t\t\t<div id="lb_top_mid" class="lb_outerBox"></div>\n';
				tmp_html += '\t\t\t<div id="lb_top_right" class="lb_outerBox"></div>\n';
				tmp_html += '\t\t</div>\n';
			}
			tmp_html += '\t\t<div id="' + settings.lb_content + '" class="' + (($.support.borderRadius !== undefined && $.support.borderRadius) ? 'br_support ' : '') + 'clearfix"></div>\n';
			if (($.support.borderRadius === undefined || ($.support.borderRadius !== undefined && !$.support.borderRadius))) {
				tmp_html += '\t\t<div id="lb_bottom" class="clearfix">\n';
				tmp_html += '\t\t\t<div id="lb_bottom_left" class="lb_outerBox"></div>\n';
				tmp_html += '\t\t\t<div id="lb_bottom_mid" class="lb_outerBox"></div>\n';
				tmp_html += '\t\t\t<div id="lb_bottom_right" class="lb_outerBox"></div>\n';
				tmp_html += '\t\t</div>\n';
			}
			tmp_html += '\t</div>\n';

			// Append: Container HTML to lightbox
			lightbox.append(tmp_html);

			// Store: DOM-Elements
			if (settings.close_icon) {
				close = $('#' + settings.lb_close);
			}
			container = $('#' + settings.lb_container);
			content = $('#' + settings.lb_content);

			// Create: Lightbox content
			lightbox_content_create();
		} else {
			lightbox_close();
		}
	}

	// Function: Create lightbox content
	function lightbox_content_create() {
		// Variables
		var html = '';

		if (typeof settings.e_url !== undefined) {
			// Load: Content by Ajax
			$.ajax({
				url: settings.e_url,
				type: settings.e_type,
				data: serialized_data,
				dataType: 'html',
				complete: function(xhr) {
					// Get response text
					var xhr_text = xhr.responseText;

					// Handle: Requestet content
					if (content.length > 0 && xhr_text.indexOf('id="logo_audi_bkk"') !== -1) {
						// Append: Requestet content to lightbox
						content.html($('<div></div>').append(xhr_text.replace(/<script(.|\s)*?\/script>/g, '')).find(settings.e_get));

						// Handle: Clean pages
						if (xhr_text.indexOf('cleanpage') !== -1) {
							// Add: New class for individual styles
							content.find('#content_left').addClass('cleanpage');
						}
						if (xhr_text.indexOf('cleanpage_228') !== -1) {
							// Add: New class for individual styles
							content.find('#content_left').addClass('cleanpage_228');
						}
						if (xhr_text.indexOf('cleanpage_704') !== -1) {
							// Add: New class for individual styles
							content.find('#content_left').addClass('cleanpage_704');
						}

						// Load: Javascript
						loadScript(xhr_text);

						// Refresh: Cufon
						Cufon.refresh();

						// ReInit: External links
						$.externallink();

						// Set: Lightbox dimensions
						lightbox_set_dimensions();

						// Set: Lightbox position
						lightbox_set_position();

						// Calculate: Lightbox position
						lightbox_calc_position();

						// Remove: Preloader
						lightbox_remove_preloader();

						// Bind: Close function
						lightbox_binding_close('bind');

						// Init: Callback
						if (typeof settings.e_callback === 'function') {
							// Call: Callback function
							settings.e_callback();
						}

						// Bind: Resize
						$(window).resize(function() {
							lightbox_calc_position();
						});
					} else {
						lightbox_close();
					}
				},
				error: function() {
					lightbox_close();
				}
			});
		} else {
			lightbox_close();
		}
	}

	// Function: Set dimensions
	function lightbox_set_dimensions() {
		if (container.length > 0) {
			// Set: Fixed width
			if (!isNaN(settings.e_width) && settings.e_width > 0) {
				// Get: Content width
				var e_width = parseInt(lightbox.find(settings.e_get).outerWidth());
				// Calculate: Required width
				var max_e_width = ( e_width + (settings.lb_border*2) + (settings.lb_hSpace*2) );
				// Update: Container width
				if (max_e_width <= settings.e_width) {
					if (settings.e_width <= calc_maxWidth) {
						// Set: Container width
						container.css('width', (settings.e_width+(settings.lb_border*2)) + 'px');
					} else {
						if (max_e_width >= calc_maxWidth) {
							// Set: Container width
							container.css('width', (calc_maxWidth+(settings.lb_border*2)) + 'px');
							// Set: Content overflow
							content.css('overflow-x', 'auto');
						} else {
							// Set: Container width
							container.css('width', (e_width+(settings.lb_border*2)) + 'px');
						}
					}
				} else {
					// Set: Container width
					container.css('width', (e_width+(settings.lb_border*2)) + 'px');
					// Set: Content overflow
					content.css('overflow-x', 'auto');
				}
			}

			// Set: Dynamic width
			if (isNaN(settings.e_width) || settings.e_width <= 0) {
				// Get: Content width
				var e_width = parseInt(lightbox.find(settings.e_get).outerWidth());
				// Calculate: Required width
				var max_e_width = ( e_width + (settings.lb_border*2) + (settings.lb_hSpace*2) );
				// Update: Container width
				if (max_e_width >= calc_maxWidth) {
					// Set: Container width
					container.css('width', (calc_maxWidth+(settings.lb_border*2)) + 'px');
					// Set: Content overflow
					content.css('overflow-x', 'auto');
				} else {
					// Set: Container width
					container.css('width', (e_width+(settings.lb_border*2)) + 'px');
				}
			}

			// Set: Container dimensions
			container.css({
				'height': 'auto'
			});

			// Calculate: Container middle width
			var mid_width = (parseInt(container.width())-(settings.lb_border*2));

			// Set: Lightbox Top and bottom width
			$('#lb_top').css('width', (mid_width+(settings.lb_border*2)) + 'px');
			$('#lb_top_mid').css('width', mid_width + 'px');
			$('#lb_bottom').css('width', (mid_width+(settings.lb_border*2)) + 'px');
			$('#lb_bottom_mid').css('width', mid_width + 'px');
		} else {
			lightbox_close();
		}
	}

	// Function: Set position
	function lightbox_set_position() {
		if (container.length > 0) {
			container.css({
				'left': '50%',
				'margin-left': '-' + (container.outerWidth() / 2) + 'px'
			});
		} else {
			lightbox_close();
		}
	}

	// Function: Remove preloader
	function lightbox_remove_preloader() {
		if (overlay.length > 0) {
			overlay.removeClass(settings.lb_overlay_preload);
		}
	}

	// Function: Bind close function
	function lightbox_binding_close(a) {
		if (a === 'bind') {
			if (settings.close_icon && close.length > 0) {
				close.bind('click', lightbox_close);
			}
			if (settings.close_overlay && overlay.length > 0) {
				overlay.bind('click', lightbox_close);
			}
		} else if (a === 'unbind') {
			if (settings.close_icon && close.length > 0) {
				close.unbind('click', lightbox_close);
			}
			if (settings.close_overlay && overlay.length > 0) {
				overlay.unbind('click', lightbox_close);
			}
		}
	}

	// Function: Show scrollbars
	function show_scrollbars() {
		if ($.browser.msie) {
			html.css({
				'overflow': 'scroll',
				'overflow-x': 'auto'
			});
		} else {
			body.css({
				'overflow': 'auto'
			});
		}
	}

	// Function: Close lightbox
	function lightbox_close() {
		// Handle: URL
		handleURL('', '');
		// Remove: Print CSS
		$('head').find('link[href=' + settings.print_file + ']').remove();
		// Remove: Lightbox container
		$('#' + settings.lb_container).remove();
		// Unbind: Close function
		lightbox_binding_close('unbind');
		// Hide: Overlay
		$('#' + settings.lb_overlay).fadeTo(settings.lb_overlay_speed, 0, function() {
			// Remove lightbox
			$('#' + settings.lb_id).remove();
			// Show scrollbars
			show_scrollbars();
			// Fix: IE6
			if ($.browser.msie && parseInt($.browser.version) < 7) {
				$('select').css('visibility', 'visible');
			}
		});
	}

	// Function: Calculate lightbox position
	function lightbox_calc_position() {
		// Check: Mobile OS
		if (mobileOS) {
			// Set: Lightbox position
			lightbox.css('position', 'absolute');
			// Scroll to: Top of page
			$('html, body').animate({scrollTop: 0}, 0);
		}

		if ((lightbox.length > 0) && (overlay.length > 0) && (container.length > 0)) {
			// Define: Lightbox
			lightbox.css({
	        	'height': ((mobileOS) ? $(document).height() : $(window).height()),
				'width': $('body').width(),
				'overflow-y': 'hidden'
			});
			// Define: Height
			if ($(window).height() < ((container.outerHeight() + (settings.lb_vSpace * 2)))) {
				// Set: Lightbox height
				var l_height = $(window).height();
				// Check: Mobile OS
				if (mobileOS) {
					if ((container.outerHeight() + (settings.lb_vSpace * 2)) > $(window).height()) {
						// Reset: Lightbox height if lightbox is larger than window
						l_height = (container.outerHeight() + (settings.lb_vSpace * 2));

						if ((container.outerHeight() + (settings.lb_vSpace * 2)) < $(document).height()) {
							// Reset: Lightbox height if document is larger than lightbox
							l_height = $(document).height();
						}
					}
				}
				lightbox.css({
	        		'height': l_height,
					'overflow-y': 'scroll'
				});
				overlay.css('height', ((mobileOS) ? $(document).height() : (container.outerHeight() + (settings.lb_vSpace * 2))));
				container.css('top', settings.lb_vSpace + 'px');
			} else {
				lightbox.css('overflow-y', 'hidden');
				overlay.css({
					'height': '100%'
				});
				container.css({
					'top': (($(window).height() - container.outerHeight()) / 2) + 'px'
				});
			}
			// Define: Width
			if ($(window).width() < ((container.outerWidth() + (settings.lb_hSpace * 2)))) {
				lightbox.css({
					'width': $(window).width(),
					'overflow-x': 'scroll'
				});
				overlay.css('width', container.outerWidth() + (settings.lb_hSpace * 2));
				container.css({
					'left': settings.lb_hSpace + 'px',
					'margin-left': 0 + 'px'
				});
			} else {
				lightbox.css('overflow-x', 'hidden');
				overlay.css({
					'width': '100%'
				});
				container.css({
					'left': '50%',
					'margin-left': '-' + (container.outerWidth() / 2) + 'px'
				});
			}
		} else {
			lightbox_close();
		}
	}

};

// Function: Handle URL
function handleURL(c, url) {
	// Get: Location
	var location_href = document.location.href;
	var location_href_arr = location_href.split('#');

	if (location_href_arr.length > 1) {
		location_href = location_href_arr[0];
	}

	// Update: Share link
	if (c === 'page') {
		// Build: Share link
		var share_link = 'index.php?id=45&share=' + location_href + ((url !== undefined && url !== '#' && c !== undefined && c !== '') ? '#source=' + url + '&c=' + c : '#source=&c=');
		// Set: Share link
		$('a.sendlink', '#share_inner_box').attr('href', share_link);
	}

	// Update: Location
	document.location.href = location_href + ((url !== undefined && url !== '#' && c !== undefined && c !== '') ? '#source=' + url + '&c=' + c : '#source=&c=');
}

// Function: Automatic content loader
function autoload() {
	// Check if we have a source...
	if (document.location.href.indexOf("#source") !== -1) {
		// Variables
		var src_arr	= document.location.href.split('#source=');
		var src = '';
		var src_params_arr = [];
		var src_path = '';
		var src_container = '';

		// Get: URL Hash
		if (src_arr.length > 1) {
			src = src_arr[1];
		}

		// Get: Parameters
		src_params_arr = src.split('&c=');

		// Store: Path
		if (src_params_arr[0] !== undefined) {
			src_path = src_params_arr[0];
		}

		// Store: Container
		if (src_params_arr[1] !== undefined) {
			src_container = src_params_arr[1].substring(0, src_params_arr[1].length);
		}

/*
console.log('Path: ' + src_path);
console.log('Container: ' + src_container);
*/

		if (src_path !== undefined && src_path !== '' && src_path !== '#' && src_container !== undefined && src_container !== '') {
			// Handle: By type of container
			if (src_container === 'lightbox') {
				// Call: Lightbox
				$.lightbox({
					e_url: src_path
				});
			} else if (src_container === 'page') {
				// Get: Last link in subnavigation with equal href and rel="page"
				var elem_trigger = $('div.subnavigation', '#col1_content').find('a[href=' + src_path + ']').filter('[rel=page]:last');

				if (elem_trigger !== undefined && elem_trigger.length > 0) {
					// Trigger: Element click
					elem_trigger.trigger('click');

					// Reset: List and list elements
					$('.subnavigation', '#col1_content')
						.find('ul')
						.removeClass('active')
						.end()
						.find('li')
						.removeClass('current');

					// Get: Parent list
					var elem_li = elem_trigger.parent();
					var elem_ul = elem_li.parent();
					var elem_ul_level = elem_ul.attr('class');

					// Configure: Subnavigation
					if (elem_ul_level === 'level_one') {
						// Config: Current link and list children
						elem_li
							.addClass('current')
							.find('ul.level_two')
							.addClass('active');
					} else if (elem_ul_level === 'level_two') {
						// Config: Current link and list children
						elem_li
							.addClass('current')
							.find('ul.level_three')
							.css('display', 'block')
							.addClass('active');
						// Config: List
						elem_ul
							.addClass('active')
							.closest('li')
							.addClass('current');
					} else if (elem_ul_level === 'level_three') {
						// Config: Current link
						elem_li.addClass('current');
						// Config: List
						elem_ul
							.addClass('active')
							.css('display', 'block')
							.closest('ul.level_two')
							.addClass('active')
							.closest('li')
							.addClass('current');
					}

				}
			}
		}
	}
}

/* Function: Search service center */
function search_service_center(centerPlz) {
	// Variables
	var centerPlz;
	var center = [];
	var geocoder = null;
	var map;
	var zoom = 6;

	// Set: Default map position
	center.push(51.37178);
	center.push(10.50293);

	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();

		// Config: Map
		if (centerPlz !== undefined && centerPlz !== 'undefined' && !isNaN(centerPlz)) {
			// Set: Zoom
			zoom = 9;
			// Center: Map
			centerMap(centerPlz);
			// Show: Location
			showLocation(centerPlz);
		}

		// Get: Map
		map = new GMap2(document.getElementById('map'));
		// Set: New map position and zoom
		map.setCenter(new GLatLng(center[0], center[1]), zoom);
		// Ass: Controls to map
		map.addControl(new GLargeMapControl());
		// Enable: Zoom
		map.enableDoubleClickZoom();

		// Get: Locaton data
		$.getJSON('fileadmin/templates/1/designvorlage/php/getlocations.php', function(_data) {
			if (_data !== undefined && _data.length > 0) {
				// Create: Info bubbles
				for (var i = 0; i < _data.length; i++) {
					// Variables
					var _html = '';
					var _title = '';
					var zip = 0;

					// Create: HTML
					_html += '<strong>' + _data[i].center + '</strong><br /><br />';
					if (_data[i].streetAdditional.length > 0) {
						_html += _data[i].streetAdditional + '<br />';
					}
					_html += _data[i].street + '<br />';
					_html += _data[i].zip + ' ' + _data[i].place + '<br /><br />';
					_html += 'Tel. ' + _data[i].phone + '<br />';
					if (_data[i].fax.length > 0) {
						_html += 'Fax ' + _data[i].fax + '<br />';
					}
					_html += '<a href="mailto:' + _data[i].email + '">' + _data[i].email + '</a><br />';
					_html += '<br /><a href="' + _data[i].link + '" title="zum Service-Center" rel="lightbox" class="more">zum Service-Center</a>';

					// Get: Title for Pin
					_title = ((_data[i].center.length > 0) ? _data[i].center : 'Details');

					// Insert: Marker into map
					insertMarker(_data[i].latitude, _data[i].longitude, _html, _title);
				}
			}
		});
	}

	/* Unload: Document */
	$(document).unload(function() {
		GUnload();
	});

	/* Function: Add address */
	function addAddressToMap(response) {
		if (!response || response.Status.code !== 200) {
			alert('Die angegebene Adresse wurde nicht gefunden.');
		} else {
			// Variables
			place = response.Placemark[0];
			point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			// Create: User icon
			var userIcon = new GIcon(G_DEFAULT_ICON);
			userIcon.image = 'images/map/pin_user.png';
			userIcon.shadow = '';
			userIcon.iconSize = new GSize(24, 43);
			// Set: GMarkerOptions object
			markerOptions = { title: 'Ihr Standort', icon: userIcon };
			// Create: Marker
			var marker = new GMarker(point, markerOptions);
			map.addOverlay(marker);
			marker.openInfoWindowHtml('<strong>Ihr Standort:</strong><br /><br />' + place.address);
			GEvent.addListener(marker, 'click', function() {
				marker.openInfoWindowHtml('<strong>Ihr Standort:<br /><br /></strong>' + place.address);
			});
		}
	}

	/* Function: Insert Marker */
	function insertMarker(_lat, _long, _text, _linktitle) {
		// Create: Location icon
		var locationIcon = new GIcon(G_DEFAULT_ICON);
		locationIcon.image = 'images/map/pin_location.png';
		locationIcon.shadow = '';
		locationIcon.iconSize = new GSize(38, 41);
		// Set: GMarkerOptions object
		markerOptions = { title: _linktitle, icon: locationIcon };
		// Create: Marker
		var marker = new GMarker(new GLatLng(_lat, _long), markerOptions);	
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(_text);
		});
		map.addOverlay(marker);
	}

	/* Funtion: Center map */
	function centerMap(plz) {
		if (geocoder) {
			geocoder.getLatLng('Deutschland ' + plz, function(point) {
				if (point) {
					var thispoint = new GLatLng(point.y, point.x);
					map.setCenter(thispoint);
				}
			});
		}
	}

	/* Function: Show location */
	function showLocation(address) {
		geocoder.getLocations('Deutschland ' + address, addAddressToMap);
	}
}
