$(function () {
	'use strict';

	var $header = $('#header');
	var $content = $('#content');
	var $leftBlock = $('#left');
	var $miscNavigation = $('#misc-navigation');
	var $productNavigation = $('#product-navigation');
	var $shadowLeft = $('#shadow-left');
	var $shadowTop = $('#shadow-top');

	var headerWidth = $header.width();
	var miscMargin = parseInt($miscNavigation.css('margin-top'));
	var miscHeight = $miscNavigation.outerHeight(1) - miscMargin;

	var $win = $(window);
	
	var isIE6 = $(document.body).hasClass('ie6');
	var isIE7 = $(document.body).hasClass('ie7');
	var isIE8 = $(document.body).hasClass('ie8');
	
	if (isIE6) {
		$('.csc-default > *:first-child').css('margin-top', 0);
		$('.csc-default > *:last-child').css('margin-bottom', 0);
		
		// ??? otherwise top shadow doesnt show
		$('#shadow-left').hide();
		setTimeout(function() {
			$('#shadow-left').show();
		}, 0);
	}
	
	// fix for first-child in ie7
	if (isIE7) {
		$('.csc-default > *:last-child').css('margin-bottom', 0);
		// first-child selector has a bug in IE7: if a first-child element has a preceding
		// comment node, it is not counted as first-child.
		// Solution: remove all comments
		// TODO: document.getElementsByTagName('*')
		$(':first-child').each(function() {
			var prev = this.previousSibling;
			var nextPrev;
			while(prev) {
				nextPrev = prev.previousSibling;
				if (prev.nodeType === 8) {
					prev.parentNode.removeChild(prev);
				}
				prev = nextPrev;
			}
		});
	}
	
	if (isIE8) {
		$('.csc-default > *:last-child').css('margin-bottom', 0);
	}

	var $div = $('<div>', {css: {position: 'fixed', top: '10px', left: 0}}).appendTo(document.body);
	var supportFixed = $div[0].offsetTop === 10;
	$div.remove();

	// is this layout currently using fixed positioning (for head and left)
	var usingFixed = false;

	var $toTop = $();

	$win.bind('resize.diasys', function() {
		var winHeight = $win.height();
		var winWidth  = $win.width();

		var hasScrollbar = $(document).height() > winHeight;
		if (hasScrollbar && supportFixed) {
			if (!$toTop.length) {
				var translations = {
					en: 'Back to top',
					de: 'Nach oben'
				};
				$toTop = $('<div>', {id: 'back-to-top', 'class': 'noprint'}).appendTo($content);
				$toTop.width($content.width());
				$toTop.append($('<a>', {
					href: '#top',
					text: translations[$('html').attr('lang')] || translations.de,
					'class': 'more-link',
					click: function(event) {
						event.stopPropagation();
						event.preventDefault();

						// scroll to top
						$('<p>').prop('foo', $win.scrollTop()).animate({foo: 0}, {
							step: function(p) {
								$win.scrollTop(p);
							}
						});
					}
				}));
			}

			if ($win.scrollTop() && !$toTop.data('showing')) {
				$toTop.stop().fadeTo(null, 1).data('showing', true);
			}
		} else {
			$toTop.stop().fadeTo(null, 0).data('showing', false);
		}

		$miscNavigation.css('margin-top',20);
		var miscPos = $miscNavigation.offset().top;
		if (usingFixed) {
			// fix jquery bug with fixed positioned elements
			miscPos -= $win.scrollTop();
		}
		// check if it is possible to position the miscNavigation at the bottom of the initial screen (the fold)
		$miscNavigation.css('margin-top', Math.max(miscMargin, winHeight - miscPos - miscHeight + miscMargin));
		
		if (isIE6) {
			$content.height('auto');
			var height = Math.max($content.outerHeight(), $leftBlock.outerHeight()) - 2;
			$shadowLeft.height(height);
			$content.height(height - parseInt($content.css('padding-top'),0));
		}

		// check if the complete layout can be fixed positioned
		if (!supportFixed) {
			return;
		}

		var canUseFixed = true;

		if (headerWidth > winWidth) {
			canUseFixed = false;
		}

		if ($leftBlock.height() + $leftBlock[0].offsetTop > winHeight + 2) {
			canUseFixed = false;
		}

		if (canUseFixed && !usingFixed) {
			// apply fixed positioning
			$(document.body).addClass('fixed');
			$shadowLeft.appendTo($header);
			$shadowTop.appendTo($header);
			$productNavigation.appendTo($header);
			usingFixed = true;
		} else if (!canUseFixed && usingFixed) {
			// position absolute
			$(document.body).removeClass('fixed');
			$shadowLeft.appendTo($content);
			$shadowTop.appendTo($content);
			$productNavigation.appendTo($content);
			usingFixed = false;
		}
	}).trigger('resize.diasys');

	var scrollTimeout;
	$win.bind('scroll.diasys', function() {
		clearTimeout(scrollTimeout);
		scrollTimeout = setTimeout(function() {
			var scrollTop = $win.scrollTop();
			var showing = $toTop.data('showing');
			
			if (scrollTop && !showing) {
				$toTop.stop().fadeTo(null, 1).data('showing', true);
			} else if (!scrollTop && showing) {
				$toTop.stop().fadeTo(null, 0).data('showing', false);
			}
		}, 50);
	});

	$('label.placeholder').each(function() {
		var $label = $(this);
		var $input = $('#' + $label.attr('for').replace(/(\[|\])/g, '\\$1'));
		
		setTimeout(function() {
			if ($input.val()) {
				// currently text within the input, hide the label
				$label.addClass('hidden');
			}
		}, 100);

		if ($input.val()) {
			// currently text within the input, hide the label
			$label.addClass('hidden');
		}
		$input.change(function() {
			if ($input.val()) {
				// currently text within the input, hide the label
				$label.addClass('hidden');
			}
		});

		$input.focus(function() {
			$label.addClass('partial');
		}).blur(function() {
			if (!$input.val()) {
				// it's empty, show the label
				$label.removeClass('partial hidden');
			}
		}).keypress(function() {
			$label.addClass('hidden');
		});

		if ($input.closest('form').attr('id') != 'search' && $input.parent()[0] === $label.parent()[0]) {
			// position the label at the same position where the text would start within the input
			var parent = $input.parent();
			if (parent.css('position') == 'static') {
				parent.css('position', 'relative');
			}
			$label.css('position', 'absolute');
			var offset = $input.position();
			$label.css({
				top:   offset.top  + parseInt($input.css('padding-top'),10)  + parseInt($input.css('border-top-width'),10),
				left:  offset.left + parseInt($input.css('padding-left'),10) + parseInt($input.css('border-left-width'),10),
				width: $input.width()
			});
			$input.css('display', 'block');
		}
	});
	
	// init toggle for product page
	$('#product-page').delegate('.toggle', 'mousedown click', function(event) {
		event.preventDefault();
		event.stopPropagation();
		
		if (event.type != 'click') {
			return;
		}
		var $toggle = $(this);
		var $li = $toggle.closest('li');
		var $content = $toggle.next('.toggle-content');
		if ($li.hasClass('toggle-open')) {
			// hide
			$li.removeClass('toggle-open');
			$content.stop().slideUp(slideStop);
			return;
		}

		$('.target').removeClass('target');
		
		var $container = $toggle.closest('#product-page');
		
		var $open = $container.find('.toggle-open');
		
		$content.stop().slideDown(slideStop);
		$li.addClass('toggle-open');
		
		if ($open.length) {
			$open.removeClass('toggle-open').find('.toggle-content').stop().slideUp(slideStop);
		}
		
		function slideStop() {
			$(this).height('auto');
		}
	});

	// faking :target onload
	if (location.hash) {
		var fragment = location.hash.substr(1);
		var $element = $('#' + fragment);
		if (!$element.length) {
			$element = $('*[name=' + fragment + ']');
		}
		$element.addClass('target');

		var top = $element.offset().top;
		if ($(document.body).hasClass('fixed')) {
			// fixing scrolling, when this is the fixed layout
			top -= $content.position().top + $productNavigation.height();
			setTimeout(function() {
				document.body.scrollTop = top;
			}, 0);
		}
	}

	$(document).delegate('a[href*=#]', 'click', function(event) {
		// check if this link points to an anchor within this document
		if ((this.pathname == location.pathname || '/' + this.pathname == location.pathname) &&
			this.search == location.search) {
			
			// faking :target pseudo selector
			$('.target').removeClass('target');
			// internal link, check if link can be found
			var fragment = this.hash.substr(1);
			if (!fragment) {
				// ignore empty fragments
				return;
			}
			var $element = $('#' + fragment);
			if (!$element.length) {
				$element = $('*[name=' + fragment + ']');
			}

			if (!$element.length) {
				// didn't find the destination of the anchor
				return;
			}
			
			$element.addClass('target');

			// ok, got the element. Scroll to it (minus the fixed header)
			var top = $element.offset().top;
			if ($(document.body).hasClass('fixed')) {
				// fixing scrolling, when this is the fixed layout
				top -= $content.position().top + $productNavigation.height();
			}
			// jQuery 1.6 doesn't allow the animation of $(window).
			// Solution: Create a fake element and animate that!
			$('<p>').prop('foo', $win.scrollTop()).animate({foo: top}, {
				step: function(p) {
					$win.scrollTop(p);
				},
				complete: function() {
					if (!$(document.body).hasClass('fixed')) {
						// if the hash is changed, additional scrolling occurs in IE, which moves the element behind the fixed header
						location.hash = fragment;
					}
				}
			})

			event.preventDefault();
			event.stopPropagation();
		}
	});



	$('.vierwd-diasys-download-list').delegate('.vierwd-diasys-downloads-toggle', 'mousedown click', function(event) {
		event.preventDefault();
		event.stopPropagation();
		
		if (event.type != 'click') {
			return;
		}
		
		var fragment = this.hash.substr(1);
		if (!fragment) {
			// ignore empty fragments
			return;
		}
		var $element = $('#' + fragment);
		$('.vierwd-diasys-downloads-toggle-content').not($element).slideUp();
		$element.slideToggle();
	});

	if ($('#vierwd-download-filter').length) {
		(function() {
			var $filterElement = $('#vierwd-download-filter');
			
			// get all languages that are used for downloads
			var $languages = $('.vierwd-download-language');
			if (!$languages.length) {
				$filterElement.closest('.csc-default').hide();
				return;
			}

			// Filter by languages
			var $filterLanguage = $('#vierwd-download-filter-language select');

			var languages = vierwd.diasys.translation.filter.language;
			$.each(languages, function(key, translation) {
				if ($('.vierwd-download-language-' + key).length) {
					// there are downloads in that language, add an entry to the filter
					$('<option>', {value: key, text: translation}).appendTo($filterLanguage);
				}
			});

			$filterLanguage.bind('change.diasys', function() {
				if (!this.value) {
					// show all downloads
					$('.vierwd-download-language').show();
				} else {
					// hide all (language) downloads...
					$('.vierwd-download-language').hide();
					// ... then show all with the correct language
					$('.vierwd-download-language-' + this.value).show();
				}
			});
		})();
	}


	// create overlay icons for lightbox images
	$('a[rel^=lightbox]').each(function() {
		$('<div>', {
			'class': 'lightbox-icon-overlay'
		}).prependTo(this);
	});



	var $jobformSelect = $('#formhandler-application-type');
	if ($jobformSelect.length) {

		$jobformSelect.change(function() {
			// hide the following inputs and only show the one, that was selected
			var fields = $(this).closest('.csc-form-field').nextAll('.csc-form-field:lt(' + this.length + ')').hide();
			fields.find(':input').prop('disabled', true);
			fields.eq(this.selectedIndex).show().find(':input').prop('disabled', false);
		}).change();
	}


	var $passwordField  = $('#tx-srfeuserregister-pi1-password');
	var $passwordRepeat = $('#tx-srfeuserregister-pi1-password_again');
	var $submitButton   = $('#tx-srfeuserregister-pi1-submit');

	if ($passwordField.length) {
		// it is a page with password field
		checkPasswordStrength();
		$passwordField.keyup(checkPasswordStrength);
		$passwordRepeat.keyup(checkPasswordStrength);

		var $hintElement = $('#password-hints');

		$('.password-hints-link').click(function(event) {
			event.preventDefault();

			var pos = $(this).position();

			$hintElement.css({top: pos.top - 20, left: pos.left + 20}).show();
		});

		$hintElement.mouseleave(function() {
			$hintElement.hide();
		});
	}

	function checkPasswordStrength() {
		var i;
		var pwd = $passwordField.val();
		var pwd2 = $passwordRepeat.val();
		
		var $indicators = $('div.password-strength span.indicator');
		var indicateTo = Math.ceil(getPasswordStrength(pwd) / 100 * $indicators.length);

		$indicators.removeClass('active').filter(':lt(' + indicateTo + ')').addClass('active');

		var minlength = 8;
		var seqmaxlength = 3;
		var result = 'none';

		var lowercase = false;
		var uppercase = false;
		var numeric = false;
		var special = false;

		for (i = 0; i < pwd.length; i++) {
			var ord = pwd.charCodeAt(i);

			if (ord >= 48 && ord <= 57) numeric = true;
			else if (ord >= 65 && ord <= 90) uppercase = true;
			else if (ord >= 97 && ord <= 122) lowercase = true;
			else if ((ord >= 32 && ord <= 126) || ord >= 128) special = true;
		}

		if (pwd.length == 0) result = 'none';
		else if (pwd.length < minlength) result = 'minlength';
		else if (!numeric) result = 'numeric';
		else if (!uppercase) result = 'uppercase';
		else if (!lowercase) result = 'lowercase';
		else if (!special) result = 'special';
		else if (pwd.length < pwd2.length || pwd.substring(0, pwd2.length) != pwd2) result = 'match';

		$('.password-notice').hide();
		$('#password-quality-'+result).show();

		if (result != 'none' || pwd2 != pwd) {
			$submitButton.prop('disabled', true);
			$submitButton.addClass('disabled');
		} else {
			$submitButton.prop('disabled', false);
			$submitButton.removeClass('disabled');
		}
	}

	function getPasswordStrength(pwd) {

		var quality = 0;
		var length = pwd.length;
		var lower = pwd.toLowerCase();

		var lowercase = false;
		var uppercase = false;
		var numeric = false;
		var special = false;

		var usedChars = [];
		var i = 0;

		for(i = 0; i < length; i++) {
			var ord = pwd.charCodeAt(i);

			if (ord >= 48 && ord <= 57) numeric = true;
			else if (ord >= 65 && ord <= 90) uppercase = true;
			else if (ord >= 97 && ord <= 122) lowercase = true;
			else if (ord >= 32 && ord <= 126) special = true;
			else if (ord >= 128) special = true;

			if (ord >= 48 && ord <= 57) quality += 8; // bonus for numeric
			else if (ord >= 65 && ord <= 90) quality += 8; // bonus for uppercase
			else if (ord >= 97 && ord <= 122) quality += 0; // nothing for lowercase
			else if (ord >= 32 && ord <= 126) quality += 15; // bonus for special
			if ($.inArray(ord, usedChars) == -1) usedChars.push(ord);
		}
		quality += usedChars.length * 6;

		quality += length * 4;

		if (quality > 100) quality = 100;

		if (!lowercase) quality *= 0.8;
		if (!uppercase) quality *= 0.7;
		if (!numeric) quality *= 0.8;
		if (!special) quality *= 0.8;

		for (i = 0; i <= length - 3; i++) {
			var str = lower.substr(i, 3);
			if (str.charAt(0) == str.charAt(1) && str.charAt(1) == str.charAt(2)) {
				quality *= 0.9;
				break;
			}
		}

		var sequences = [
			'abcdefghijklmnopqrstuvwxyz',
			'1234567890',
			'!"ß$%&/()=?',
			'qwertzuiop¸+',
			'asdfghjklˆ‰#',
			'<yxcvbnm,.-', ';:_',
			'147', '258', '369', '741', '852', '963', '159', '357', '753', '951'
		];

		for (i = 0; i <= length - 3; i++) {
			var str = lower.substr(i, 3);
			for (var j = 0; j < sequences.length; j++) {
				var sequence = sequences[j];
				if (sequence.indexOf(str) != -1) {
					quality *= 0.7;
					break;
				} else if (sequence.split('').reverse().join('').indexOf(str) != -1) {
					quality *= 0.7;
					break;
				}
			}
		}

		return quality;
	}

});


