const DEBUG = (msg) => {
    if(DEBUGMODE != false){
        console.debug(msg)
    }
};

class Helpers{

	disable_scroll(){
		if (window.addEventListener){
			window.addEventListener('DOMMouseScroll', wheel, false);
		}
		window.onmousewheel = document.onmousewheel = wheel;
		document.onkeydown = keydown;
	}

	enable_scroll() {
		if (window.removeEventListener) {
			window.removeEventListener('DOMMouseScroll', wheel, false);
		}
		window.onmousewheel = document.onmousewheel = document.onkeydown = null;
	}

    getBreakPoint(){
        return  window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/\"/g, '')
    };

	chkForm(f){

		var err = false;
		$('#'+f+' input').each(function(k,i){
			var targetLabel = $('#'+f+' label[for="'+$(i).attr('name')+'"]');
			$(i).removeClass('error');

			$(targetLabel).removeClass('labelerror');
			if($(targetLabel).hasClass('required')){

				if($(i).attr('name').toLowerCase().indexOf('email') != -1){
					var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
					if(!pattern.test($(i).val())){
						$(i).addClass('error');
						$(targetLabel).addClass('labelerror');
						err = true;
					}
				}else if(($(i).attr('type') == 'text' && $(i).val() == '') || ($(i).attr('type') == 'password' && $(i).val() == '') || ($(i).attr('type') == 'checkbox' && !$(i).prop('checked'))){
					$(i).addClass('error');
					$(targetLabel).addClass('labelerror');
					err = true;
				}else if(($(i).attr('name').toLowerCase().indexOf('pw2') != -1) && $('#pwf_form').val() != $(i).val()){
					err = true;
					$(i).addClass('error');
					$(targetLabel).addClass('labelerror');
				}
			}
		});

		$('#'+f+' textarea').each(function(m,l){
			var targetLabel = $('#'+f+' label[for="'+$(l).attr('name')+'"]');
			$(l).removeClass('error');
			$(targetLabel).removeClass('labelerror');
			if($(targetLabel).hasClass('required')){

				if(($(l).val() == '')){
					$(l).addClass('error');
					$(targetLabel).addClass('labelerror');
					err = true;
				}
			}
		});

		if(err) return false;
		return true;
	};

	setGmap(points,id,zoom){

		var zoom = zoom ? zoom : 11;

		setTimeout(function(){
			var infowindow;
			var styles = [
				{
					featureType: 'road',
					elementType: 'all',
					stylers: [
						{ hue: '#c6bfb5' },
						{ saturation: -87 },
						{ lightness: 29 },
						{ visibility: 'on' }
					]
				},{
					featureType: 'landscape',
					elementType: 'all',
					stylers: [
						{ hue: '#f3f2f0' },
						{ saturation: -59 },
						{ lightness: 52 },
						{ visibility: 'on' }
					]
				},{
					featureType: 'poi',
					elementType: 'all',
					stylers: [
						{ hue: '#f3f2f0' },
						{ saturation: -74 },
						{ lightness: 76 },
						{ visibility: 'on' }
					]
				},{
					featureType: 'water',
					elementType: 'all',
					stylers: [

					]
				}
			];

			var styledMap = new google.maps.StyledMapType(styles,
				{name: "Styled Map"});

			var mapOptions = {
				zoom: zoom,
				center: new google.maps.LatLng(47.133452, 8.190855),
				mapTypeIds: [google.maps.MapTypeId.ROADMAP,'map_style'],
				scrollwheel: false,
				streetViewControl: false,
				mapTypeControl: false,
				zoomControl: true,
				zoomControlOptions: {
					position: google.maps.ControlPosition.LEFT_CENTER
				}
			};

			var map = new google.maps.Map(document.getElementById(id),mapOptions);

			map.mapTypes.set('map_style', styledMap);
			map.setMapTypeId('map_style');

			$.each(points, function(k,p){

				var mapimg = '/static/img/gmap_ico.png';

				var size = new google.maps.Size(40, 40);
				var scaledSize = new google.maps.Size(20, 20);


				var image = {
					url: mapimg,
					scaledSize: scaledSize,
					anchor: new google.maps.Point(10,20),
					origin: new google.maps.Point(0,0)
				};


				var myLatlng = new google.maps.LatLng(p.lat,p.lang);
				var marker = new google.maps.Marker({
					position: myLatlng,
					map: map,
					icon: image
				});

				marker.setMap(map);

				infowindow = new google.maps.InfoWindow({
					content: '<div class="mapcontent"><b>'+p.standort+'</b><br/>'+p.strasse+'<br/>'+p.plzort+'<br/>'+ p.telefon+'<br/></div>'
				});

				google.maps.event.addListener(marker, 'click', function() {
					if (infowindow) infowindow.close();

					infowindow = new google.maps.InfoWindow({
						content: '<div class="mapcontent"><b>'+p.standort+'</b><br/>'+p.strasse+'<br/>'+p.plzort+'<br/>'+ p.telefon+'<br/></div>'
					});

					infowindow.open(map,marker);
				});
				infowindow.open(map,marker);

				google.maps.event.addDomListener(window, "resize", function() {
					var center = map.getCenter();
					google.maps.event.trigger(map, "resize");
					map.setCenter(center);
				});

			})

		},0)

    };


}

