File: D:/HostingSpaces/SBogers10/douven.komma.pro/wwwroot/js/site/app.js
/* ==========================================================================
Browser Handler
========================================================================== */
var BrowserHandler = {
userAgent: '',
browserInfo: '',
init: function () {
BrowserHandler.userAgent = window.navigator.userAgent;
BrowserHandler.browserInfo = BrowserHandler.getBrowserInfo();
BrowserHandler.handleIE();
BrowserHandler.handleSafari();
},
handleIE: function () {
// Detect versions below ie11
var msie = BrowserHandler.userAgent.indexOf('MSIE ');
var ielt11 = msie > 0;
// Detect ie11
var ie11 = !!navigator.userAgent.match(/Trident.*rv\:11\./);
// If Internet Explorer
if (ielt11 || ie11) {
// Default version
var version = '11';
// Way to detect version < 11
if (ielt11) version = parseInt(BrowserHandler.userAgent.substring(
msie + 5,
BrowserHandler.userAgent.indexOf(".", msie)
));
// Append classes to HTML
$('html').addClass('ie v' + version);
}
},
// Fallback for older safari version
handleSafari: function () {
if(BrowserHandler.browserInfo.name === 'Safari' && BrowserHandler.browserInfo.version <= 10) $('html').addClass('ie');
},
getBrowserInfo: function () {
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE ',version:(tem[1]||'')};
}
if(M[1]==='Chrome'){
tem=ua.match(/\bOPR\/(\d+)/)
if(tem!=null) {return {name:'Opera', version:tem[1]};}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
return {
name: M[0],
version: M[1]
};
}
};
BrowserHandler.init();
/**
* Created by Pascal on 23/11/17.
*/
/**
*
* @param {string} id - html id of form
* @param {array} required - list of required field
* @constructor
*/
function FormHandler(id, required) {
// Define form object
this.formObject = document.getElementById(id);
// Set required fields
this.requiredFields = required;
// Set default valid to true
this.valid = true;
// Validate form function
this.validate = function () {
// Reset valid to true
this.valid = true;
// Define this to self
var self = this;
var fieldToValidate = self.requiredFields.slice();
// Get all form elements
var formElements = this.formObject.querySelectorAll('input, textarea');
// Loop through the form elements
var formElementsLength = formElements.length;
for(var i = 0; i < formElementsLength; i++){
var el = formElements[i];
// Remove alert
el.classList.remove('alert');
var indexOfValidator = fieldToValidate.indexOf( el.getAttribute('name'));
// Check if it's in the required fields
if( indexOfValidator !== -1 ){
// Temporary store the value (for future checks or so ex. check if mail)
var value = el.value;
// Check if value is filled
if(value === null || value === ''){
// Else set alert and set form valid to false
el.classList.add('alert');
self.valid = false;
}
// Remove from fields to validate array
fieldToValidate.splice(indexOfValidator, 1);
}
}
// Check if all required fields are filled
if(fieldToValidate.length !== 0) {
// Else also set form valid to false
// And log because it should only happen in development
self.valid = false;
console.log('Not all required field are filled:');
console.log(fieldToValidate);
}
};
// Send form
this.send = function () {
this.formObject.submit();
}
}
/* ==========================================================================
Navigation handler
========================================================================== */
/**
* Main navigation
*/
var Header = {
// Initialize click event
init : function()
{
document.documentElement.setAttribute("data-browser", navigator.userAgent);
var last_known_scroll_position = window.scrollY;
var ticking = false;
//$('#close-navigation').bind('click',nav.close)
$('header .primary-menu .menuToggle').bind('click',function() {
$('header nav').toggleClass('visible');
$('header .menu-wrapper').toggleClass('open');
});
$('header nav .nav-bg-overlay').bind('click',function() {
$('header nav').removeClass('visible');
$('header .menu-wrapper').toggleClass('open');
});
$('header .primary-menu .menu-cat ul li').hover(function() {
$(this).addClass('active').siblings().removeClass('active');
var cat = $(this).find('span').attr('class');
$('header .primary-menu .menu-cat ul ul.sub-' + cat).addClass('open').siblings().removeClass('open');
if(cat === 'transportservice') {
$('header .primary-menu .menu-cat ul ul').removeClass('open');
}
}
// }, function() {
// $(this).removeClass('active').siblings().removeClass('active');
// $('header .primary-menu .menu-cat ul ul').removeClass('open');
// }
);
$(window).on('scroll',function(e) {
Header.last_known_scroll_position = window.pageYOffset || document.documentElement.scrollTop;
if (!Header.ticking) {
window.requestAnimationFrame(function() {
Header.changeHeader(Header.last_known_scroll_position);
Header.ticking = false;
});
Header.ticking = true;
}
});
Header.changeHeader(Header.last_known_scroll_position);
},
changeHeader : function(scroll_pos) {
if(scroll_pos > 5) {
$('header').addClass('small');
} else {
$('header').removeClass('small');
}
}
};
Header.init();
/*
* Simple isset method for this does not exist in javascript
*/
var isset = function(obj)
{
return typeof obj !== 'undefined' && obj !== null;
};
/* ==========================================================================
Image related javascript
========================================================================== */
/**
* Preload images
*/
var ImagePreloader = {
// Init preloader
init : function()
{
$('img.preload').one('load',function()
{
// Once loaded remove the preload class
// Our CSS will take care of the fade in
$(this).removeClass('preload');
})
.each(function()
{
if(this.complete) $(this).load();
});
}
};
/* ==========================================================================
Google Maps handler
-- https://developers.google.com/maps/documentation/javascript/adding-a-google-map
========================================================================== */
var MapsHandler = {
map: '',
key: 'AIzaSyCVGPUmRmQRxXvzzWu3Xyu77XebQxQ-f4Y',
location: {lat: 51.2599198, lng: 5.7291652},
styling: '',
init: function () {
// Get map by id
MapsHandler.map = document.getElementById('map');
// Check if a map is defined
if (isset(MapsHandler.map)) {
MapsHandler.setCustomStyling();
// See if google variable exists
if (typeof(google) == 'undefined' || typeof(google.maps) == 'undefined') {
// Load external script
$.getScript('https://maps.googleapis.com/maps/api/js?key=' + MapsHandler.key)
.done(function (script, textStatus) {
MapsHandler.drawMap();
});
} else {
MapsHandler.drawMap()
}
}
},
drawMap: function () {
// Create a map
var map = new google.maps.Map(MapsHandler.map, {
zoom: 13,
center: MapsHandler.location,
disableDefaultUI: true,
styles: MapsHandler.styling
});
var icon = [
'<?xml version="1.0"?>',
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 43.52 60">',
'<defs><style>.cls-1{fill:#2e80a4;}</style></defs>',
'<title>maps_marker</title>',
'<g id="Layer_2" data-name="Layer 2"><g id="Background">',
'<path class="cls-1" d="M0,21.56A22,22,0,0,1,16.27.74,21.75,21.75,0,0,1,43.16,17.65a23.71,23.71,0,0,1-1.24,12.48A66.92,66.92,0,0,1,35.1,43.61,131.49,131.49,0,0,1,23.24,59.35a1.83,1.83,0,0,1-2.62.18,34.87,34.87,0,0,1-2.57-2.87A114.16,114.16,0,0,1,5.16,37.87,43.1,43.1,0,0,1,.6,26C.31,24.55.19,23.05,0,21.56Zm10.91.12A10.92,10.92,0,1,0,21.44,10.8,10.92,10.92,0,0,0,10.91,21.68Z"/>',
'</g></g>',
'</svg>'
].join('\n');
// Add a marker
var marker = new google.maps.Marker({
position: MapsHandler.location,
map: map,
title: 'Douven Verhuur B.V.',
icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(icon), scaledSize: new google.maps.Size(60, 60) },
url: 'http://www.douvenverhuur.nl/',
animation:google.maps.Animation.DROP,
q: "douven verhuur"
});
var contentString = '<div id="content">'+
'<img src="http://douven.komma.pro/img/svg/logo_blue.svg" width="145px" height="57px" />' +
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
},
setCustomStyling: function () {
MapsHandler.styling =
[
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "#e9e9e9"
},
{
"lightness": 17
}
]
},
{
"featureType": "landscape",
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
},
{
"lightness": 20
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 17
}
]
},
{
"featureType": "road.highway",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 29
},
{
"weight": 0.2
}
]
},
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 18
}
]
},
{
"featureType": "road.local",
"elementType": "geometry",
"stylers": [
{
"color": "#ffffff"
},
{
"lightness": 16
}
]
},
{
"featureType": "poi",
"elementType": "geometry",
"stylers": [
{
"color": "#f5f5f5"
},
{
"lightness": 21
}
]
},
{
"featureType": "poi.park",
"elementType": "geometry",
"stylers": [
{
"color": "#dedede"
},
{
"lightness": 21
}
]
},
{
"elementType": "labels.text.stroke",
"stylers": [
{
"visibility": "on"
},
{
"color": "#ffffff"
},
{
"lightness": 16
}
]
},
{
"elementType": "labels.text.fill",
"stylers": [
{
"saturation": 36
},
{
"color": "#333333"
},
{
"lightness": 40
}
]
},
{
"elementType": "labels.icon",
"stylers": [
{
"visibility": "off"
}
]
},
{
"featureType": "transit",
"elementType": "geometry",
"stylers": [
{
"color": "#f2f2f2"
},
{
"lightness": 19
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.fill",
"stylers": [
{
"color": "#fefefe"
},
{
"lightness": 20
}
]
},
{
"featureType": "administrative",
"elementType": "geometry.stroke",
"stylers": [
{
"color": "#fefefe"
},
{
"lightness": 17
},
{
"weight": 1.2
}
]
}
];
}
};
MapsHandler.init();
/* ==========================================================================
NavigationHandler handler
========================================================================== */
/**
* Navigation Handler
* Primary usage for mobile NavigationHandler
* Secondary if site used a pop-up/slide-in menu
*/
var NavigationHandler = {
navElement : '',
scrolled : 0,
isActive : false,
// Initialize click event
init : function()
{
// Bind Navigation to Handler
NavigationHandler.navElement = document.getElementById('mobile-navigation');
// Bind clicks to menu button
var mobileMenuButton = document.getElementById('mobile-menu-trigger');
if(isset(mobileMenuButton)){
mobileMenuButton.addEventListener('click', function(){
NavigationHandler.open();
});
}
// Bind clicks to sticky menu button
var stickyMenuButton = document.getElementById('sticky-menu-trigger');
if(isset(stickyMenuButton)){
stickyMenuButton.addEventListener('click', function(){
NavigationHandler.open();
});
}
var mobileShade = document.getElementById('mobile-shader');
if(isset(mobileShade)){
mobileShade.addEventListener('click', function () {
NavigationHandler.close();
});
}
var mobileClose = document.getElementById('mobile-close');
if(isset(mobileClose)){
mobileClose.addEventListener('click', function () {
NavigationHandler.close();
});
}
if(isset(NavigationHandler.navElement)){
setTimeout(function () {
NavigationHandler.navElement.classList.add('allow-animation');
}, 500);
}
},
// Toggle navigation
// toggle : function()
// {
// var nav = this;
//
// if( ! $('body.NavigationHandler-is-open').length) {
// nav.open();
// }
// else
// {
// nav.close();
// }
// },
// Open Navigation
open : function()
{
NavigationHandler.scrolled = window.pageYOffset;
NavigationHandler.navElement.classList.add('active');
NavigationHandler.navElement.classList.add('shader-active');
NavigationHandler.isActive = true;
setTimeout(function(){
document.body.classList.add('preventScroll');
}, 400);
},
// Close Navigation
close : function()
{
NavigationHandler.navElement.classList.remove('active');
NavigationHandler.navElement.classList.remove('shader-active');
NavigationHandler.isActive = false;
document.body.classList.remove('preventScroll');
}
};
NavigationHandler.init();
/* ==========================================================================
Navigation handler
========================================================================== */
/**
* Main navigation
*/
var Product = {
// Initialize click event
init : function()
{
$('body.products .order-box .increase').bind('click',function(ev) {
Product.updateProductValue(1);
ev.preventDefault();
return false;
});
$('body.products .order-box .decrease').bind('click',function(ev) {
Product.updateProductValue(-1);
ev.preventDefault();
return false;
});
},
updateProductValue : function(update) {
var el = $('body.products .order-box .amount');
var amount = parseInt(el.val());
if((amount + update) > 0) {
amount += update;
el.val(amount);
}
}
};
Product.init();
/* ==========================================================================
Navigation handler
========================================================================== */
/**
* Main navigation
*/
var Reference = {
// Initialize click event
interval : null,
init : function()
{
$('body.references .refBlock .left ul.refs li span').bind('click',function(ev) {
Reference.showReference($(ev.target).parent().data('refId'));
$(ev.target).parent().addClass('active').siblings().removeClass('active');
});
this.interval = this.initInterval();
},
showReference : function(id) {
$('body.references .refBlock .right #refItem-'+id).addClass('active').siblings().removeClass('active');
$('body.references .refBlock .refItem.active .quote:first-child').addClass('active').siblings().removeClass('active');
clearInterval(this.interval);
this.interval = this.initInterval();
},
initInterval : function(){
return setInterval(function () {
var $next = $('body.references .refBlock .refItem.active .quote.active').next();
if( $next.length === 0 ) { $next = $('body.references .refBlock .refItem.active .quote').first(); }
$next.addClass('active').siblings().removeClass('active');
}, 4000);
}
};
Reference.init();
/* ==========================================================================
Resize handler
========================================================================== */
/**
* Handler the objects which are or need to be recalculated on resize
*/
var ResizeHandler = {
time: Date.now(),
timeout: null,
waitThrottle: 1000,
waitDebounce: 500,
//Initialisation
init: function () {
// Trigger start up resizes
ResizeHandler.triggerOnInit();
// Throttle Resize
window.addEventListener('resize', function () {
if ((ResizeHandler.time + ResizeHandler.waitThrottle - Date.now()) < 0) {
ResizeHandler.triggerThrottle();
ResizeHandler.time = Date.now();
}
});
// Smooth Resize
window.addEventListener('resize', function () {
ResizeHandler.triggerSmooth();
});
// Debounce Resize
window.addEventListener('resize', function () {
if(isset(ResizeHandler.timeout)) clearTimeout(ResizeHandler.timeout);
ResizeHandler.timeout = setTimeout(ResizeHandler.triggerDebounce, ResizeHandler.waitDebounce);
});
},
// Trigger on start up
// All function should be in here
triggerOnInit: function () {
// ResizeHandler.resizeWhatDoesItCostAdvantageFigure();
// console.log('Initial Resize');
},
// Trigger resize functions with throttle (preferred)
triggerThrottle: function () {
// console.log('Throttled Resize');
},
// Trigger resize on debounce
triggerDebounce: function () {
// console.log('Debounce Resize');
// ResizeHandler.resizeWhatDoesItCostAdvantageFigure();
},
// Trigger resize on the flight
triggerSmooth: function () {
// console.log('Smooth Resize');
},
// ------------------------------ CUSTOM SCROLL HANDLERS ------------------------------------
// Example function
// resizeWhatDoesItCostAdvantageFigure: function () {
// var el = document.querySelector('.advantages-own-guiding-row figure');
// if(isset(el)){
// el.style.maxHeight = 'none';
// el.style.maxHeight = el.offsetHeight + 'px';
// }
// },
};
ResizeHandler.init();
/* ==========================================================================
Scroll handler
========================================================================== */
/**
* Handler the objects which are bind on scroll events or visible in viewport
*/
var ScrollHandler = {
// Variables for debounce and throttle effects
time: Date.now(),
timeout: null,
waitThrottle: 1000,
waitDebounce: 300,
// Variables for scroll direction
lastScrollTopPosition: 0,
scrollDirectionDown: true,
scrollDirectionUp: false,
//Initialisation
init: function () {
// Trigger start on start up
ScrollHandler.triggerOnInit();
// Throttle scroll
window.addEventListener('scroll', function () {
if ((ScrollHandler.time + ScrollHandler.waitThrottle - Date.now()) < 0) {
ScrollHandler.triggerThrottle();
ScrollHandler.time = Date.now();
}
});
// Smooth scroll
window.addEventListener('scroll', function () {
ScrollHandler.triggerSmooth();
});
// Debounce scroll
window.addEventListener('scroll', function () {
if(isset(ScrollHandler.timeout)) clearTimeout(ScrollHandler.timeout);
ScrollHandler.timeout = setTimeout(ScrollHandler.triggerDebounce, ScrollHandler.waitDebounce);
});
},
// Trigger on start up
triggerOnInit: function () {
ScrollHandler.triggerElementInViewportAnimation();
},
// Trigger scroll functions with throttle (preferred)
triggerThrottle: function () {
// console.log('Throttled scroll');
ScrollHandler.triggerElementInViewportAnimation();
},
// Trigger scroll on debounce
triggerDebounce: function () {
// console.log('Debounce scroll');
},
// Trigger scroll on the flight
triggerSmooth: function () {
// console.log('Smooth scroll');
ScrollHandler.detectScrollDirection();
ScrollHandler.toggleStickyNavigation();
},
// Detect if part of a given element is visible in the viewport
// El must be a node element
detectIfElementIsPartlyInViewport: function(el)
{
if(isset(el)){
var rect = el.getBoundingClientRect();
// DOMRect { x: 8, y: 8, width: 100, height: 100, top: 8, right: 108, bottom: 108, left: 8 }
var windowHeight = (window.innerHeight || document.documentElement.clientHeight);
var windowWidth = (window.innerWidth || document.documentElement.clientWidth);
var vertInView = (rect.top <= (windowHeight)) && ((rect.top + rect.height) >= 0);
var horInView = (rect.left <= windowWidth) && ((rect.left + rect.width) >= 0);
return (vertInView && horInView);
}
},
// Detect if a given element is fully visible in the viewport
// El must be a node element
detectIfElementIsFullyInViewport: function(el)
{
if(isset(el)){
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.bottom <= window.innerHeight
);
}
},
detectScrollDirection: function () {
var scrollTopPosition = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
if (scrollTopPosition >= ScrollHandler.lastScrollTopPosition){
ScrollHandler.scrollDirectionDown = true;
ScrollHandler.scrollDirectionUp = false;
} else {
ScrollHandler.scrollDirectionDown = false;
ScrollHandler.scrollDirectionUp = true;
}
ScrollHandler.lastScrollTopPosition = scrollTopPosition;
},
// Trigger animation on elements that have 'element-in-viewport' and that are in the viewport
// These animation can only be triggered once, if you want more then that you should write an specific function for this
triggerElementInViewportAnimation: function () {
var elements = document.querySelectorAll('.element-in-viewport');
var elementsLength = elements.length;
for(var e = 0; e < elementsLength; e++){
var element = elements[e];
if(ScrollHandler.detectIfElementIsPartlyInViewport(element)){
element.classList.remove('element-in-viewport');
}
}
},
// ------------------------------ CUSTOM SCROLL HANDLERS ------------------------------------
// Hide or show sticky navigation when header isn't visible
toggleStickyNavigation: function () {
var mainNavigation = document.querySelector('body >header');
var stickyNavigation = document.getElementById('sticky-navigation');
if(isset(stickyNavigation) && isset(mainNavigation)){
// Show sticky navigation
if(!ScrollHandler.detectIfElementIsFullyInViewport(mainNavigation) && ScrollHandler.scrollDirectionUp){
stickyNavigation.classList.add('active');
}
// Hide sticky navigation
if(ScrollHandler.scrollDirectionDown || ScrollHandler.detectIfElementIsPartlyInViewport(mainNavigation)){
stickyNavigation.classList.remove('active');
}
}
},
};
ScrollHandler.init();
/* ==========================================================================
Scroll To Click handler
========================================================================== */
var ScrollToHandler = {
init : function(){
$('.scroll-to-target').bind('click',function()
{
ScrollToHandler.scrollToTarget($(this));
return false;
});
},
/**
* Handles click on the mouse with the arrow
*
* @param el
*/
scrollToTarget : function(el, offset, time){
offset = isset(offset) ? offset : 60;
time = isset(time) ? time : 800;
var scrollTo = el.prop('href');
scrollTo = scrollTo.substr(scrollTo.indexOf('#')+1);
var body = $('html,body');
body.animate({
scrollTop: $('#'+scrollTo).offset().top - offset
}, time);
body.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
body.stop();
});
}
};
ScrollToHandler.init();
/**
* Created by Pascal on 06/12/17.
*/
/*
HTML Example
<script src="/js/slider.js"></script>
<script>
var imageSliderSetting = new SliderSetting({
sliderId: 'image-slider',
slideQuery: '#image-slider .placeholder figure',
slideContentQuery: 'span',
definedPreviousNext: true,
navigationButtons: '#image-slider .placeholder .controllers .nav-item',
dots: '#image-slider .placeholder .controllers .dots',
autoSlider: true,
sliderInterval: 4000
});
imageSliderSetting = imageSliderSetting.prepareParameters();
var imageSlider = new Slider(imageSliderSetting);
</script>
*/
function SliderSetting(settingsObject) {
var self = this;
this.sliderId = '';
this.definedPreviousNext = true;
this.autoSlider = false;
this.sliderInterval = 4000;
this.navigationButtons = '';
this.dots = '';
this.thumbs = '';
this.slideQuery = '';
this.slideContentQuery = '';
this.setSliderId = function ($string) {
this.sliderId = $string;
return this;
};
this.setDefinedPreviousNext = function ($boolean) {
this.definedPreviousNext = $boolean;
return this;
};
this.setAutoSlider = function ($boolean) {
this.autoSlider = $boolean;
return this;
};
this.setSliderInterval = function ($integer) {
this.sliderInterval = $integer;
return this;
};
this.setSlideQuery = function ($string) {
this.slideQuery = $string;
return this;
};
this.setNavigationButtons = function ($string) {
this.navigationButtons = $string;
return this;
};
this.setDots = function ($string) {
this.dots = $string;
return this;
};
this.setThumbs = function ($string) {
this.thumbs = $string;
return this;
};
this.getSliderId = function () {
return this.sliderId;
};
this.getDefinedPreviousNext = function () {
return this.definedPreviousNext;
};
this.getAutoSlider = function () {
return this.autoSlider;
};
this.getSliderInterval = function () {
return this.sliderInterval;
};
this.getSlideQuery = function () {
return this.slideQuery;
};
this.getNavigationButtons = function () {
return this.navigationButtons;
};
this.getDots = function () {
return this.dots;
};
this.getThumbs = function () {
return this.thumbs;
};
// Invert setters to getters
this.prepareParameters = function () {
return {
sliderId: self.getSliderId(),
definedPreviousNext: self.getDefinedPreviousNext(),
autoSlider: self.getAutoSlider(),
sliderInterval: self.getSliderInterval(),
navigationButtons: self.getNavigationButtons(),
dots: self.getDots(),
thumbs: self.getThumbs(),
slideQuery: self.getSlideQuery()
}
};
// Mass assign settings
this.fill = function () {
// Object.keys(settingsObject).forEach(function (key) {
// self[key] = settingsObject[key];
// });
var settingsObjectKeys = Object.keys(settingsObject);
var settingsObjectLength = settingsObjectKeys.length;
for (var i = 0; i < settingsObjectLength; i++) {
var key = settingsObjectKeys[i];
self[key] = settingsObject[key];
}
};
this.fill();
return {
sliderId: self.setSliderId,
definedPreviousNext: self.setDefinedPreviousNext,
autoSlider: self.setAutoSlider,
sliderInterval: self.setSliderInterval,
navigationButtons: self.setNavigationButtons,
dots: self.setDots,
thumbs: self.setThumbs,
slideQuery: self.setSlideQuery,
prepareParameters: self.prepareParameters
};
}
function Slider(settings) {
//Define Slider object
var self = this;
this.sliderObject = '';
//SlideParameters
this.activeSlideId = 0;
this.previousSlideId = 0;
this.nextSlideId = 0;
this.availableSlides = 1;
this.slides = [];
this.autoSliderInterval = null;
this.settings = {};
this.init = function () {
//Append settings to self
this.settings = settings;
//Assign needed elements and calculations
this.sliderObject = document.getElementById(this.settings.sliderId);
this.slides = document.querySelectorAll(this.settings.slideQuery);
this.availableSlides = this.slides.length;
this.activeSlideId = 0;
//Define previous and next if we want to use those
if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide();
// Set active slide (and possible previous and next classes)
this.setSlide();
// Swipe interaction
$(this.sliderObject).swipe({
swipeLeft: function () {
self.resetAutoSlider();
self.nextSlide();
self.setSlide();
},
swipeRight: function () {
self.resetAutoSlider();
self.previousSlide();
self.setSlide();
}
});
if (this.settings.navigationButtons != '') {
// Click interaction
var navigationButtons = document.querySelectorAll(this.settings.navigationButtons);
var navigationButtonsLength = navigationButtons.length;
for (var i = 0; i < navigationButtonsLength; i++) {
var navigationButton = navigationButtons[i];
navigationButton.addEventListener('click', function () {
self.clickNavigationButton(this);
});
}
}
if (this.settings.dots != '') {
// Click interaction
var dots = document.querySelectorAll(this.settings.dots);
var dotsLength = dots.length;
for (var i = 0; i < dotsLength; i++) {
var dot = dots[i];
dot.addEventListener('click', function () {
self.clickDot(this);
});
}
}
if (this.settings.thumbs != '') {
// Click interaction
var thumbs = document.querySelectorAll(this.settings.thumbs);
var thumbsLength = thumbs.length;
for (var i = 0; i < thumbsLength; i++) {
var thumb = thumbs[i];
thumb.addEventListener('click', function () {
self.clickThumb(this);
});
}
}
// Define resize
$(window).resize(
//$.throttle(20, self.resizeSlider)
self.resizeSlider()
);
self.resizeSlider();
self.autoSlider();
setTimeout(self.resizeSlider(), 500);
};
this.autoSlider = function () {
if (this.autoSliderInterval !== null) clearInterval(this.autoSliderInterval);
if (this.settings.autoSlider && Number.isInteger(this.settings.sliderInterval)) {
this.autoSliderInterval = setInterval(function () {
self.nextSlide();
self.setSlide();
}, this.settings.sliderInterval
);
}
};
this.resetAutoSlider = self.autoSlider;
this.nextSlide = function () {
this.activeSlideId++;
if (this.activeSlideId >= this.availableSlides) this.activeSlideId = 0;
if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide();
};
this.previousSlide = function () {
this.activeSlideId--;
if (this.activeSlideId < 0) this.activeSlideId = this.availableSlides - 1;
if (self.settings.definedPreviousNext) this.setPreviousAndNextSlide();
};
this.setPreviousAndNextSlide = function () {
this.nextSlideId = this.activeSlideId + 1;
if (this.nextSlideId >= this.availableSlides) this.nextSlideId = 0;
this.previousSlideId = this.activeSlideId - 1;
if (this.previousSlideId < 0) this.previousSlideId = this.availableSlides - 1;
};
this.setSlide = function () {
// Loop through the form elements
var slidesLength = self.slides.length;
for (var i = 0; i < slidesLength; i++) {
var slide = self.slides[i];
// Convert dataset attribute to desired type
var slideOrder = parseInt(slide.dataset.order);
// Remove and set active for all slides
if (slideOrder !== self.activeSlideId) slide.classList.remove('active');
else slide.classList.add('active');
// If we use the previous and next, also set those classes
if (self.settings.definedPreviousNext) {
if (slideOrder !== self.previousSlideId) slide.classList.remove('previous');
else slide.classList.add('previous');
if (slideOrder !== self.nextSlideId) slide.classList.remove('next');
else slide.classList.add('next');
}
}
if (self.settings.dots != '') {
self.setActiveDot();
}
if (self.settings.thumbs != '') {
self.setActiveThumb();
}
};
this.clickNavigationButton = function (navButton) {
self.activeSlideId = parseInt(navButton.dataset.order);
if (self.settings.definedPreviousNext) self.setPreviousAndNextSlide();
self.setSlide();
var next = document.querySelector(self.settings.navigationButtons + '.next');
var previous = document.querySelector(self.settings.navigationButtons + '.previous');
next.dataset.order = self.nextSlideId;
previous.dataset.order = self.previousSlideId;
self.resetAutoSlider();
// next.querySelector('p').innerHTML = self.slides[self.nextSlideId].dataset.name;
// previous.querySelector('p').innerHTML = self.slides[self.previousSlideId].dataset.name;
};
this.clickDot = function (clickedDot) {
self.activeSlideId = parseInt(clickedDot.dataset.order);
self.setSlide();
self.resetAutoSlider();
};
this.setActiveDot = function () {
var dots = document.querySelectorAll(this.settings.dots);
var dotsLength = dots.length;
for (var i = 0; i < dotsLength; i++) {
var dot = dots[i];
dotOrder = parseInt(dot.dataset.order);
if (dotOrder !== self.activeSlideId) dot.classList.remove('active');
else dot.classList.add('active');
}
};
this.clickThumb = function (clickedThumb) {
self.activeSlideId = parseInt(clickedThumb.dataset.order);
self.setSlide();
self.resetAutoSlider();
};
this.setActiveThumb = function () {
var thumbs = document.querySelectorAll(this.settings.thumbs);
var thumbsLength = thumbs.length;
var offsetX = -thumbs[0].clientWidth;
for (var i = 0; i < thumbsLength; i++) {
var thumb = thumbs[i];
thumbOrder = parseInt(thumb.dataset.order);
if (thumbOrder !== self.activeSlideId) {
thumb.classList.remove('active');
} else {
thumb.classList.add('active');
var newScrollLeft = offsetX + thumb.offsetLeft;
//thumb.parentNode.scrollLeft = newScrollLeft;
this.scrollToThumb(thumb.parentNode, newScrollLeft, 500, 5);
}
}
};
this.scrollToThumb = function (parent, position, duration, steps) {
//clearInterval(scrollInterval);
var startPosition = parent.scrollLeft;
var newPosition = position;
var distance = (newPosition - startPosition); // negative values are intentional
var startTime = null;
if (!distance) return;
// Bootstrap our animation - it will get called right before next frame shall be rendered.
window.requestAnimationFrame(function step(timestamp) {
if (!startTime) startTime = timestamp;
// Elapsed miliseconds since start of scrolling.
var time = timestamp - startTime;
// Get percent of completion in range [0, 1].
var percent = Math.min(time / duration, 1);
parent.scrollLeft = startPosition + (distance * percent);
// Proceed with animation as long as we wanted it to.
if (time < duration) {
window.requestAnimationFrame(step)
}
})
};
this.resizeSlider = function () {
// console.log('hier');
};
// this.init();
}
/* ==========================================================================
Navigation handler
========================================================================== */
/**
* Main navigation
*/
var Transport = {
// Initialize click event
init : function()
{
$('body.transportservice .transBlock .icon-holder .icon').bind('click',function(ev) {
Transport.changeTransportBlock(ev.target);
});
},
changeTransportBlock : function(element) {
if(!$(element).hasClass('active')) {
var className = $(element).attr('class');
$(element).addClass('active').siblings().removeClass('active');
var iconBlock = className.split(' ')[1];
$('body.transportservice .transBlock .bottom .service-block').removeClass('active');
console.log($('.service-block '+iconBlock));
$('body.transportservice .transBlock .bottom .'+iconBlock).addClass('active');
}
}
};
Transport.init();
/* ==========================================================================
Youtube handler
========================================================================== */
var YoutubeHandler = {
elementId : '',
youtubeId : '',
/**
*
*/
init : function()
{
YoutubeHandler.elementId = 'ytplayer';
// YoutubeHandler.youtubeId = 'L1SzPfYkeF4'; //Komma sfeerimpressie video
YoutubeHandler.youtubeId = 'X-dMOvEOQiM'; //Blue motion video
YoutubeHandler.playVideo()
},
/**
* Check if external script is loaded
*
*/
playVideo: function() {
// See if YT variable exists
if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') {
// Setup API ready function
window.onYouTubePlayerAPIReady = function() {
YoutubeHandler.loadPlayer();
};
// Load external script
$.getScript('https://www.youtube.com/iframe_api');
// If YT already exists load player
} else {
YoutubeHandler.loadPlayer();
}
},
/**
* Load Youtube player with parameters
*
*/
loadPlayer: function() {
// Load player
window.player = new YT.Player(YoutubeHandler.elementId,{
height: 200,
width: 200,
videoId: YoutubeHandler.youtubeId,
playerVars: {
modestbranding: 0,
showinfo: 0,
rel: 0,
controls: 0,
disablekb: 1
},
events: {
'onReady': YoutubeHandler.onReady,
'onStateChange': YoutubeHandler.onStateChange
}
});
},
/**
* When player is ready to play
*/
onReady : function() {
// Show video
setTimeout(function(){ $('#' + YoutubeHandler.elementId).stop().animate({ opacity: 1 },1000) },800);
// If not on tablet or mobile, play on high quality
window.player.mute();
window.player.playVideo();
window.player.setPlaybackQuality('hd1080');
},
/**
* Listener for Youtube state change
*
* @param state
*/
onStateChange : function(state) {
// Loop video
if (state.data === YT.PlayerState.ENDED ) {
window.player.playVideo();
}
}
};