// Calibration
$(document).ready(function(){
	var $resultContainer = $('#vierwd-diasys-calibration-result');

	var $parameter = $('#vierwd-diasys-parameter');
	var $lotSelect = $('#vierwd-diasys-lot');
	var $form = $parameter.closest('form');
	
	if (!$resultContainer.length || !$parameter.length || !$lotSelect.length) {
		return;
	}
	
	var $newLot = $('<select>', {name: $lotSelect.attr('name'), id: $lotSelect.attr('id')});
	$lotSelect.replaceWith($newLot);
	$lotSelect = $newLot;
	
	$parameter.change(function() {
		$lotSelect.empty();
		$resultContainer.empty();
		$lotSelect.append($('<option>', {value: '', text: '-'}));
		var lots = '' + $(this).children(':selected').data('lots');
		if (lots) {
			lots = lots.split(',');
			$.each(lots, function(index, lot) {
				if (lot) {
					$lotSelect.append($('<option>', {value: lot, text: lot}));
				}
			});
		}
	}).change();
	$lotSelect.change(function() {
		$form.trigger('submit');
	});
	
	if ($parameter.find('option').length == 1) {
		// only one option, replace it
		var $option = $parameter.find('option:first');
		var $part = $();
		$part[$part.length++] = $('<span>', {text: $option.text()})[0];
		$part[$part.length++] = $('<input>', {
			value: $option.val(),
			type: 'hidden',
			name: $parameter.attr('name')
		})[0];
		$parameter.replaceWith($part);
	}

	$form.submit(function(event) {
		event.preventDefault();

		var $form = $(this);

		$resultContainer.empty();
		
		$spinner = $form.find('.spinner');
		if (!$spinner.length) {
			$spinner = $('<img>', {
				src: 'typo3/gfx/spinner.gif',
				alt: '',
				'class': 'spinner'
			}).insertAfter($form.find(':submit'));
		}

		// post the form back to the search action, show the result
		$.ajax({
			url: $form.attr('action'),
			type: 'POST',
			data: $form.serializeArray(),
			success: function(data, textStatus, jqXHR) {
				$spinner.remove();
				$resultContainer.html(data);
			}
		});
	});
});