const HELPERS = new Helpers();
var $applicationForm = $("#applicationForm").children("form");

$(document).ready(function(){

    // Initialize mobile navigation
    setHamburger();

    // Navigation switch by click on "go down" button
    setGoDownButton();

    // Check which navigation to show
    setScrollFunction();

    // Initialize map
    setMap();

    // Initialize gallery
    setGallery();

    // Initialize Jobs
    setJobs();

    /* Application Form */

    if ($applicationForm.length) {

        /* Form Field Focus - Color Change */

            $applicationForm.find("input, textarea").focus(function(){
                $(this).addClass("focused");
            }).blur(function(){
                $(this).removeClass("focused");
                $(this).prev("label").removeClass("error");
            });

         /* Form Validation */

             $applicationForm.submit(function(event) {

                 var formValid = true;

                 if ($(this).find("input#firstName").val() == "") {
                     $(this).find("label[for='firstName']").addClass("error");
                     formValid = false;
                 } else {
                     $(this).find("label[for='firstName']").removeClass("error");
                 }

                 if ($(this).find("input#lastName").val() == "") {
                     $(this).find("label[for='lastName']").addClass("error");
                     formValid = false;
                 } else {
                     $(this).find("label[for='lastName']").removeClass("error");
                 }

                 if ($(this).find("input#verfugbarkeit").val() == "") {
                     $(this).find("label[for='verfugbarkeit']").addClass("error");
                     formValid = false;
                 } else {
                     $(this).find("label[for='verfugbarkeit']").removeClass("error");
                 }

                 if ($(this).find("input#salarwunsch").val() == "") {
                     $(this).find("label[for='salarwunsch']").addClass("error");
                     formValid = false;
                 } else {
                     $(this).find("label[for='salarwunsch']").removeClass("error");
                 }


                 if (validateEmail($(this).find("input#eMail").val())) {
                     $(this).find("label[for='eMail']").removeClass("error");
                 } else {
                     $(this).find("label[for='eMail']").addClass("error");
                     formValid = false;
                 }

                 if ($(this).find("input#phone").val().length < 10) {
                     $(this).find("label[for='phone']").addClass("error");
                     formValid = false;
                 } else {
                     $(this).find("label[for='phone']").removeClass("error");
                 }

                 if ($(this).find("input#termsAccepted").val() == "no") {
                     $(this).find("span#termsOfUse").addClass("error");
                     formValid = false;
                 } else {
                     $(this).find("span#termsOfUse").removeClass("error");
                 }

                 if ($(this).find("label[for='file1']").hasClass("fileAdded") != true) {
                    $(this).find("span.filesTitle").addClass("error");
                    formValid = false;
                 } else {
                     $(this).find("span.filesTitle").removeClass("error");
                 }

                return formValid;

             });

        /* Terms of Use */

            $applicationForm.find("span#termsOfUse").click(function() {
                if ($(this).hasClass("isClicked")) {
                    $(this).removeClass("isClicked");
                    $applicationForm.find("input#termsAccepted").val("no");
                } else {
                    $(this).addClass("isClicked");
                    $applicationForm.find("input#termsAccepted").val("yes");
                }
            });

    }

});

let setScrollFunction = function () {
    var image_height = $('.background-image').height() || 120;

    $(window).scroll(function() {
        if ($(this).scrollTop() < image_height) {
            $('.navigation').removeClass("scroll");
            $('.mobile-navigation').removeClass("scroll");
            $(".button").fadeIn();
        } else {
            $('.navigation').addClass("scroll");
            $('.mobile-navigation').addClass("scroll");
            $(".button").fadeOut();
        }
    });
};


let setGoDownButton = function () {
    $(".godown").on("click", function() {
        let y = $(window).scrollTop();
        $(".button").fadeOut();
        $("html, body").animate({ scrollTop: y + 600 }, 600);
    });
};


let setHamburger = function () {
    $("#menu").mmenu({
        // Options
    }, {
        offCanvas: {
            pageSelector: "#mainWrapper"
        }
    });

    var API = $("#menu").data( "mmenu" );

    $(".hamburger").click(function() {
        if ($(this).hasClass("is-active")) {
            API.close();
        } else {
            API.open();
        }
    });

    API.bind("open:finish", function () {
        $('.hamburger').addClass("is-active");
    });

    API.bind("close:finish", function () {
        $('.hamburger').removeClass("is-active");
    });
};


