(function($) {

	/**
	 * Equalize height on a collection of elements
	 *
	 * WARNING: If you're loading webfonts this script will most likely trigger beforehand.
	 * So the calculation is broken if the system-font and the webfont have different number of lines!
	 * Wrap the call to this function in window.load to prevent this!
	 *
	 * @memberof jQuery
	 * @function equalizeHeights
	 */
	$.fn.equalizeHeights = function (buffer) {
		var buffer = buffer || 1;
		return this.css('min-height', 0).css('min-height', Math.max.apply(this, $(this).map(function (i, e) {
			return $(e).outerHeight() + buffer;
		}).get()));
	};

    $(document).ready(function () {

	    // Mobile search
	    $('#searchMobile').each(function () {
		    var $searchMobile = $(this);
		    var $open = $searchMobile.find('.open');
		    var $form = $searchMobile.find('form');
		    var $sword = $searchMobile.find('.suche_feld');
		    var $submit = $searchMobile.find('.suche_button');

		    $open.on('click', function (e) {
			    e.stopPropagation();
			    $form.addClass('expanded');
		    });
		    $submit.on('click', function (e) {
			    e.preventDefault();
			    if ($sword.val() !== '') {
				    $form.submit();
			    }
			    else {
				    $form.removeClass('expanded');
			    }
		    });
	    });

        // Mobile navigation
        $('#navMobile').each(function () {
            var $navMobile = $(this);

            $navMobile.find('a').on('click', function (e) {
		        e.stopPropagation();
	        });

            $navMobile.find('li.ifsub').each(function () {
                var $li = $(this);

                if ($li.hasClass('act')) {
                    $li.data('act', true);
                    $li.find('>ul').show();
                    $li.addClass('expanded');
                } else {
                    $li.data('act', false);
                }

                $li.on('click', function (e) {
                    e.stopPropagation();
                    if ($(e.target).is($li) || $(e.target).is('span')) {
                        if (!$li.data('act')) {
                            $li.data('act', true);
                            $li.find('>ul').show();
                            $li.siblings('li').data('act', false).removeClass('expanded').find('>ul').hide();
                            $li.addClass('expanded');
                        } else {
                            $li.data('act', false);
                            $li.find('>ul').hide();
                            $li.removeClass('expanded');
                        }
                    }
                });
            });
        });

	    // Simple wrapper for too wide tables
	    $('table.contenttable').each(function(){
		    var $table = $(this);
		    var $tCanvas = $('<div class="tableCanvas"></div>');
		    var $tDimensions = $('<div class="tableDimensions"></div>');
		    $tDimensions.height($table.height());
		    $table.addClass('responsive').wrap($tDimensions).wrap($tCanvas);
	    });

	    // Lightbox (Magnific Popup)
	    $('.csc-default').each(function() {
		    var $csc = $(this);
		    var $imgSelection = $csc.find('a[rel^="lightbox"]');
		    if (jQuery.isFunction($imgSelection.magnificPopup)) {
			    $imgSelection.magnificPopup({
				    type: 'image',
				    mainClass: 'mfp-add-zoom',
				    gallery: {
					    //enabled: Boolean($imgSelection.first().data('lightbox-imageset')) === true
					    enabled: true
				    }, zoom: {
					    enabled: true, duration: 300, easing: 'ease-in-out'
				    }
			    });
		    }
	    });

	    // Rewriting inline script for tx-jfmulticontent-pi1
	    $('.tx-jfmulticontent-pi1').each(function(){
		    /**
		     * Checking location hash for a relevant value which is sth. like this: #jfmulticontent_cXXXXX-Y
		     * [jfmulticontent_cXXXXX] is the id of the whole accordion
		     * [Y] is the index of the requested item (aka referenced content element)
		     */
		    var hash = window.location.hash; //console.log(hash);
		    if (!hash || hash.match('jfmulticontent') === null) {
			    return false;
		    }
		    var accordionId = hash.split('-')[0]; //console.log(accordionId);
		    var requestedIndex = hash.split('-')[1]-1; //console.log(requestedIndex);
		    var $accordion = $(accordionId);

		    $accordion.accordion({
			    autoHeight:false,
			    active:requestedIndex,
			    animated:'slide'
		    });
		    $('html,body').animate({
			    scrollTop: $accordion.find('h2').eq(requestedIndex).offset().top
		    }, 300);
	    });


	    /**
	     * Link datepicker to the specified fields
	     * Either single fields or grouped (range) fields ar possible
	     */
	    $('input.date').each(function(){
		    var $field      = $(this),
			    groupClass  = 'group',
                monthsArray = 'Januar,Februar,März,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember',
			    months      = monthsArray.split(','),
	            daysArray   = 'So,Mo,Di,Mi,Do,Fr,Sa',
			    days        = daysArray.split(','),
			    format      = 'd.m.Y';


			// if is a grouped date field (range, from-to) with given class
		    if($field.hasClass(groupClass)) {

			    // is the field either the from field...
			    if($field.data('date-from')) {
					// get id of the from field
				    var tofieldId = $field.data('date-to-field');

				    $field.datetimepicker({
					    format: format,
					    timepicker: false,
						// localize months and dates
					    lang: 'de',
					    i18n:{
						    de:{
							    months: months,
							    dayOfWeek: days
						    }
					    },
					    // set max date of to field
					    onShow:function(ct){
						    this.setOptions({
							    maxDate: $(tofieldId).val()?$(tofieldId).val():false
						    });
					    }
				    });
			    //... or the to field
			    } else if($field.data('date-to')) {
				    // get id of the to field
				    var fromfieldId = $field.data('date-from-field');

				    // trigger to field
				    $field.datetimepicker({
					    format: format,
					    timepicker: false,
					    // localize months and dates
					    lang: 'de',
					    i18n:{
						    de:{
							    months: months,
							    dayOfWeek: days
						    }
					    },

					    // set min date of from field
					    onShow:function(ct){
						    this.setOptions({
							    minDate: $(fromfieldId).val()?$(fromfieldId).val():false
						    });
					    }
				    });
			    }
		    // if no grouped date field, trigger the normal datepicker
		    } else {
			    $field.datetimepicker({
				    format: format,
				    timepicker: false,
				    // localize months and dates
				    lang: 'de',
				    i18n:{
					    de:{
						    months: months,
						    dayOfWeek: days
					    }
				    }
			    });
		    }
	    });


	    /**
	     * Internship application form
	     * Toggle driving license field if "yes" is choosen
	     */
	    $('#driversLicenseCheck').on('change',function(){
		    // if value 1 = yes, show field
		    if( $(this).val()==='1'){
			    $("#driversLicenseWrap").show()
		    }
		    // else hide
		    else {
			    $("#driversLicenseWrap").hide()
		    }
	    });



        // Temporary helper
        //var helper = $('<div style="position:fixed;bottom:0;right:0;background:yellowgreen;font-size:10px;padding:3px 6px;color:white;z-index:99999;"></div>').prependTo('body');

	    // Handle resize or orientation changes
	    $(window).bind('resize',function() {
		    var mediaQueries = [
			    'screen and (max-width: 979px)',
			    'screen and (max-width: 768px)',
			    'screen and (max-width: 640px)',
			    'screen and (max-width: 480px)',
			    'screen and (max-width: 400px)',
			    'screen and (max-width: 320px)'
		    ];

			// Simplest implementation of throttling the resize-event via setTimeout
	        clearTimeout(window.resizedFinished);
		    window.resizedFinished = setTimeout(function(){
		        //console.log('window.resizedFinished');
	            //helper.text('default');

			    // Help imageslider to get its dimensions right (the brute force way)
			    $('.tx-imagecycle-pi1').each(function(){
				    var $images = $(this).find('.tx-imagecycle-pi1-images');
				    var height =  $images.find('img:visible').height();
				    $images.css('height',height);
			    });

			    // Adjust heights of teasers on homepage. At some point they don't float correctly due to text-wrapping...
			    $('.page.start article.teaserboxSmall').equalizeHeights();
			   /*
			    for (var i = 0; i < mediaQueries.length; i++) {
				    if (window.matchMedia(mediaQueries[i]).matches) {
					    //helper.text(mediaQueries[i]);
				    }
			    }
			    */
	        }, 100);
        });
	    $(window).bind('load',function(){
		    $('body').trigger('resize');
	    });
    });
})(jQuery);
