$(function() {
	// Super BG Image
	$.fn.superbgimage.options = {
		slideshow: 0,
		transition: 0,
		vertical_center: 0,
		showimage: 1
	};

	// autoloop for collections
	if ($('body').hasClass('kollektionen')) {
		$.fn.superbgimage.options = {
			transition: 1,
			slideshow: 1,
			slide_interval: 4000,
			randomimage: 0,
			speed: 'slow'
		};
	}
	
	// Zebra	
	$(".zebra li:nth-child(even)").addClass("even");
	
	$(".kol8 a").toggle(function() {
	 	$(".start #kollektionTeaser").fadeIn('fast');
	}, function() {
		$(".start #kollektionTeaser").fadeOut('fast');
	}); 
		
	//	Kontakt Layer
	$(".trigger_adress").mousedown(function() {
		 $("#k_adressen").fadeIn('fast');
	});
	$(".close_adress").mousedown(function() {
		$("#k_adressen").fadeOut('fast');
	});	
	
	//	Kontakt hidden layer navigation
	$(".k_adressen_nav .upper").mousedown(function(){
		$(".k_adressen_daten").hide(0);
		$(this).next().show(0);
		$(".k_adressen_nav .upper").removeClass("active").removeClass("red-gradient");
		$(this).addClass("active").addClass("red-gradient");
	});
	
	// Checkbox Optik
	$('input[type=checkbox]').each(function() {
		$(this).wrap(function() {
			return ($(this).is(':checked')) ? '<span class="custom_checkbox selected" />' : '<span class="custom_checkbox" />';
		});
	});
		
	$('.custom_checkbox input[type=checkbox]').click(function () {
		$(this).parent().toggleClass('selected');
	});
	
	//Länderauswahl Optikersuche
	$("#o_land_select li").click(function() {
		var text = $(this).text();
		$("#o_land_trigger").val(text);
	});
	
	// Kollektion Scrollable
	if ($(".scrollable")) {
		
		var count = 0;
		var groupCount = 0;
		$(".scrollable .items img").each(function(){
			if (count % 3 == 0) $(".scrollable .items").append("<div class='itemGroup itemGroup" + (++groupCount) + "'></div>");
			$(this).addClass('itemImage' + count);
			$(this).next().addClass('itemText' + count);
			$(this).next().next('span').addClass('item_360link' + count);
			$(".scrollable .items .itemGroup" + groupCount).append($(this).next().next('span'));
			$(".scrollable .items .itemGroup" + groupCount).append($(this).next());
			$(".scrollable .items .itemGroup" + groupCount).append($(this));
			++count;
		});
		
		$(".scrollable").scrollable();
		$(".scrollable .items img").click(function() {

			// see if same thumb is being clicked
			if ($(this).hasClass("active")) { return; }

			// calclulate large image's URL based on the thumbnail URL
			var orderIDRegex = /itemImage(\d+)/;
			var orderID = orderIDRegex.exec($(this).attr('class'))[1];
			var url = $(this).attr("name");
			var modalUrl = $(this).attr("rel");
			var modalClass = $(this).attr('class');
			var link360 = $('.scrollable .item_360link' + orderID).html();

			// get handle to element that wraps the image and make it semi-transparent
			var wrap = $("#image_wrap").fadeTo(0, 0.5);

			// get the large image 
			var img = new Image();

			// call this function after it's loaded
			img.onload = function() {
				// make wrapper fully visible
				wrap.fadeTo(0, 1);
				// change the image
				wrap.find("img").attr("src", url);
				// change the text
				$("#kollektionTeaser .content").html($(".scrollable .itemText" + orderID).html());
				// add url to lightbox-link
				wrap.find(".k_lightbox").attr("href", modalUrl).attr('class', modalClass + ' k_lightbox')
				// show 360-display link if available
				if (link360)
					wrap.find('.k_360').attr('href', link360).show();
				else
					wrap.find('.k_360').hide();
			};

			// begin loading the image from www.flickr.com
			img.src = url;

			// activate item
			$(".scrollable .items img").removeClass("active");
			$(this).addClass("active");

		// when page loads simulate a "click" on the first image
		}).filter(":first").click();
	}
	
	if ( $(".opt_scrollable").length == 1 && $(".opt_scrollable .items").length == 1 ) {
		
		var classAttr = $(".opt_scrollable .items").attr('class');
		var itemCount = Number(classAttr.substr(classAttr.length-2));
		var totalItems = $(".opt_scrollable .items .opt_content").length;
		var wraps = Math.ceil(totalItems / itemCount);
		
		for ( i = 1; i <= wraps; i++ ) {
			var itemWrap = $('<div class="itemwrap"></div>').appendTo(".opt_scrollable .items");
			var items = $(".opt_scrollable .items > .opt_content");
			
			for ( j = 0; j < itemCount; j++ ) {
				itemWrap.append(items[j]);
			}
		}
		
		// Optiker-News overview Scrollable
		$(".opt_scrollable").scrollable();
		
		
		
	}
	
	if ( $(".opt_scrollable .itemwrap").length <= 1 || $(".opt_scrollable .itemwrap .opt_content").length <= 9 ) {
		$(".opt_browser a").addClass('disabled');
		$(".opt_scrollhead a").addClass('disabled');
	}
	
	
	// Geschichte Scrollable & Bg-Image
	var history_showLastYear = location.href.indexOf('lastYearDisplay') > -1;
	var seeking = false;
	if ($('.history_scrollable').length) {
		if ($('#history_subnav').length) {
			$.fn.superbgimage.options = {
				slideshow: 0,
				transition: 1,
				vertical_center: 0,
				showimage: history_showLastYear ? $('#thumbs a').length : 1
			};
			$('#thumbs a').click(function() {
				if (!seeking)
					historyScr_API.seekTo($('#thumbs a').index($(this)));
			});
		}
		
		// init scrollable pos if last year should initally be displayed (prevents flicker)
		if (history_showLastYear)
			$('.history_scrollable .items').first().css('left', '-' + ($('.itemwrap').outerWidth() * ($('#thumbs a').length - 1)) + 'px');

		// get decade nav element and check for next/previous decade nav-points
		var decadeNavCount = $('#history_nav li').length;
		var activeNav = $('#history_nav li.active');
		var prevPageURL = activeNav.index() > 0 ? activeNav.prev().find('a').attr('href') : '';
		if (prevPageURL != '' && prevPageURL[0] != '/') prevPageURL = '/' + prevPageURL;
		var nextPageURL = activeNav.index() < decadeNavCount - 1 ? activeNav.next().find('a').attr('href') : '';
		if (nextPageURL != '' && nextPageURL[0] != '/') nextPageURL = '/' + nextPageURL;
		
		// prepare prev/next links on scrollable if there are prev/next decades
		var prevLink = $('#history_textbox .prev');
		if (prevPageURL != '') prevLink.addClass('decade_jumpable');
		var nextLink = $('#history_textbox .next');
		if (nextPageURL != '') nextLink.addClass('decade_jumpable');
	
		function jumpToPrevPeriod() {
			var prevParam = (prevPageURL.indexOf('?') > -1 ? '&' : '?') + 'lastYearDisplay';
			location.href = prevPageURL + prevParam;
		}
		
		prevLink.click(function() {
			if (!$(this).hasClass('disabled')) {
				seeking = true;
				$('#thumbs a').eq(historyScr_API.getIndex() - 1).click();
			} else if ($(this).hasClass('decade_jumpable'))
				jumpToPrevPeriod();
		});
		nextLink.click(function() {
			if (!$(this).hasClass('disabled')) {
				seeking = true;
				$('#thumbs a').eq(historyScr_API.getIndex() + 1).click();
			}
		});
		$(document).keydown(function(evt) {
			if (evt.keyCode == 37 && historyScr_API.getIndex() > 0) {
				seeking = true;
				$('#thumbs a').eq(historyScr_API.getIndex() - 1).click();
			}
			if (evt.keyCode == 39 && historyScr_API.getIndex() < historyScr_API.getSize() - 1) {
				seeking = true;
				$('#thumbs a').eq(historyScr_API.getIndex() + 1).click();
			}
			if (evt.keyCode == 37 && prevLink.hasClass('disabled') && prevLink.hasClass('decade_jumpable'))
				jumpToPrevPeriod();
		});
		
		// init scrollable and set callback to change bg image as well when seeking
		$('.history_scrollable').scrollable({
			keyboard: 'static',
			onBeforeSeek: function(evt, newIndex) {
				if (newIndex == historyScr_API.getIndex()) return;
				var direction = newIndex > historyScr_API.getIndex() ? 'next' : 'prev';
				var directionLink = eval(direction + 'Link');
				
				// jump to prev/next decade when possible
				if (directionLink.hasClass('disabled') && directionLink.hasClass('decade_jumpable')) {
					location.href = eval(direction + 'PageURL');
					return;
				}
				$.superbg_inAnimation = false;
			},
			onSeek: function() { seeking = false; }
		});
		var historyScr_API = $('.history_scrollable').data('scrollable');
		if (history_showLastYear) historyScr_API.seekTo(historyScr_API.getSize() - 1);
	}
	
	// career dynamic content
	if ($('#career-nav li').length) {
		$('#career-nav li').click(function() {
			$('#content-box').html($(this).find('div.career-content').html());
			$('#career-content-container').show();
			var theURL = location.href;
			var currentURL = (theURL.indexOf('#') > -1) ? theURL.substr(0, theURL.lastIndexOf('#')) : theURL;
			var hashTag = $(this).find('span.deeplink-url').html();
			if (hashTag && hashTag != '')
				location.href = currentURL + '#' + $(this).find('span.deeplink-url').html();
		});
		
		// deeplink handling through hashtag in URL
		var hashTagPart = location.href.split('#')[1];
		if (hashTagPart) {
			var initCareerContent;
			$('#career-nav li span.deeplink-url').each(function() {
				if ($(this).html() == hashTagPart) {
					initCareerContent = $(this);
					window.setTimeout(function() {initCareerContent.parent('li').click();}, 100);
				}
			});
		}
	}
	
	// Press-Releases moving boxes
	if ($('#press_releases').length) {
		$('#press_releases').movingBoxes({
			startPanel   : 1,      // start with this panel
			width        : 950,    // overall width of movingBoxes (not including navigation arrows)
			panelWidth   : .35,    // current panel width% of overall width
			reducedSize  : .78,    // non-current panel size% of panel size
			imageRatio   : 32/22,  // Image ratio
			fixedHeight  : true,
			initialized  : function() { $('#press_releases').hide().css('top', '0').fadeIn(); }
		});
	}
	
	// Fancybox
	$(".k_extra_nav a").fancybox({
		overlayColor: '#000',
		overlayOpacity: '0.65',
		titleShow: false,
		width: 749,
		height: 506
	});
	
	// superbgimage & home intro fade
	if ($('#home-intro').length) {
		$.fn.superbgimage.options.slideshow = 0;
		window.setTimeout(function() {
			$('#home-intro').animate({ opacity: 0 }, 400, function() {
				$('#home-intro').hide();
				$('#thumbs').startSlideShow();
			})
		}, 3000);
	}
	$('#thumbs').superbgimage();
		
});