let setJobs = function () {
    $('.area-jobs .box').hover(function () {
        $(this).next('.box-on-hover').addClass('hover');

        $(this).next('.box-on-hover').mouseleave(function () {
            $(this).removeClass('hover');
        });
    });

    $('.area-jobs .box').click(function () {
        $('.box-on-hover.hover').each(function () {
            $(this).removeClass("hover");
        });

        $(this).next('.box-on-hover').addClass('hover');

        $(this).next('.box-on-hover.hover').click(function () {
            $('.box-on-hover.hover').each(function () {
                $(this).removeClass("hover");
            });
        });
    });
};


let setGallery = function () {
    $('.show-overlay').click(function() {
        var gallery_id = $(this).attr('id');
        var gallery = $('#gallery_' + gallery_id);

        $('#mainWrapper').hide();
        gallery.addClass("active");

        $(window).scrollTop(0);

        gallery.find('.single-item').slick({
            touchMove: true,
            arrows: false,
            dots: true,
            mobileFirst: true,
            speed: 500,
            fade: true,
            cssEase: 'linear'
        });

        var close = gallery.find('.close');
        var dots = gallery.find('.slick-dots');

        var top = close.position().top;
        var left = close.position().left;

        dots.css({
            "top": top - 3,
            "left": left - dots.width() * 1.3
        })
    });

    $(document).keyup(function(e) {
        if (e.keyCode == 27) {
            $('#mainWrapper').show();
            $(window).scrollTop(400);
            $('.gallery-overlay').each(function () {
                $(this).removeClass('active');
            })
        }
    });

    $('.close').click(function() {
        $('#mainWrapper').show();
        $(window).scrollTop(400);
        $('.gallery-overlay').each(function () {
            $(this).removeClass('active');
        })
    });
};



let setMap = function () {
    if ($('#map').length > 0) {
        var home = {lat: 47.170920, lng: 8.513910};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 9,
            center: home
        });

        var styles = [{
            featureType: 'water',
            elementType: 'all',
            stylers: [{hue: '#a2aeab'}, {saturation: -85}, {lightness: -13}, {visibility: 'on'}]
        }, {
            featureType: 'landscape',
            elementType: 'Man-made',
            stylers: [{hue: '#eaf0ee'}, {saturation: -38}, {lightness: 36}, {visibility: 'on'}]
        }, {
            featureType: "landscape.natural",
            elementType: "labels",
            stylers: [{"visibility": "off"}
            ]
        }, {
            featureType: 'poi',
            elementType: 'all',
            stylers: [{hue: '#cbdad5'}, {saturation: -61}, {lightness: 21}, {visibility: 'on'}]
        }, {
            featureType: 'road',
            elementType: 'all',
            stylers: [{hue: '#a2aeab'}, {saturation: -93}, {lightness: 5}, {visibility: 'on'}]
        }, {featureType: 'water', elementType: 'all', stylers: []}];

        var options = {
            mapTypeControlOptions: {mapTypeIds: ['Styled']},
            center: new google.maps.LatLng(47.1708962, 8.5117047), zoom: 10, mapTypeId: 'Styled'
        };

        var div = document.getElementById('map');
        map = new google.maps.Map(div, options);
        var styledMapType = new google.maps.StyledMapType(styles, {name: 'Styled'});
        map.mapTypes.set('Styled', styledMapType);

        var image = '/static/img/marker_small.png';
        var marker = new google.maps.Marker({
            position: home,
            map: map,
            icon: image
        });
    }
};

function validateEmail(mail) {

    var re = /^(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/;

    return re.test(mail);

}

(function($, window, document, undefined) {

    $(".inputfile").each( function() {

        var $input	 = $(this),
            $label	 = $input.next("label"),
            labelVal = $label.html();

        $input.on("change", function(e) {

            var fileName = '';

            if( this.files && this.files.length > 1 )
                fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
            else if( e.target.value )
                fileName = e.target.value.split( '\\' ).pop();

            var fileSizeInMB = this.files[0].size / 1024 / 1024;

            if (fileSizeInMB <= 5) {

                $label.removeClass("fileAdded");

                if (fileName) {
                    $label.html(fileName).addClass("fileAdded");
                } else {
                    $label.html(labelVal);
                }

            }

        });

        // Firefox bug fix
        $input
            .on( 'focus', function(){ $input.addClass( 'has-focus' ); })
            .on( 'blur', function(){ $input.removeClass( 'has-focus' ); });
    });

})(jQuery, window, document);
/*globals*/
const DEBUGMODE = false;

DEBUG(HELPERS.getBreakPoint())