
APP.namespace = function(namespaceString) {
    "use strict";

    var parts = namespaceString.split('.'),
        parent = window,
        currentPart = '';

    for (var i = 0, length = parts.length; i < length; i++) {
        currentPart = parts[i];
        parent[currentPart] = parent[currentPart] || {};
        parent = parent[currentPart];
    }

    return parent;
};;

APP.trace = function (message) {
    "use strict";

    if (APP.Core.DeviceManager.isIE() && APP.Core.DeviceManager.isIE() <= 9) {
        return;
    }

    if (APP.Configuration.debug == true) {
        if ((typeof console !== 'undefined') && (typeof console.log === 'function')) {
            console.log(message);
        } else if (typeof Firebug !== 'undefined') {
            Firebug.console.log(message);
        } else {
            // keep silence in IE
            // alert(message);
        }
    }
};
;

APP.namespace('APP.Block');

APP.Block.Column = (function($, window) {
    "use strict";

    var app,
        config = {
            delay : 700,
            elementClass : '.block.block-column',
            animateClass : 'block-animate'
        };

    app = {
        methods : {
            init : function () {
                if (!$(config.elementClass).length) {
                    return;
                }

                setTimeout(function(){
                    app.methods.render();
                }, config.delay);
            },
            render : function () {
                $('.column').each(function(){
                    var elObj = $(this),
                        index = elObj.index(),
                        blockObj = elObj.find(config.elementClass),
                        intervalValue;

                    if (!blockObj.length) {
                        return;
                    }

                    intervalValue = index * 200;

                    setTimeout(function () {
                        blockObj.addClass(config.animateClass);
                    }, intervalValue);
                });
            }
        }
    };

    return {
        init : function () {
            app.methods.init()
        }
    }

}($, window));;

APP.namespace('APP.Block');

APP.Block.EqualHeight = (function($, window) {
    "use strict";

    var app,
        block = $('.equal-height'),
        domWindow = $(window);

    app = {
        events : {
            onResize : function () {
                app.methods.build();
            }
        },
        methods : {
            isForce : function () {
                var isForce = false;

                block.each(function(){
                    var f = $(this).data('equal-height-force');

                    if (typeof f !== 'undefined' && f) {
                        isForce = true;
                    }
                });

                return isForce;
            },
            update : function() {
                block = $('.equal-height');

                if (!block.length || (APP.Core.DeviceManager.hasFlex() && !app.methods.isForce()) ) {
                    return;
                }

                if (APP.Core.DeviceManager.hasFlex() && app.methods.isForce()) {
                    block = $('.equal-height[data-equal-height-force]');
                }

                if (APP.Core.DeviceManager.hasFlex() && app.methods.isForce()) {
                    block = $('.equal-height[data-equal-height-force]');
                }

                app.methods.build();
            },
            init : function() {
                if (!block.length || (APP.Core.DeviceManager.hasFlex() && !app.methods.isForce()) ) {
                    return;
                }

                APP.trace('Log: [block|equal-height] Instantiate equal height block...');

                //wait until window load...
                domWindow.on('load', function() {
                    app.methods.build();
                    app.methods.attach();
                });
            },
            reset : function () {
                block.css({
                    'height' : 'auto'
                });
            },
            build : function () {
                //reset equal height properties...
                app.methods.reset();

                //reset relative bottom properties...
                APP.Block.RelativeBottom.reset();

                //calculate and set height bottom element...
                APP.Block.RelativeBottom.setHeight();

                //iterate rows and calculate
                // equal height elements...
                app.methods.createBlocks();

                //Check for alignment
                APP.Plugin.Align.update();

                //set relative bottom position
                APP.Block.RelativeBottom.setPosition();
            },
            createBlocks : function () {
                $('.row').each(function(e) {
                    var blocks,
                        height;

                    blocks = $(this).find(block);
                    height = 0;

                    blocks.each(function(e) {
                        var element,
                            limit,
                            width;

                        // block element
                        element = $(this);

                        // look for limit
                        limit = element.data('equal-height-limit');
                        width = $('.container').width();

                        if(!limit || width >= limit) {
                            var elementH = element.outerHeight();

                            if (elementH > height) {
                                height = elementH;
                            }
                        }
                    });

                    if (height > 0) {
                        blocks.height(height);
                    }
                });
            },
            attach : function () {
                domWindow.unbind('resize',app.events.onResize).on('resize', app.events.onResize);
            }
        }
    };

    return {
        init : function () {
            app.methods.init();
        },
        update : function () {
            app.methods.update();
        }
    };

}($, window));;

APP.namespace('APP.Block');

APP.Block.Featured = (function(window, document) {
    "use strict";

    var app,
        jqObj;

    app = {
        events : {
            eventHandler : function (evt) {
                evt.preventDefault();

                var type = evt.type,
                    el = $(this);

                if (type !== 'click') {
                    switch (type) {
                        case 'mouseenter':
                            el.addClass('block-hover');
                            break;
                        case 'mouseleave':
                            el.removeClass('block-hover');
                            break;
                    }

                    return;
                }

                var link = el.find('a:eq(0)');

                if (link.length) {
                    window.location.href = link.attr('href');
                }
            }
        },
        methods : {
            init : function () {
                jqObj = $('.block.featured-block');

                if (!jqObj.length) {
                    return;
                }

                app.methods.bind();
            },
            bind : function () {
                jqObj.off('mouseenter mouseleave click', app.events.eventHandler)
                    .on('mouseenter mouseleave click', app.events.eventHandler);
            }
        }
    };

    return {
        init : app.methods.init
    }

}(window, document));;

APP.namespace('APP.Block');

APP.Block.RelativeBottom = (function($) {
    "use strict";

    var app,
        block = $('.relative-bottom');

    app = {
        methods : {
            reset : function () {
                if (!block.length) {
                    return;
                }

                block.css({
                    'padding-bottom' : 0
                });

                block.find('.bottom').removeAttr('data-position').css({
                    'height'    : 'auto',
                    'position'  : 'static',
                    'bottom'    : 'auto'
                });
            },
            setHeight : function () {
                if (!block.length) {
                    return;
                }

                $('.row').each(function(e) {
                    var blocks,
                        height;

                    blocks = $(this).find(block);
                    height = 0;

                    blocks.each(function(e) {
                        var element,
                            limit,
                            width,
                            elementH;

                        // block element
                        element = $(this);

                        // look for limit
                        limit = element.data('equal-height-limit');
                        width = $('.container').width();

                        if(limit && width >= limit) {
                            elementH = element.find('.bottom').outerHeight();

                            if (elementH > height) {
                                height = elementH;
                            }
                        }
                    });

                    if (height > 0) {
                        blocks
                            .children('.bottom')
                            .addClass('js-active')
                            .attr('data-position','absolute').css({
                            'height' : height + 'px'
                        });
                    }
                });
            },
            setPosition : function() {
                if (!block.length) {
                    return;
                }

                block.find('.bottom[data-position="absolute"]').css({
                    'position'  : 'absolute',
                    'bottom'    : '0px'
                });
            }
        }
    };

    return {
        reset : function () {
            app.methods.reset();
        },
        setHeight : function () {
            app.methods.setHeight();
        },
        setPosition : function () {
            app.methods.setPosition();
        }
    };

}($));;

APP.namespace('APP.Components');

APP.Components.BSPopOver = (function ($) {
    "use strict";

  var app, jqSelector;

    app = {
        config : {
            trigger: 'hover',
            placement: 'bottom'
        },
        methods: {
            isTouchDevice : function () {
                return 'ontouchstart' in window        // works on most browsers 
                || navigator.maxTouchPoints;       // works on IE10/11 and Surface
            },
            init : function (options) {
                $.extend(app.config, options);

                jqSelector = $('[data-toggle="popover"]');

                if (!jqSelector.length || APP.Components.BSPopOver.active) {
                    return;
                }

                APP.Components.BSPopOver.active = true;

                // set trigger to click for touch devices
                if (app.methods.isTouchDevice()) {
                    app.config.trigger = 'click';
                }

                jqSelector.popover(app.config);
            },
          destroy: function () {
              if (jqSelector) {
                jqSelector.popover('destroy');
              }
            }
        }
    };

    return {
        active: false,
        init : app.methods.init,
        destroy : app.methods.destroy
    };

}(jQuery));;

APP.namespace('APP.Components');

APP.Components.Chat = (function ($) {

  var app,
    buttons,
    isDebug = false,
    timer = null,
    timerConfig = {
      interval: 15000,
      startOn: {
        hour: 15,
        minutes: 45
      },
      hideActiveChatAfter: {
        hour: 16,
        minutes: 15
      }
    },
    config = {
      roomNumber: '0fd30e07f04208280860',
      runOptions: {
        country: "nl",
        interfaceTexts: {
          desc: 'Eigen Haard - Chat',
          buttonLabel: 'Klik hier om te chatten',
          inviteNotification: 'Waarmee kunnen we u helpen?',
          infoText: '&#201;&#233;n van onze chatters komt zo bij je.',
          optionsDownloadText: 'Download gesprek',
          closeAlertTitle: 'Wil je het gesprek be&#235;indigen?',
          offlineNotification: '<p><b>Er is nu niemand om mee te chatten.</b></p><p>Op werkdagen tussen 9.00 en 16.00 uur kunt u met ons chatten. Stel uw vraag <a href="http://www.eigenhaard.nl/contactformulier"</a>via het contactformulier</a> of dien hier een <a href="http://www.eigenhaard.nl/reparatieverzoek">een reparatieverzoek</a> in.</p>',
          closeAlertBody: ''
        },
        hideCloseBtn: true
      },
      weekdays: [
        ["Sunday"],
        ["Monday", 9.00, 12.00],    ["Monday", 13.00, 16.00],
        ["Tuesday", 9.00, 12.00],   ["Tuesday", 13.00, 16.00],
        ["Wednesday", 9.00, 12.00], ["Wednesday", 13.00, 16.00],
        ["Thursday", 9.00, 12.00],  ["Thursday", 13.00, 16.00],
        ["Friday", 9.00, 12.00],    ["Friday", 13.00, 16.00],
        ["Saturday"]
      ],
      interface: {
        showAgentName: false,
        hideChatAfterBusinessHours: true,
        closeAlert: true
      },
      fcmConfig: {
        enabled: true,
        serviceWorkerLocation: '/assets/vendor/parley/firebase-messaging-sw.js'
      }
    };

  app = {
    events: {
      onButtonClick: function (evt) {
        evt.preventDefault();
        app.methods.toggleChat();
      }
    },
    methods: {
      parleyIsActive: function () {
        return typeof window.parleySettings !== 'undefined';
      },
      parleyIsLoaded: function () {
        return typeof window.parleyConstructor === 'function';
      },
      parleyIsOffline: function () {
        return typeof window.parleySettings.isOffline !== 'undefined' && window.parleySettings.isOffline;
      },
      init: function () {

        $.getScript("/assets/vendor/parley/app.js", function ()
        {
          app.methods.create();
        });

        APP.trace('Log: [components|chat] Instantiate component...');
      },
      create: function () {
        // Interval to make sure that all 3rd 
        //  party files are loaded...
        var intervalId = setInterval(function () {
          if (!app.methods.parleyIsLoaded()) return;

          app.methods.enableChat();

          clearInterval(intervalId);
        }, 500);
      },
      enableChat: function () {
        for (var i in buttons) {
          if (buttons.hasOwnProperty(i)) {
            buttons[i].show();
          }
        }

        // Create instance
        window.parleyConstructor(config);

        // app.methods.resetPreviousChat(); disabled for now!
        app.methods.createTimer();
        app.methods.disableChatWhenOffline();
        app.methods.attach();
      },
      createTimer: function () {
        if (app.methods.parleyIsOffline()) return;

        // Get the current date
        var currentDate = new Date();

        // Start the timer from this date
        var timeStartDate = new Date();

        // Set the start time
        timeStartDate.setHours(timerConfig.startOn.hour);
        timeStartDate.setMinutes(timerConfig.startOn.minutes);
        timeStartDate.setSeconds(0);

        // Start timer
        if (currentDate >= timeStartDate) {
          timer = setInterval(app.methods.timer, timerConfig.interval);
        }
      },
      destroyTimer: function () {
        clearInterval(timer);
      },
      timer: function () {
        var currentDate = new Date();
        var closingDate = new Date();

        // Set the hideActiveChatAfter time values
        closingDate.setHours(timerConfig.hideActiveChatAfter.hour);
        closingDate.setMinutes(timerConfig.hideActiveChatAfter.minutes);
        closingDate.setSeconds(0);

        // Log values
        if (isDebug) {
          console.log(currentDate, closingDate)
        }

        // Hide any active chat after closing time
        if (currentDate >= closingDate) {          
          app.methods.disableChat();
          app.methods.destroyTimer();
        }
      },
      disableChat: function () {
        window.parleySettings.isOffline = true;

        $('#parleychat-container').addClass('parleychat-in-offline');
      },
      isLessThanOneHourAgo: function(date) {
        const HOUR = 1000 * 60 * 60;
        const anHourAgo = Date.now() - HOUR;
    
        return date > anHourAgo;
      },
      resetPreviousChat: function () {
        var unixTimestamp = window.localStorage.getItem('parleychat_showMessengerDate');        
        var prevDate = new Date(unixTimestamp * 1000);

        // Delete all chat data, because it's only possible 
        //  to reactive chat when previous chat is less than one hour!
        if (!app.methods.isLessThanOneHourAgo(prevDate)) {
          window.parleySettings.deleteAllDataFromStorage();
        }
      },
      disableChatWhenOffline: function() {
        if (typeof window.parleySettings.isOffline === 'undefined' || !window.parleySettings.isOffline) return;

        $('#plugin-constructor-view-off-line-inner').remove();
      },
      toggleChat: function () {
        if (!app.methods.parleyIsActive()) return;
        window.parleySettings.showInviteNotification();
      },
      attach: function () {

        buttons = [
          $('[data-component="chat"]'),
          $('.btn.btn-chat'),
          $('ul.link-list a.icon-chat'),
          $('#parleychat-launcher .buttonLabel')
        ];

        for (var i in buttons) {
          if (buttons.hasOwnProperty(i)) {
            // Fetching selector because jQuery on/off event binding not working!
            var el = buttons[i].get(0) || undefined;
            if (el) {
              el.removeEventListener('click', app.events.onButtonClick, false);
              el.addEventListener('click', app.events.onButtonClick, false);
            }
          }
        }       
      }
    }
  };

  return {
    init: app.methods.init
  };

}($));
;

APP.namespace('APP.Components');

APP.Components.Click = (function ($) {

  var app,
    jqObj,
    processed = false;

  app = {
    events: {
      onClick: function (evt) {
        var el = $(this),
          text = el.text(),
          href = el.attr('href'),
          track = el.data('track') || 'Outbound link',
          target = el.attr('target');

        if (text !== '') {
          text = text.replace(/\s+/g, " "); // remove double spaces
        }

        var status = APP.Core.Tracking.set({
          trackingType: 'event',
          eventCategory: 'tracked link',
          eventAction: 'click',
          eventLabel: track + ': ' + text + ' (' + href + ')',
          hitCallback: function () {
            if (target !== '_blank') {
              window.location.href = href;
            }
          },
          hitCallbackFail: function () {
            if (target !== '_blank') {
              window.location.href = href;
            }
          }
        });

        // when target == blank there's no need to stop the event
        // as it will be opened in a new tab and the sending of the
        // event will always complete. now there's no need to use
        // window.open that will be blocked by most popup blockers
        if (target != '_blank' && status) {
          evt.preventDefault();
        }
      }
    },
    methods: {
      init: function () {

        jqObj = $('[data-track], a[href^="https://eigenhaard.easycruit.com"]');
        if (!jqObj.length) {
          return;
        }

        APP.trace('Log: [components|click] Instantiate component...');

        // attach event...
        app.methods.attach();
      },
      attach: function () {
        $('a[data-track]')
          .off('click', app.events.onClick)
          .on('click', app.events.onClick);

        $('a[href^="https://eigenhaard.easycruit.com"]')
          .off('click', app.events.onClick)
          .on('click', app.events.onClick);
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    }
  };

}($));;

APP.namespace('APP.Components');

APP.Components.BackButton = (function($){

  var app, jqObj;

    app = {
        events : {
            onClick: function (evt) {
                evt.preventDefault();
                window.history.back();
            }
        },
        methods : {
            init : function () {

                jqObj = $('.back-button');
                if (!jqObj.length) {
                    return;
                }

                APP.trace('Log: [components|back-button] Instantiate component...');

                // attach event...
                app.methods.attach();
            },
            attach : function () {
                jqObj
                    .off('click', app.events.onClick)
                    .on('click', app.events.onClick);
            }
        }
    };

    return {
        init : function () {
            app.methods.init();
        }
    };

}($));
;

/**
 *
 * APP.Components.ConfirmButton
 *
 * Creates a modal to make sure an user confirms his action,
 *  eg. form submit or button / link click...
 *
 * Additional note:
 *  1. Configuration stored in window.GLOBAL, hard-coded in template;
 *  2. Modal can be created based on a input[type="radio"] list;
 *
 * @author  K van den Broek     <k.vandenbroek@uselab.com>
 * @return  init                function to instantiate the component...
 *
 * --------------------------------------------------------------------------------------------
 *
 * Example 1) Create modal based on button or href link:
 *  <button class="btn btn-default" data-confirm-button="keuze1">keuze1</button>
 *  <a href="#" class="btn btn-default" data-confirm-button="keuze1" data-confirm-action="redirect">keuze1</button>
 *
 *  <script>
 *      window.GLOBAL.ConfirmButton = {
 *          keuze1 : {
 *              modal : 'modal-alert',
 *              title : 'Keuze 1',
 *              text : 'Keuze 1 tekst',
 *              button : {
 *                  cancel : 'Annuleren',
 *                  confirm : 'Opslaan'
 *              }
 *          }
 *      }
 *  </script>
 *
 * Example 2) Create modal based on "checked" radio option:
 *  <input type="radio" id="keuze1" name="keuze" value="0">
 *  <input type="radio" id="keuze2" name="keuze" value="0">
 *  <input type="submit" data-confirm-button="radio_list" value="Versturen">
 *
 *  <script>
 *      window.GLOBAL.ConfirmButton = {
 *          radio_list : {
 *              keuze1 : {
 *                  modal : 'modal-alert',
 *                  title : 'Keuze 1',
 *                  text : 'Keuze 1 tekst',
 *                  button : {
 *                      cancel : 'Annuleren',
 *                      confirm : 'Opslaan'
 *                  }
 *              },
 *              keuze2 : {
 *                  modal : 'modal-alert',
 *                  title : 'Keuze 2',
 *                  text : 'Keuze 2 tekst',
 *                  button : {
 *                      cancel : 'Annuleren',
 *                      confirm : 'Opslaan'
 *                  }
 *              }
 *          }
 *      }
 * </script>
 *
 */

APP.namespace('APP.Components');

APP.Components.ConfirmButton = (function($){

    var app,
        modalOptions,
		button;

    app = {
        config : {},
		events : {
			onClick : function (evt) {
                if (!app.methods.isValid()) {
                    return;
                }

                var el = $(this);

                app.config.button = {};
                app.config.button.action = el.data('confirm-action') || 'submit';
                app.config.button.type = el.data('confirm-button');
                app.config.button.self = el;
               
                if (app.config.button.action === 'redirect') {
                    app.config.button.href = el.attr('href') || '';
                }

                modalOptions = app.methods.getModalOptions();

                if (typeof modalOptions === 'object') {
                    app.methods.createDialog();
                    evt.preventDefault();
                }
			}
		},
        methods : {
		    getConfig : function () {
                try {
                    return window.GLOBAL.ConfirmButton;
                }
                catch(err) {
                    return {};
                }
            },
            init : function () {
                button = $('[data-confirm-button]');

                if (!button.length) {
                    return;
                }

                APP.trace('Log: [components.confirm-button] Instantiate component...');
				
				app.methods.create();
            },
            getModalOptions : function () {
                var type = app.config.button.type,
                    data = (typeof type !== 'undefined' && typeof app.config[type] !== 'undefined' ? app.config[type] : undefined),
                    modalData = undefined;

                if (type === 'radio_list') {
                    $.each(data, function(k){
                        var selectorId = '#' + k,
                            jqSelector = $(selectorId),
                            isChecked = jqSelector.prop('checked');

                        if (isChecked && typeof data[k] !== 'undefined') {
                            modalData = data[k];
                        }
                    });
                } else {
                    modalData = data;
                }

                return modalData;
            },
            isValid : function () {
                return $('.error-message').is(':visible') ? false : true;
            },
            create : function () {
                $.extend(app.config, app.methods.getConfig());

                if ($.isEmptyObject(app.config)) {
                    APP.trace('Error: [components.confirm-button] Configuration not specified...');
                    return;
                }

                app.methods.attach();
            },
            createDialog : function () {
                APP.Components.Modal.create({
                    data : {
                        type : modalOptions.modal,
                        title : modalOptions.title,
                        text : modalOptions.text,
                        animation : true,
                        button : [
                            {
                                text : modalOptions.button.confirm,
                                callback : 'confirm',
                                'class' : 'btn btn-default',
                                dismiss : true
                            },
                            {
                                text : modalOptions.button.cancel,
                                'class' : 'btn btn-primary',
                                callback : 'cancel',
                                dismiss : true
                            }
                        ],
                        beforeConfirm: modalOptions.beforeSubmit
                    },
                    callback : {
                        confirm : {
                            type : 'click',
                            fn : function() {
                                switch (app.config.button.action) {
                                    case 'submit':
                                        if (modalOptions.beforeSubmit) modalOptions.beforeSubmit();
                                        app.methods.submitForm();
                                        break;
                                    case 'redirect':
                                        window.location.href = app.config.button.href;
                                        break;
                                }
                            }
                        },
                        cancel : {
                            type : 'click'
                        }
                    }
                });
            },
            submitForm : function () {
                app.config.button.self.off('click', app.events.onClick)
                app.config.button.self.trigger('click');
            },
            attach : function () {
				button
                    .off('click', app.events.onClick)
                    .on('click', app.events.onClick);
            }
        }
    };

    return {
        init : app.methods.init
    };

}($));;

APP.namespace('APP.Components');

APP.Components.CookieBar = (function($){
	
	var app,
		cookieBar;

	app = {
		methods : {
      init: function () {			
        cookieBar = $('.cookie-bar');
				if (!cookieBar.length) {
					return;
				}
				
				APP.trace('Log: [components|cookie-bar] Instantiate component...');
				
				app.methods.build();
			},
			build : function () {
				if(app.methods.areCookiesAllowed() == true){
					cookieBar.hide();
				} else {
					cookieBar.show();
					cookieBar.find('[data-event="onClick"]').on('click', function(e) {
						e.preventDefault();
						app.methods.allowCookies();
					});
				}				
				
				setTimeout(function(){
					app.methods.clearCookies()
				},1200);
			},
			createCookie : function (name, value, days) {
				var expires;
				if (days) {
					var date = new Date();
					date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
					expires = "; expires=" + date.toGMTString();
				}
				else expires = "";
				document.cookie = name + "=" + value + expires + "; path=/";
			},
			eraseCookie : function(name) {
				app.methods.createCookie(name, "", -1);
			},
			areCookiesAllowed : function () {
				if (document.cookie && document.cookie != '') {
					var split = document.cookie.split(';');
					for (var i = 0; i < split.length; i++) {
						var nameValue = split[i].split("=");
						var name = nameValue[0].replace(' ', '');
						var value = nameValue[1].replace(' ', '');
						if (name == 'allowCookies' && value == 'on') {
							return true;
						}
					}
				}
				return false;
			},
			clearCookies : function () {
				var cookies = {};
				var cookieNames = new Array();
				var allowed = app.methods.areCookiesAllowed();

				if(allowed == false && document.cookie && document.cookie != '') {
					
					var split = document.cookie.split(';');

					for (var i = 0; i < split.length; i++) {
					
						var nameValue = split[i].split("=");
						var name = nameValue[0].replace(' ', '');

						if(name != 'tourVisited' && name != 'forceWebsiteView') {
							app.methods.eraseCookie(name);
							app.methods.eraseCookie(name, '.' + window.location.hostname);
						}
					}
				}
			},
			tourVisited : function () {
				if (document.cookie && document.cookie != '') {
					var split = document.cookie.split(';');
					for (var i = 0; i < split.length; i++) {
						var nameValue = split[i].split("=");
						var name = nameValue[0].replace(' ', '');
						var value = nameValue[1].replace(' ', '');
						if (name == 'tourVisited' && value == 'true') {
							return true;
						}
					}
				}
				return false;
			},
			setTourVisited : function () {
				app.methods.createCookie('tourVisited', 'true', 356);
			},
			setForceWebsiteView : function () {
				app.methods.createCookie('forceWebsiteView', 'true', 356);
			},
			getBaseURL : function () {
				var baseUrl;
				
				baseUrl = window.location.pathname;

				if (baseUrl.substr(baseUrl.length - 1, 1) != '/') {
					baseUrl += '/';
				}
				return baseUrl;
			},
			allowCookies : function () {
				app.methods.createCookie('allowCookies', 'on', 356);
				cookieBar.hide();
				
				window.location.href = app.methods.getBaseURL() + '?allowCookies=on';
			}
		}
	};
		
    return {
        init : function () {
            app.methods.init();
        }
    };

}($));










;

APP.namespace('APP.Components');

APP.Components.Employees = (function (window, document) {

  var app,
    jqObj,
    toggleObj;

  app = {
    events: {
      onResize: function () {
        app.methods.build();
      }
    },
    methods: {
      getContainerWidth: function () {
        return $('.container').outerWidth();
      },
      init: function () {
        jqObj = $('.employees');
        toggleObj = jqObj.find('.employee');
        if (!jqObj.length) {
          return;
        }

        APP.trace('Log: [components|employees] Instantiate component...');

        app.methods.build();
        app.methods.attach();
      },
      build: function () {
        if (app.methods.getContainerWidth() >= 750) {
          jqObj.find('.employee').attr('data-toggle', 'popover');

          APP.Components.BSPopOver.init({
            container: '.overlay'
          });
        } else {
          APP.Components.BSPopOver.destroy();
        }
      },
      attach: function () {
        $(window)
          .off('resize', app.events.onResize)
          .on('resize', app.events.onResize);

        toggleObj
          .on('click', function (evt) {
            evt.preventDefault();
          }).on('touchend', function () {
            toggleObj.not(this).popover('hide');
          });
      }
    }
  };

  return {
    init: app.methods.init
  };

}(window, document));;

APP.namespace('APP.Components');

APP.Components.Gallery = (function ($) {

    var Gallery = {},
        $rgGallery,
        $esCarousel,
        $items,
        itemsCount,
        current = 0, // index of the current item
        mode = 'carousel', // mode : carousel || fullview
        anim = false;


    Gallery = {
      init: function () {

            $rgGallery = $('#rg-gallery');
            $esCarousel = $rgGallery.find('div.es-carousel-wrapper');
            $items = $esCarousel.find('ul > li');
            itemsCount = $items.length;
            current = 0; // index of the current item
            mode = 'carousel'; // mode : carousel || fullview
            anim = false;

            APP.trace('Log: [components|gallery] Instantiate component...');

            Gallery.addViewModes();
            Gallery.addImageWrapper();
            Gallery.showImage($items.eq(current));
 
            // Hide
            if (itemsCount < 2) {
                mode = 'fullview';
            }
            // Create Gallery...
            if (mode === 'carousel') {
                Gallery.create();
            }
        },
        create: function () {
            // Init elastislide jQuery plugin...
            $esCarousel.show().elastislide({
                imageW: 90,
                onClick: function ($item) {
                    if (anim) return false;
                    anim = true;
                    // on click show image
                    Gallery.showImage($item);
                    // change current
                    current = $item.index();
                },
                onReady: function () { }
            });

            // Set current...
            $esCarousel.elastislide('setCurrent', current);
        },
        addViewModes: function () {
            var $viewfull = $('<a href="#" class="rg-view-full"></a>'),
				$viewthumbs = $('<a href="#" class="rg-view-thumbs rg-view-selected"></a>');

            $rgGallery.prepend($('<div class="rg-view"/>').append($viewfull).append($viewthumbs));

            $viewfull.on('click.rgGallery', function (event) {
                if (mode === 'carousel')
                    $esCarousel.elastislide('destroy');
                $esCarousel.hide();
                $viewfull.addClass('rg-view-selected');
                $viewthumbs.removeClass('rg-view-selected');
                mode = 'fullview';
                return false;
            });

            $viewthumbs.on('click.rgGallery', function (event) {
                Gallery.create();
                $viewthumbs.addClass('rg-view-selected');
                $viewfull.removeClass('rg-view-selected');
                mode = 'carousel';
                return false;
            });

            if (mode === 'fullview') {
                $viewfull.trigger('click');
            }
        },
        addImageWrapper: function () {

            $('#img-wrapper-tmpl').tmpl({ itemsCount: itemsCount }).prependTo($rgGallery);

            if (itemsCount > 1) {
                var $navPrev = $rgGallery.find('a.rg-image-nav-prev'),
					$navNext = $rgGallery.find('a.rg-image-nav-next'),
					$imgWrapper = $rgGallery.find('div.rg-image');

                $navPrev.on('click.rgGallery', function (event) {
                    Gallery.navigate('left');
                    return false;
                });

                $navNext.on('click.rgGallery', function (event) {
                    Gallery.navigate('right');
                    return false;
                });

                // add touchwipe events on the large image wrapper
                $imgWrapper.touchwipe({
                    wipeLeft: function () {
                        Gallery.navigate('right');
                    },
                    wipeRight: function () {
                        Gallery.navigate('left');
                    },
                    preventDefaultEvents: false
                });

                $(document).on('keyup.rgGallery', function (event) {
                    if (event.keyCode == 39)
                        Gallery.navigate('right');
                    else if (event.keyCode == 37)
                        Gallery.navigate('left');
                });

            }
        },
        navigate: function (dir) {
            if (anim) {
                return false;
            }

            anim = true;

            if (dir === 'right') {
                if (current + 1 >= itemsCount) {
                    current = 0;
                } else {
                    ++current;
                }
            } else if (dir === 'left') {
                if (current - 1 < 0) {
                    current = itemsCount - 1;
                } else {
                    --current;
                }
            }

            Gallery.showImage($items.eq(current));
        },
        showImage: function ($item) {
            var $loader = $rgGallery.find('div.rg-loading').show();

            $items.removeClass('selected');
            $item.addClass('selected');

            var $thumb = $item.find('img'),
				largesrc = $thumb.data('large'),
				title = $thumb.data('description'),
				alt = $thumb.data("alt");

            $('<img/>').on('load', function () {

                $rgGallery.find('div.rg-image').html('<img src="' + largesrc + '" alt="' + alt + '" />');

                if (title) {
                    $rgGallery.find('div.rg-caption').show().children('p').empty().text(title);
                }

                $loader.hide();

                if (mode === 'carousel') {
                    $esCarousel.elastislide('reload');
                    $esCarousel.elastislide('setCurrent', current);
                }

                anim = false;

                APP.Block.EqualHeight.update();

            }).attr('src', largesrc);
        },
        addItems: function ($new) {
            $esCarousel.find('ul').append($new);
            $items = $items.add($($new));
            itemsCount = $items.length;
            $esCarousel.elastislide('add', $new);
        }
    };

    return {

        init: function () {
            Gallery.init();
        },

        add: function (elements) {
            Gallery.addItems(elements);
        }
    };

}($));;
APP.namespace('APP.Component');

APP.Components.PasswordStrength = (function() {
	"use strict";
	
	var app,
		jqObj,
		inputObj,
		inputValue,
		rank = {
			TOO_SHORT : 1,
			WEAK : 2,
			MEDIUM : 3,
			STRONG : 4,
			VERY_STRONG : 5
		};

	app = {
		events : {
			onFocusBlur : function (evt) {
				if (evt.type === 'blur') {
					inputValue = $(this).val();

					var rank = app.methods.getRank();
					app.methods.animateBar(rank);
				}
			}
		},
		methods : {
			init : function () {
				inputObj = $('input[type="password"]');

				if (!inputObj.length && !inputObj.next().hasClass('.password-strength')) {
					return;
				}

                APP.trace('Log: [components.passwordstrength.init] Init component...');
                APP.Components.PasswordStrength.active = true;

				jqObj = inputObj.next();
				app.methods.attach();
			},
			animateBar : function (r) {
				var pos = parseFloat(r * 20) + '%';

				jqObj.show();

				setTimeout(function(){
					jqObj.find('.bar').css('margin-left', pos);
				}, 100)
			},
			getRank : function () {
				var upper = /[A-Z]/,
					lower = /[a-z]/,
					number = /[0-9]/,
					special = /[^A-Za-z0-9]/,
					minLength = 8,
					score = 0;

				if (inputValue === '') {
					return 0;
				}

				if (inputValue.length < minLength) {
					return rank.TOO_SHORT;
				}

				if (upper.test(inputValue)) score++;
				if (lower.test(inputValue)) score++;
				if (number.test(inputValue)) score++;
				if (special.test(inputValue)) score++;

				// penalize when there aren't at least three character types
				if (score < 4) score--;

				if (inputValue.length > minLength) {
					score += Math.floor((inputValue.length - minLength) / 2);
				}

				if (score < 4) return rank.WEAK; // score is three or lower
				if (score < 5) return rank.MEDIUM; // score is four
				if (score < 7) return rank.STRONG; // score is six or five
				return rank.VERY_STRONG;
			},
			attach : function () {
				inputObj.off('focus blur', app.events.onFocusBlur)
						.on('focus blur', app.events.onFocusBlur)
			}
		}
	};
	
	return {
		init : app.methods.init
	}

}());
;

APP.namespace('APP.Components');

APP.Components.Switch = (function ($) {

  var app,
    input;

  app = {
    events: {
      onInputChange: function (evt) {
        evt.preventDefault();

        var jqObj = $(this);
        app.methods.switch(jqObj);
      }
    },
    methods: {
      init: function () {
        input = $('input[data-switch], .form-row[data-switch] input');
        if (!input.length) {
          return;
        }

        APP.trace('Log: [components|switch] Instantiate component...');

        // render...
        app.methods.render();

        // attach event...
        app.methods.attach();
      },
      render: function () {
        input.each(function () {
          var jqObj = $(this);

          if (jqObj.is(':checked')) {
            app.methods.switch(jqObj);
          }
        });
      },
      switch: function (jqObj) {
        switch (jqObj[0].type) {
          case 'radio':
            app.methods.toggle.radio(jqObj);
            break;
          case 'checkbox':
            app.methods.toggle.checkbox(jqObj);
            break;
        }
      },
      toggle: {
        checkbox: function (jqObj) {
          var name = jqObj.attr('name'),
            switchTarget = jqObj.data('switch') || jqObj.attr('id'),
            targetObj = $('[data-switch-target="' + switchTarget + '"]');

          if (targetObj.hasClass('hidden')) {
            targetObj.removeClass('hidden');
          } else {
            targetObj.addClass('hidden');
          }
        },
        radio: function (jqObj) {
          var name = jqObj.attr('name'),
            switchTarget = jqObj.filter(':checked').data('switch'),
            contentObj = $('[data-switch-name="' + name + '"]'),
            targetObj = $('[data-switch-target="' + switchTarget + '"]');

          contentObj.removeClass('active');
          targetObj.addClass('active');
        }
      },
      attach: function () {
        input
          .off('change', app.events.onInputChange)
          .on('change', app.events.onInputChange);
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    }
  };

}($));;

APP.namespace('APP.Components');

APP.Components.Modal = (function ($) {
  "use strict";

  var app,
    button,
    config,
    jqObject;

  app = {
    config: {
      templateUrl: '/assets/js/APP/components/modal.html'
    },
    methods: {
      isActive: function () {
        jqObject = $('.modal.' + config.data.type);
        return (jqObject.length ? true : false);
      },
      create: function (o) {
        if (typeof o !== 'object') {
          return;
        }

        // store config locally...
        // ---------------------------------
        config = o;

        if (app.methods.isActive()) {
          app.methods.render();
        } else {
          app.methods.get(function (html) {
            jqObject = $(html);

            // append html
            $('body').prepend(jqObject);

            // render modal
            app.methods.render();
          });
        }
      },
      get: function (callback) {
        if (typeof callback === 'function') {
          $.get(app.config.templateUrl, callback);
        }
      },
      render: function () {
        app.methods.ui.modal();
        app.methods.ui.closeButton();
        app.methods.ui.buttons();

        app.methods.ui.bind.events();
        app.methods.ui.bind.callbacks();

        app.methods.open();
      },
      ui: {
        modal: function () {
          if (config.data.animation === true) {
            jqObject.addClass('fade');
          }

          // add modal type class
          jqObject.find('.modal-inner').addClass(config.data.type);

          // remove elements
          jqObject.find('.modal-inner > .modal-header > button').html('').hide();
          jqObject.find('.modal-inner > .modal-footer > ul > li').remove();

          // set the modal data
          jqObject.find('h2').text(config.data.title);
          jqObject.find('p').html(config.data.text);
        },
        closeButton: function () {
          if (typeof config.data.close !== 'object') {
            return;
          }

          var type,
            content,
            button;

          type = config.data.close.type;
          content = config.data.close.content;
          button = jqObject.find('.modal-inner > .modal-header > button');

          // when type is icon and content is instance of jQuery, append element...
          if (type === 'icon' && content instanceof jQuery) {
            button.append(content);
          }

          // when type is text and typeof content is string, store text...
          if (type === 'text' && typeof content === 'string') {
            button.text(content);
          }

          button.show();
        },
        buttons: function () {
          if (typeof config.data.button !== 'object') {
            return;
          }

          var ul,
            list = [];

          $.each(config.data.button, function (index, value) {
            if (typeof value !== 'object') {
              return;
            }

            var button,
              item;

            button = $('<button/>', {
              'text': value.text,
              'class': value.class
            });

            button.attr('data-dismiss', (value.dismiss ? 'modal' : null));
            button.attr('data-callback', value.callback);

            item = $('<li/>');
            item.append(button);

            list.push(item);
          });

          ul = jqObject.find('.modal-footer > ul');
          ul.append.apply(ul, list);
        },
        bind: {
          events: function () {
            if (typeof config.events !== 'object') {
              return;
            }

            var evt;

            // bootstrap modal api
            // ---------------------------------
            // eg. show.bs.modal
            for (evt in config.events) {
              if (config.events.hasOwnProperty(evt) && typeof config.events[evt] === 'function') {
                jqObject
                  .off(evt, config.events[evt])
                  .on(evt, config.events[evt]);
              }
            }
          },
          callbacks: function () {
            if (!jqObject.find('button[data-callback]').length) {
              return;
            }

            jqObject.find('button[data-callback]').each(function () {
              var button,
                cb;

              button = $(this);
              cb = button.data('callback');

              if (typeof config.callback[cb] === 'object') {
                button.off(config.callback[cb].type, config.callback[cb].fn).on(config.callback[cb].type, config.callback[cb].fn);
              }
            });
          }
        }
      },
      open: function () {
        jqObject.modal('show');
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    },
    create: function (data) {
      app.methods.create(data);
    }
  };

}(jQuery));;

APP.namespace('APP.Components');

APP.Components.Panel = (function($){

    var app,
        panel,
		containerWidth = 0;

    app = {
        events : {
            onResize : function () {
                if (!panel) return;

                var newWidth = panel.closest('.container').width();

                //only horizontal resizing
				if (newWidth !== containerWidth) {
					containerWidth = newWidth;
					
					app.methods.toggle('close');
					app.methods.build();
				}
            }
        },
        methods : {
			update : function () {				
				panel = $('.panel-filter');
				
				if (!panel.length) {
					return;
				}
				
				containerWidth = panel.closest('.container').width();
					
				app.methods.build();			
			},
            init : function () {				
				APP.trace('Log: [components|panel] Instantiate component...');
				
				panel = $('.panel-filter');				
				containerWidth = panel.closest('.container').width();
					
				app.methods.build();
				app.methods.attach();
            },
            build : function () {
                var limit,
                    width;

                limit = parseFloat(panel.attr('data-panel-limit'));
                width = panel.closest('.container').width();

                if (!limit || width < limit) {
                    return;
                }

                app.methods.toggle('open');
            },
            toggle : function (type) {				
                switch (type) {
                    case 'open':
                        panel.find('.panel-heading a').attr('aria-expanded','true');
                        panel.find('.panel-collapse').addClass('in');
                        break;
                    case 'close':
                        panel.find('.panel-heading a').attr('aria-expanded','false');
                        panel.find('.panel-collapse').removeAttr('style').removeClass('in');
                        break;
                }
            },
            attach : function () {
                $(window).unbind('resize',app.events.onResize).on('resize',app.events.onResize);
            }
        }
    };

    return {
        init : function () {
            app.methods.init();
        },
		update : function () {
            app.methods.update();
        }
    };

}($));;
/**
 * TabPanel
 * ----------------------------------------------------------
 *
 * @type       JS
 * @author     Ken van den Broek    <k.vandenbroek@uselab.com>
 * @copyright  2015 Uselab.com
 * @deprecated
 */
APP.namespace('APP.Components');

APP.Components.TabPanel = (function (document, window) {

    var app,
        tabObj,
        tabNavObj,
        tabContentObj;

    app = {
        events : {
            onResize : function () {
                app.methods.render();
            },
            onTabClick : function () {
                var liObj = $(this).parent(),
                    index = liObj.index(),
                    name = liObj.data('panel');

                // calculate and set the horizontal scroll position...
                if (app.methods.isVisibleScroll()) {
                    var width = (app.methods.getScrollWidth(index) - 15);

                    tabObj.find('nav').delay(100).animate({
                        scrollLeft: width
                    }, 600, 'easeInOutQuad');
                }

                // toggle nav and content...
                app.methods.toggle(name);
            }
        },
        methods : {
          init: function () {
                tabObj = $('.tab-panel');
                tabNavObj = $('.panel-nav nav > ul');
                tabContentObj = $('.panel-content');
                APP.trace('Log: [components|tab-panel] Instantiate component...');

                // render...
                app.methods.render();

                // toggle...
                app.methods.toggle();

                // attach events...
                app.methods.attach();
            },
            render : function () {
                if (app.methods.isVisibleScroll()) {
                    tabObj.find('nav').css('overflow-x', 'scroll');
                } else {
                    tabObj.find('nav').removeAttr('style');
                }
            },
            getActivePanel : function () {
                var hashBang = window.location.hash;

                if (hashBang.substring(0,7) == "#panel-") {
                    return hashBang.split('-')[1];
                }
            },
            getScrollWidth : function (i) {
                var w = 0;

                tabNavObj.children('li').each(function(){
                    var liObj = $(this);

                    if (liObj.index() < i || typeof i === 'undefined') {
                        w = ( w + liObj.outerWidth() );
                    }
                });

                return w;
            },
            toggle : function (n) {
                var name = (typeof n !== 'undefined' ? n : app.methods.getActivePanel()),
                    selectedTab;

                // when name is undefined (no click event), and when there's no hashbang, get the first panel name...
                // otherwise we are sending an analytics event with the tabbed data...
                if (typeof name === 'undefined') {
                    name = tabNavObj.find('li:eq(0)').data('panel');
                } else {
                    app.methods.sendTracking(name);
                }

                selectedTab = tabContentObj.find('div[data-panel~="' + name + '"]');

                // tabs...
                tabNavObj.find('li').removeClass('selected');
                tabNavObj.find('li[data-panel="' + name + '"]').addClass('selected');

                // remove content classes...
                tabContentObj.find('div[data-panel]')
                    .removeClass('visible')
                    .removeClass('animate');

                // add content visible class...
                selectedTab.addClass('visible');

                // reset content
                selectedTab.find('[data-content]').removeClass('visible');
                selectedTab.find('[data-content="' + name + '"]').addClass('visible');

                // timeout...
                setTimeout(function(){
                    // animate panel
                    selectedTab.addClass('animate');

                    // broadcast event to listeners...
                    // added in timeout to make sure that the event
                    // is triggered when other components are loaded...
                    $(document).trigger("tab.panel.change", {
                        name : name
                    });
                }, 75);
            },
            isVisibleScroll : function () {
                var width = app.methods.getScrollWidth();
                return (width > tabObj.outerWidth());
            },
            sendTracking : function (name) {
                APP.Core.Tracking.set({
                    trackingType : 'event',
                    eventCategory : 'Panel Tab Navigation',
                    eventAction : 'click',
                    eventLabel : name
                })
            },
            attach : function () {
                $(window)
                    .off('resize', app.events.onResize)
                    .on('resize', app.events.onResize);

                tabNavObj.find('a')
                    .off('click', app.events.onTabClick)
                    .on('click', app.events.onTabClick);
            }
        }
    };

    return {
        init : app.methods.init
    }

}(document, window));;

APP.namespace('APP.Components');

APP.Components.TabPanelRealEstate = (function ($) {

  var app;
  var selectType;
  var selectMin;
  var selectMax;
  var wrapper;
  var selectRegions;
  var infoWoningNet;

  // removed from the HTML for SEO reasons
  var infoWoningNetText = (typeof window.woningnetverwijzing !== 'undefined' ? window.woningnetverwijzing : "");

  // data objects
  var FormData;
  var selectMinData = {};
  var selectRegionsData = {};
  var selectMaxData = {};

  app = {
    events: {
      onChange: function () {
        var type = selectType.val();
        app.methods.changeHandler(type);
      }
    },
    ui: {
      changeFormSearchFilter: function () {
        var type = selectType.val();

        if (type === 'bedrijf') {
          selectMin.parent().hide(); // hide from / to
          selectMax.parent().hide();
        }

        // show from / to
        selectMin.parent().show();
        selectMax.parent().show();
        infoWoningNet.html('&nbsp;');
        wrapper.removeClass('bedrijfsruimte');

        switch (type) {
          default:
          case 'huur':
            infoWoningNet.html(infoWoningNetText);
            break;
          case 'koop':
            break;
          case 'bedrijf':
            wrapper.addClass('bedrijfsruimte');
            selectMin.parent().hide(); // hide from / to
            selectMax.parent().hide();
            break;
          case 'parkeer':
            break;
        }
      },
      changeFormSearchPanel: function () {
        var cityObject = $('.panel-content .custom-dropdown.select-plaats > select'),
          type = selectType.val();

        cityObject.parent().removeClass('custom-dropdown');

        $('.panel-content div[data-panel~="' + type + '"] .select-plaats')
          .addClass('custom-dropdown')
          .append(cityObject);
      }
    },
    methods: {

      init: function () {


        selectType = $('.select-soort select');
        selectMin = $('select[data-range-selector="from"]');
        selectMax = $('select[data-range-selector="to"]');
        wrapper = $('.wrapper');
        selectRegions = $('.select-plaats select');
        infoWoningNet = $('.info-woningnet');

        if (!$('.tab-panel.tab-panel-real-estate').length && !$('.home-header-nav').length) {
          return;
        }

        APP.trace('Log: [component|tab-panel-real-estate] Instantiate component...');

        // build data and call function...
        app.methods.getData(app.methods.render);
      },
      getData: function (cb) {
        var jsonData = window.TekoopTeHuurFilterValuesJson,
          i;

        if (typeof jsonData === 'undefined') {
          return;
        }

        FormData = {};

        for (i in jsonData) {
          if (jsonData.hasOwnProperty(i)) {
            FormData[jsonData[i].Key] = jsonData[i].Value;
          }
        }

        if (typeof cb === 'function') {
          cb.call();
        }
      },
      render: function () {
        var type = selectType.val();

        app.methods.attach();
        app.methods.changeHandler(type);
      },
      changeHandler: function (type) {
        if (typeof FormData !== 'object') {
          return;
        }

        switch (type) {
          default:
          case 'huur':
            selectMinData = FormData.huur_prijs_low;
            selectRegionsData = FormData.huur_regios;
            selectMaxData = FormData.huur_prijs_high;
            break;
          case 'koop':
            selectMinData = FormData.koop_prijs_low;
            selectRegionsData = FormData.koop_regios;
            selectMaxData = FormData.koop_prijs_high;
            break;
          case 'bedrijf':
            selectRegionsData = FormData.bedrijfsruimte_regios;
            break;
          case 'parkeer':
            selectMinData = FormData.parkeerplaats_prijs_low;
            selectRegionsData = FormData.parkeerplaats_regios;
            selectMaxData = FormData.parkeerplaats_prijs_high;
            break;
        }

        // create UI first!
        app.methods.createUI();

        // create Form elements...
        app.methods.createElements();
      },
      createUI: function () {
        // currently the only form rendered dynamic is the search panel
        //  which is placed on the homepage...
        app.ui.changeFormSearchPanel();
      },
      createElements: function () {
        var multiSelect = $(".select-plaats select");


        try {
          multiSelect.multiselect("destroy");
        } catch (e) { }

        selectRegions.html('');
        selectMin.html('');
        selectMax.html('');

        $.each(selectRegionsData, function (key, value) {
          selectRegions.append($("<option></option>")
            .attr("value", value.Item1)
            .attr("data-group", value.Item3)
            .text(value.Item2));
        });

        $.each(selectMinData, function (key, value) {
          selectMin.append($("<option></option>")
            .attr("value", value.Item1)
            .text(value.Item2));
        });

        $.each(selectMaxData, function (key, value) {
          selectMax.append($("<option></option>")
            .attr("value", value.Item1)
            .text(value.Item2));
        });

        multiSelect.multiselect({
          /* selectedList: 4, // 0-based index */
          selectedList: 1,
          noneSelectedText: "Plaats / Stadsdeel",
          checkAllText: "Selecteer alles",
          uncheckAllText: "Wis alles",
          selectedText: "# geselecteerd"
        });
      },
      changeSelectValue: function (event, data) {
        var selectObj = $('.select-soort > select');
        selectObj.val(data.name);
        selectObj.trigger('change');
      },
      attach: function () {
        selectType
          .off('change', app.events.onChange)
          .on('change', app.events.onChange);

        $(document)
          .off('tab.panel.change', app.methods.changeSelectValue)
          .on('tab.panel.change', app.methods.changeSelectValue);
      }
    }
  };

  return {
    init: app.methods.init
  };

}($));;


APP.namespace('APP.Components');

APP.Components.TableDefault = (function ($) {
  "use strict";

  var app,
    DefaultTables,
    LineGraphs,
    PieGraphs,
    ColumnGraphs,
    tableCollections,
    tableID = 0;

  app = {
    settings: {
      graphColors: ['#E2124C', '#92278F', '#919195', '#F78E1E', '#FFD200', '#8DC63F', '#337AB7', '#23527C'],
      backgroundColor: '#FAF9F9'
    },

    drawVisualization: function (tableEl, chartType) {
      var values = []; // to hold our values for data table
      // get our values

      var graphId = 'graph_' + tableID++;

      var tmp = tableEl.before('<div id="' + graphId + '"></div>');

      tableEl.find('tr').each(function (i, v) {
        values[i] = [];
        // select either th or td, doesn't matter
        $(this).children('th, td').each(function (ii, vv) {
          values[i][ii] = (i == 0 || ii == 0) ? $(this).text() : parseFloat($(this).text());
        });
      });
      // convert 2d array to dataTable and draw
      var data = google.visualization.arrayToDataTable(values);

      var legend = {
        maxLines: 4,
        position: 'bottom',
        scrollArrows: {
          activeColor: '#337AB7',
          inactiveColor: '#afafaf',
          textColor: '#afafaf',
          height: 10,
          width: 10,
          size: 10
        },
        pagingTextStyle: {
          color: '#655F5F',
          fontSize: 0.01
        }
      };

      var g = new google.visualization.ChartWrapper({
        containerId: graphId,
        dataTable: data,
        chartType: chartType,
        options: {
          chartArea: { width: '100%' },
          width: '100%',
          height: 400,
          colors: app.settings.graphColors,
          backgroundColor: app.settings.backgroundColor,
          allowHtml: true,
          legend: legend
        }
      });

      g.draw();
      tableEl.hide();
      tableEl.closest('.table-default-container').css({ overflow: 'hidden' })
    },

    methods: {
      init: function () {
        DefaultTables = $('table.table-default, table.text-table');
        LineGraphs = $('table.line-graph');
        PieGraphs = $('table.pie-graph');
        ColumnGraphs = $('table.column-graph');
        tableCollections = $('.tablecollection');

        LineGraphs.each(function () {
          app.drawVisualization($(this), 'LineChart');
        });

        PieGraphs.each(function () {
          app.drawVisualization($(this), 'PieChart');
        });

        ColumnGraphs.each(function () {
          app.drawVisualization($(this), 'ColumnChart');
        });

        if ($('body#pdfprint').length) return;

        // in print version we don't show table collections but all
        // tables/ graphs separately
        if (DefaultTables.length > 0) {
          DefaultTables.wrap('<div class="table-default-container"></div>');
        }
        tableCollections.prepend('<h3></h3>');

        // create select box for
        tableCollections.each(function () {

          var tableItems = $(this).find('.tableitem');
          var tableCollection = $(this);

          if (tableItems.length !== 0) {

            var selectElement = $("<select />", { "class": "collection-select" });

            tableItems.each(function () {
              selectElement.append($("<option />").html($(this).data("option")));
            });

            selectElement.change(function () {
              tableItems.hide();
              var item;
              if (typeof ($.prop) !== 'undefined') {
                item = $(tableItems[$(this).prop("selectedIndex")]);
              } else {
                item = $(tableItems[$(this).find(":selected").index()]);
              }
              item.show();
              tableCollection.find('h3').first().text(item.find('h3').text());
            });

            // show only first item
            tableItems.hide();
            $(this).prepend(selectElement);

            tableCollection.find('h3').first().text($(tableItems[0]).find('h3').text());

            tableItems.first().show();
            selectElement.wrap('<div class="select-container"></div>');
          }

        });
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    }
  };

}(jQuery));;

APP.namespace('APP.Components');

APP.Components.TabList = (function (document, window) {

    var app,
        tabObj,
        tabActive,
        tabLinks,
        tabsEnabled = false;

    app = {
        events : {
            onResize: function() {
               if($(window).width() <= 974) {
                   tabsEnabled = true;
                   if(!tabObj.hasClass('expanded')) {
                       tabObj.height(0)
                   }
               } else {
                   tabsEnabled = false;
                   tabObj.height('auto')
               }
            }
        },
        methods : {
            init : function () {
            tabObj = $('.tab-list ul');
            tabActive = $('.tab-list ul li.active');
            tabLinks = $('.tab-list ul li a');
                $(window)
                    .off('resize', app.events.onResize)
                    .on('resize', app.events.onResize);

                tabActive.on('click', function(e) {

                    if(!tabsEnabled) return;

                    e.preventDefault();

                    if(tabObj.hasClass('expanded')) {
                        tabObj.removeClass('expanded')

                        tabObj.animate({
                            height: 0
                        }, 200, function() {
                            // Animation complete.
                        });

                    } else {
                        tabObj.addClass('expanded')
                        tabObj.animate({
                            height: (tabObj.find('li').length * 53) - 50
                        }, 200, function() {
                            // Animation complete.
                        });
                    }

                })

                // expand tabs if no option was chosen by the user yet
                if(!app.methods.getTabClicked()) {
                    tabObj.addClass('expanded')
                    tabObj.height((tabObj.find('li').length * 53) - 50);
                }

                // save status when option is chosen by user so we don't need to expand it next time
                tabLinks.on('click', function(e) {
                    app.methods.setTabClicked();
                });

                app.events.onResize();
            },
            setTabClicked : function () {
                var tabID = 'tab-selected-' + tabObj.data("tab-id");
                if(tabID) {
                    $.cookie(tabID, true, { expires: 356 });
                }
            },
            getTabClicked : function () {
                var tabID = 'tab-selected-' + tabObj.data("tab-id");
                if(tabID) {
                    return $.cookie(tabID);
                }
                return false;
            }
        }
    };

    return {
        init : app.methods.init
    }

}(document, window));;

APP.namespace('APP.Components');

APP.Components.Tabs = (function (document, window) {

  var app,
    tabs,
    currentTab,
    streetViewLoaded = false,
    selectors = {
      'tab-fotos': '#rg-gallery',
      'tab-video': '#tab-video-content',
      'tab-plan': '#tab-plan-content',
      'tab-map': '.map',
      'tab-streetview': '.map'
    };

  app = {
    events: {
      onTabClick: function (evt) {
        var el = $(this),
          tabMenu = el.parents('.nav-tabs'),
          data = tabMenu.data(),
          targetId = data.component.split('.')[1] || undefined,
          tabId;

        tabMenu.find('li').removeClass('active');

        currentTab = el.parent();
        currentTab.addClass('active');

        tabId = currentTab.attr('id');

        app.methods.hideTabContent(targetId);
        app.methods.showTabContent(tabId, targetId);

        APP.Core.Bootstrap.onPanelReady();

        evt.preventDefault();
      }
    },
    methods: {
      init: function () {
        tabs = $('[data-component^="tabs"]');
        if (!tabs.length) {
          return
        }

        APP.trace('Log: [components|tabs] Instantiate component...');

        app.methods.build();
        app.methods.attach();
        app.methods.show();
      },
      build: function () {
        app.methods.hideTabContent();
      },
      openTabFromHash: function () {
        var hashStr = window.location.hash.substr(1);
        if (hashStr === '/tab-video' || hashStr === '!#tab-video' || hashStr === 'tab-video') {
          if ($(selectors['tab-video']).length) {
            app.methods.triggerClick('tab-video');
          }
        }
      },
      showTabContent: function (tabId, targetId) {
        var selectorObj,
          target = (typeof targetId !== 'undefined' ? '[data-tab-content="' + targetId + '"]' : 'body');

        if (tabId && typeof selectors[tabId] !== 'undefined') {
          var selector = selectors[tabId];
          selectorObj = $(target).find(selector);
          if (selectorObj.length) {
            selectorObj.show();
          }
        }

        if (tabId === 'tab-streetview') {
          app.methods.update.streetView();
        } else if (tabId === 'tab-map') {
          app.methods.update.map();
        }
      },
      hideTabContent: function (targetId) {
        var target = (typeof targetId !== 'undefined' ? '[data-tab-content="' + targetId + '"]' : 'body');

        $.each(selectors, function (k, v) {
          // hide the video
          if (v === '#tab-video-content') {
            var videoContentEl = $('#tab-video-content');
            if (videoContentEl.length) {
              var videoContent = videoContentEl.html();
              videoContentEl.html(''); // remove (stop) video
              videoContentEl.html(videoContent); // resore video iframe (resetted version)
            }
          }
          $(target).find(v).hide();
        });
      },
      update: {
        streetView: function () {
          if (!streetViewLoaded) {
            initStreetView();
            streetViewLoaded = true;
          } else {
            showStreetView(true);
          }
        },
        map: function () {
          updateMap();
          showStreetView(false);
        }
      },
      triggerClick: function (item) {
        var el = $('#' + item);
        el.find('a').trigger('click');
      },
      show: function () {
        tabs.each(function () {
          var el = $(this),
            data = el.data(),
            init = data.init;

          if (typeof init !== 'undefined' && typeof selectors[init] !== 'undefined') {
            app.methods.triggerClick(init);
          } else {
            var targetId = data.component.split('.')[1] || undefined,
              target = (typeof targetId !== 'undefined' ? '[data-tab-content="' + targetId + '"]' : 'body');

            if ($(target).find(selectors['tab-fotos']).length) {
              app.methods.triggerClick('tab-fotos');
            } else if ($(target).find(selectors['tab-video']).length) {
              app.methods.triggerClick('tab-video');
            } else if ($(target).find(selectors['tab-plan']).length) {
              app.methods.triggerClick('tab-plan');
            } else {
              app.methods.triggerClick('tab-map');
            }
          }
        });

        app.methods.openTabFromHash();
      },
      attach: function () {
        tabs.find('li a').on('click', app.events.onTabClick);
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    }
  };

}(document, window));;

APP.namespace('APP.Components');

APP.Components.ExpandableList = (function (document, window) {

  var app, faqList;


  app = {
    events: {

    },
    methods: {
      init: function () {
        faqList = $('ul.expandable-list');

        if (location.hash == '' || !faqList.length) return

        // fix Vue hashbang
        var locationHash = location.hash.split('#').join('');
        locationHash = locationHash.split('/').join('');

        var item = faqList.find('li h3[data-target=\'#' + locationHash + '\']');

        if (item.length == 1) {
          $(window).on('load', function () {
            $('html, body').animate({
              scrollTop: item.offset().top - 10
            }, 300, function () {
              item.trigger('click');
            });
          })
        }
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    }
  };

}(document, window));;

APP.namespace('APP.Components');

APP.Components.CookieBar = (function (window, document) {
  "use strict";

  var app,
    topObj,
    jqObj,
    selectedObj;

  function hasDependency() {
    return (typeof window.CookieConsent !== 'undefined');
  }

  app = {
    config: {
      baseUrl: '/assets/js/app/components/',
      template: 'cookie-bar-placeholder.html',
      default: '.block[data-consent-type="necessary|preferences"]',
      key: {
        ESCAPE: 27
      },
      states: {
        hidden: 'is-hidden',
        visible: 'is-visible',
        selected: 'is-selected'
      },
      checkboxes: {
        necessary: 'input#CybotCookiebotDialogBodyLevelButtonNecessary',
        preferences: 'input#CybotCookiebotDialogBodyLevelButtonPreferences',
        statistics: 'input#CybotCookiebotDialogBodyLevelButtonStatistics',
        marketing: 'input#CybotCookiebotDialogBodyLevelButtonMarketing'
      },
      button: 'button#CybotCookiebotDialogBodyLevelButtonAccept',
      cookieBanner: 'div#cookieBanner',
      declarationPanel: 'div#CookieDeclarationUserStatusPanel',
      consent: []
    },
    events: {
      onResize: function () {
        app.methods.changeUi();
      },
      onToggleModal: function (evt) {
        evt.preventDefault();

        var scroll = (evt.data && evt.data.scroll ? evt.data.scroll : false);

        app.methods.showModal(scroll);
      },
      onSelect: function () {
        selectedObj = $(this);
        app.methods.selectOption();
      },
      onApply: function (evt) {
        evt.preventDefault();
        app.methods.applyConsent();
      },
      onApplyAll: function (evt) {
        evt.preventDefault();
        selectedObj = $('.block[data-consent-type="necessary|preferences|statistics|marketing"]');
        app.methods.applyConsent();
      },


      onKeyUp: function (evt) {
        if (evt.keyCode !== app.config.key.ESCAPE) return;

        app.methods.set();
        app.methods.hideModal();
      }
    },
    methods: {

      /**
       * init()
       * 
       * Default fn to instantiate te module...
       * 
       */

      init: function () {


        topObj = $('body').find('#navigation');
        jqObj = $('body').find('.cookiebar');

        if (!jqObj.length) {
          return;
        }

        if (!topObj.length) {
          APP.trace('Log: [components|cookie-bar] Requisite element not found...');
          return false;
        } else {
          APP.trace('Log: [components|cookie-bar] Instantiate component...');
          app.methods.create();
          return true;
        }
      },

      /**
       * getTemplatePath()
       * 
       * Returns the template path to load thru $.get() method...
       * 
       * @returns     string
       * 
       */

      getTemplatePath: function () {
        var lang = $('html').attr('lang') || 'nl';
        return (app.config.baseUrl || '') + app.config.template.replace('placeholder', lang);
      },

      /**
       * getCookie()
       * 
       * Get the CookieConsent cookie...
       * 
       * @returns     string
       * 
       */

      getCookie: function () {
        return (APP.Utilities.Cookie.get('CookieConsent') || '');
      },

      /**
       * getConsent()
       * 
       * Get the current user consent setting...
       * 
       * @param       string
       * @returns     array
       * 
       */

      getConsent: function (cookie) {
        var data = cookie.replace(/{|}|\'/g, '').split(','),
          consent = [];

        $.each(data, function (k, v) {
          var item = {};

          item.type = v.split(':')[0];
          item.consent = v.split(':')[1];

          if (typeof app.config.checkboxes[item.type] !== 'undefined' && item.consent === 'true') {
            consent.push(item.type);
          }
        });

        return consent;
      },

      /**
       * applyConsent()
       * 
       * Apply new consent settings, which modifies the 
       *  original cookie consent banner and triggers the button click...
       * 
       */

      applyConsent: function () {
        var consent = selectedObj.data('consent-type').split('|'),
          checkboxes = app.config.checkboxes,
          button = $(app.config.button);

        $.each(checkboxes, function (k, v) {
          var el = $(v);

          if (el.length) {
            el.prop('checked', (consent.indexOf(k) !== -1));
          }
        });

        jqObj.removeClass(app.config.states.visible)
          .addClass(app.config.states.hidden);

        button.trigger('click');
      },

      /**
       * isAfter()
       * 
       * Checks the position of the cookie banner...
       * 
       * @returns     boolean
       * 
       */

      isAfter: function () {
        return ($('body').find('#top').next().hasClass('cookiebar') ? true : false);
      },

      /**
       * isMobile()
       * 
       * Check screen width is mobile...
       * 
       * @returns     boolean
       * 
       */

      isMobile: function () {
        return false;//!APP.Utilities.Responsive.isMedium();
      },

      /**
       * create()
       * 
       * Create the cookie banner...
       * 
       */

      create: function () {
        jqObj.addClass(app.config.states.hidden);

        app.methods.changeUi();

        var tpl = app.methods.getTemplatePath();

        $.get(tpl, app.methods.render);
      },

      /**
       * changeUi()
       * 
       * Change the UI and modify layout based on the device screen width...
       * 
       */

      changeUi: function () {
        // removed with 2019 update
      },

      /**
       * render()
       * 
       * Render cookie banner with layout retrieved from $.get();
       * 
       */

      render: function (data) {
        jqObj.append($(data));

        app.methods.initBanner();
        app.methods.attach();
        app.methods.set();
      },

      /**
       * set()
       * 
       * Sets the inital consent setting to the UI...
       * 
       */

      set: function () {

        var cookie = app.methods.getCookie(),
          selector;

        app.config.consent = app.methods.getConsent(cookie);

        if (!app.config.consent.length || app.config.consent.length === 1) {
          jqObj.removeClass(app.config.states.hidden);
          selector = jqObj.find('.cookie-configuration .row .column').find(app.config.default)[0];
        } else {
          selector = '[data-consent-type="placeholder"]'.replace('placeholder', app.config.consent.join('|'));
        }

        $(selector).trigger('click');
      },

      /**
       * showModal()
       * 
       * Show modal screen...
       * 
       */

      showModal: function (scroll) {
        jqObj.removeClass(app.config.states.hidden)
          .addClass(app.config.states.visible);

        if (app.methods.isMobile() && scroll) {
          $(window).scrollTop(jqObj.offset().top);
        }
      },

      /**
       * hideModal()
       * 
       * Hide modal screen...
       * 
       */

      hideModal: function () {
        jqObj.removeClass(app.config.states.visible);

        if (app.config.consent.length) {
          jqObj.addClass(app.config.states.hidden);
        }
      },

      /**
       * selectOption()
       * 
       * Sets the selected consent option in modal...
       * 
       */

      selectOption: function () {
        selectedObj.parents('.row:eq(0)').find('.block').removeClass(app.config.states.selected);
        selectedObj.addClass(app.config.states.selected);
      },
      /**
       * initBanner()
       * 
       * Show the original CookieConsent banner, 
       *  otherwise we can't adjust the consent configuration...
       * 
       */
      initBanner: function () {
        var loader,
          timer = 400;

        loader = setInterval(function () {
          if (!hasDependency()) return;

          // another timeout because CookieConsent sometimes still 
          //  causes an error when script hasn't finished loading...
          setTimeout(function () {
            var banner = $(app.config.cookieBanner),
              panel = $(app.config.declarationPanel);

            // make sure the banner is active...
            if ((!banner.length || !banner.hasClass('active')) && typeof CookieConsent !== 'undefined' && typeof CookieConsent.show !== 'undefined') {
              CookieConsent.show();
            }

            // overwrite cookie consent fn...
            if (panel.length) {
              CookieConsent.renew = function () {
                app.methods.showModal(true);
              };
            }
          }, timer);

          clearInterval(loader);
        }, timer);
      },

      /**
       * attach()
       * 
       * Bind all event listeners...
       * 
       */

      attach: function () {

        $(window)
          .off('resize', app.events.onResize)
          .on('resize', app.events.onResize);

        $('.cookie-settings')
          .off('click', app.events.onToggleModal)
          .on('click', { scroll: true }, app.events.onToggleModal);

        $('a[href="#configuration"]')
          .off('click', app.events.onToggleModal)
          .on('click', app.events.onToggleModal);

        jqObj.find('.cookie-configuration .row .block')
          .off('click', app.events.onSelect)
          .on('click', app.events.onSelect);

        jqObj.find('button#apply')
          .off('click', app.events.onApplyAll)
          .on('click', app.events.onApplyAll);

        jqObj.find('button#apply-modal')
          .off('click', app.events.onApply)
          .on('click', app.events.onApply);

        $(document)
          .off('keyup', app.events.onKeyUp)
          .on('keyup', app.events.onKeyUp);

        $(".CookieDeclarationTable").wrap("<div class='scroll-container'></div>");
      }
    }
  };

  return {
    init: app.methods.init
  };

}(window, document));;

APP.namespace('APP.Components');

APP.Components.CookieStatement = (function($, window) {
    "use strict";

    var app,
        el;

    function hasDependency() {
        return (typeof window.CookieConsent !== 'undefined');
    }

    app = {
        config : {
            table: 'table.CookieDeclarationTable',
            cookieBotID: '20bfe89c-2e17-4a08-867b-b6879c590f24'
        },
        methods : {
            init: function () {
                var _this = this;
                var contentPlaceholder = document.getElementById("cookiestatement");
                if(contentPlaceholder) {
                    var cookieDeclarationScript = document.createElement("script");
                    cookieDeclarationScript.type = "text/javascript";
                    cookieDeclarationScript.id = "CookiePolicy";
                    cookieDeclarationScript.src = "https://consent.cookiebot.com/"+app.config.cookieBotID+"/cd.js";
                    contentPlaceholder.appendChild(cookieDeclarationScript);
                    app.methods.create();
                }

                APP.trace('Log: [components|cookie-statement] Init component...');
            },
            create: function () {
                var loader,
                    timer = 400;

                var loader = setInterval(function () {
                    console.log(1);
                    if (!$('body').find(app.config.table) || !hasDependency()) return;

                    // another timeout because CookieConsent sometimes still 
                    //  causes an error when script hasn't finished loading...
                    setTimeout(function () {
                        app.methods.render();
                    }, timer);

                    clearInterval(loader);
                }, timer);
            },
            getWrapper: function () {
                return $('<div/>', {
                    'class': 'scroll-container'
                });
            },
            render: function () {
                var wrapper = app.methods.getWrapper();
                $('body').find(app.config.table).each(function () {
                    $(this)
                        .addClass('table table-striped table-small')
                        .wrap(wrapper);
                })
            }
        }
    };

    return {
        init : app.methods.init
    };

}(jQuery, window));;

APP.namespace('APP.Core.Components');

window.onYouTubeIframeAPIReady = function () {
    APP.Components.YoutubePlayer.onYouTubeIframeAPIReady();
};

APP.Components.YoutubePlayer = (function (window, document) {
    "use strict";

    var app,
        uniqueIndex = 0,
        jqObj;

    app = {
        methods: {
            init: function () {
                jqObj = $('[data-video-id]');

                if (!jqObj.length) return false;

                app.methods.bind();

                return true;
            },
            onYouTubeIframeAPIReady: function () {
                jqObj.each(function () {
                    var el = $(this),
                        videoID = $(this).data('video-id'),
                        videoW = $(this).data('video-width'),
                        videoH = $(this).data('video-height'),
                        backgroundImg = $(this).data('background-image'),
                        videoContainer = 'video-' + uniqueIndex++,
                        inner = $('<div/>', {
                            id: videoContainer
                        });

                    el.append(inner);
                    el.css({
                        'background-image': 'url($img)'.replace('$img', backgroundImg),
                        'padding-bottom': ((videoH / videoW * 100) + '%')
                    });

                    var player = new YT.Player(videoContainer, {
                        width: videoW,
                        height: videoH,
                        host: 'https://www.youtube-nocookie.com',
                        playerVars: {
                            autoplay: 0,
                            loop: 1,
                            controls: 1,
                            showinfo: 0,
                            autohide: 1,
                            modestbranding: 1,
                            rel: 0,
                            vq: 'hd1080'
                        },
                        videoId: videoID
                    });

                    el.data('video-obj', player);
                    el.parent().on('click', function (evt) {
                        var container = $(this),
                            playerInstance = container.find('.player').data('video-obj'),
                            videoData = playerInstance.getVideoData() || {},
                            videoId = (typeof videoData.video_id !== 'undefined' ? videoData.video_id : null),
                            videoTitle = (typeof videoData.title !== 'undefined' ? videoData.title : null),
                            videoDetailStr = '';

                        if (videoId && videoTitle) {
                            videoDetailStr = ': $videoTitle ($videoId)';
                            videoDetailStr = videoDetailStr.replace('$videoId', videoId);
                            videoDetailStr = videoDetailStr.replace('$videoTitle', videoTitle);
                        }

                        APP.Core.Tracking.set({
                            trackingType: 'event',
                            eventCategory: 'Video',
                            eventAction: 'Click',
                            eventLabel: 'Play video' + videoDetailStr
                        });

                        container.addClass('visible');
                        playerInstance.playVideo();
                    });
                });
            },
            bind: function () {
                var tag = document.createElement('script');
                tag.src = "https://www.youtube.com/iframe_api";

                var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            },
        }
    };

    return {
        init: app.methods.init,
        onYouTubeIframeAPIReady: app.methods.onYouTubeIframeAPIReady
    };

}(window, document));;
// BASED ON https://www.npmjs.com/package/plyr
APP.namespace('APP.Components');

APP.Components.Plyr = (function (window) {
  'use strict';

  var app;
  var jqObj;

  app = {

    methods: {
      /*
      * init
      *
      */
      init: function () {
        jqObj = $('[data-plyr-embed-id]');

        if (!jqObj.length) {
          return false;
        }
        app.methods.bind(function () {
          app.methods.ready();
        });

        return true;
      },

      ready: function () {
   
        /*eslint-disable */
        var players = Plyr.setup('.v-player', {
          title: 'Video',
          youtube: {
            cc_load_policy: 1,
            rel: 0,
            showinfo: 0,
            controls: 0,
            autohide: 1,
            modestbranding: 1,
            noCookie: true,
          },
          captions: {
            active: true,
            language: 'auto'
          },
          settings: ['captions']
        });

        /* eslint-enable */
        // assign poster to video element if defined
        for (var i = 0; i < players.length; i++) 
        {
          var poster = players[i].media.dataset.plyrPoster;
          if (poster) {
            players[i].poster = poster;
          }
          
          players[i].on('play', function(event) {
            var title = event.detail.plyr.config.title || 'No title';
            APP.Core.Tracking.set({
                trackingType: 'event',
                eventCategory: 'Video',
                eventAction: 'Click',
                eventLabel: 'Play video: ' + title
            });
          });

          players[i].on('ready', function(event) {
            // wait or title to be filled
            var interval = setInterval(function(e) {
              if(e.detail.plyr.config.title !== 'Video') {
                $(e.detail.plyr.elements.poster).append('<h3>' + e.detail.plyr.config.title + '</h3>');
                clearInterval(interval);
              }
            }, 500, event);
          });
        }

        window.players = players;
      },

      /*
      * bind events
      *
      */
      bind: function (callback) {
        // load API code asynchronously.
        var script = document.createElement('script');
        var head = document.getElementsByTagName('head')[0];

        script.src = 'https://cdn.plyr.io/3.5.6/plyr.polyfilled.js';

        if (script.readyState) { // only required for IE <9
          script.onreadystatechange = function () {
            if (script.readyState === 'loaded' || script.readyState === 'complete') {
              script.onreadystatechange = null;
              callback();
            }
          };
        } else { // Others
          script.onload = function () {
            callback();
          };
        }

        head.appendChild(script);
        return true;
      }
    }
  };

  return {
    init: app.methods.init
  };
}(window));
;

APP.namespace('APP.Components');

/**
 * This script adds background-image support to Slimmage...
 *
 */

APP.Components.ResponsiveBgImage = (function (window) {
  'use strict';

  /*
     * jquery element
     */

  var el = $('[data-background-image]');
  /*
     * widthStep (160) - Caching is impossible unless we limit the number of image variations.
     * The default, 160, gives us 160, 320, 480, 640, 800, 960, 1120, 1280, 1440, 1600, 1760, 1920, 2080(2048) - 13 variants, and keeps bandwidth waste very low.
     */

  var widthSteps = [160, 320, 480, 640, 800, 960, 1120, 1280, 1440, 1600, 1760, 1920, 2080];

  /*
     * images
     */

  var images = {};

  /*
     * app
     */

  var app;

  app = {
    events: {
      onResize: function () {
        app.methods.setImage();
      }
    },
    methods: {
      init: function () {
        if (!el.length) {
          return;
        }

        // could be more then one (carousel)
        el = $('[data-background-image]');
        app.methods.checkSlimmageVars();
        app.methods.setCenter();
        app.methods.setImage();
        app.methods.attach();

        return true;
      },
      getImageId: function (bg) {
        var p = bg.split('/');
        return p[1] + '_' + p[2];
      },
      showImage: function (imageId, bg, newWidthStep) {
        var jqObject = $(this);
        var image = images[imageId];
        var headerHeight = jqObject.height();
        var adjustedHeight = (newWidthStep * image.height / image.width);

        if (adjustedHeight < headerHeight) {
          // adjusted image height is smaller then the header height...
          adjustedHeight = Math.floor(headerHeight * 1.5);
          newWidthStep = Math.floor(newWidthStep * 1.5);

          bg = app.methods.adjustParameter(bg, 'width=', 'width=', newWidthStep);
          bg = app.methods.adjustParameter(bg, 'heightratio=', 'height=', adjustedHeight);
        } else if (newWidthStep <= 480) {
          // mobile or tablet mobile view...
          newWidthStep = Math.floor(newWidthStep * 1.5);
          bg = app.methods.adjustParameter(bg, 'width=', 'width=', newWidthStep);
        } else {
          // desktop / normal view...
          bg = app.methods.adjustParameter(bg, 'width=', 'width=', newWidthStep);
        }

        $('<img/>').attr('src', bg).on('load', function (e) {
          // append new bg and add class...
          jqObject.css({
            'background-image': 'url(' + bg + ')',
            'background-size': 'cover'
          });
          // remove to prevent memory leaks...
          $(this).remove();
        });
      },
      adjustParameter: function (inputString, param, replaceParam, appendValue) {
        var parts = inputString.split(param);

        if (parts.length > 1) {
          parts[1] = parts[1].substr(parts[1].indexOf('&'));
        }

        return parts.join(replaceParam + appendValue);
      },
      setImage: function () {
        var i;

        // iterate all images,
        // could be more then one for a carousel...
        el.each(function () {
          var newWidthStep = 0;
          var elWidth = $(this).get(0).clientWidth;

          // find slimmage widthStep...
          for (i = 0; i < widthSteps.length; i++) {
            if (widthSteps[i] >= elWidth) {
              newWidthStep = widthSteps[i];
              break;
            }
          }

          var jqObject = $(this);
          var bg = jqObject.data('background-image');
          var imageId = app.methods.getImageId(bg);

          if (typeof images[imageId] !== 'undefined') {
            app.methods.showImage.call(jqObject[0], imageId, bg, newWidthStep);
          } else {
            var data = jqObject.data();
            images[imageId] = {};
            images[imageId].height = data.imageHeight || 1600;
            images[imageId].width = data.imageWidth || 900;
            app.methods.showImage.call(jqObject[0], imageId, bg, newWidthStep);
          }
        });
      },

      checkSlimmageVars: function () {
        // check if image has slimmage vars, if not, add some
        // standard vars so slimmage works
        el.each(function () {
          var _this = $(this);
          var styleString = _this.data('background-image');
          if (styleString.indexOf('width=') === -1 && styleString.indexOf('height=') === -1) {
            _this.data('background-image', styleString + '?anchor=center&mode=crop&width=2000&quality=90&slimmage=true');
          }
        });
      },

      setCenter: function () {
        // could be more then one (carousel)
        el.each(function () {
          var _this = $(this);
          var styleString = _this.data('background-image');

          if (!styleString) return;

          var startIndex = styleString.indexOf('center=');
          var endIndex = styleString.indexOf('&', startIndex);

          // found 'center='
          if (startIndex !== -1) {
            // skip 'center=' string
            startIndex += 7;

            var str = styleString.substr(startIndex, endIndex - startIndex);

            if (str === 'center') {
              _this.css('background-position', 'center center');
            } else {
              var pos = str.split(',');

              if (pos.length === 2) {
                var bgy = (pos[0] * 100) + '%';
                var bgx = (pos[1] * 100) + '%';
                _this.css('background-position', bgx + ' ' + bgy);
              }
            }
          } else {
            _this.css('background-position', 'center center'); // default to center
          }
        });
      },
      attach: function () {
        $(window).on('resize orientationChanged', app.events.onResize);
      }
    }
  };

  return {
    init: app.methods.init
  };
}(window));
;

APP.namespace('APP.Components');


APP.Components.Notification = (function ($) {

  var app,
    notificationObj;


  app = {
    methods: {
      init: function () {

        APP.trace('Log: [components|notification] Instantiate component...');

        app.methods.build();
      },
      build: function () {
        if (app.methods.showNotification() == true) {
          $('body').append('<div id="notification"><p>Het woonprofiel en tijdelijke huurwoning account werkt vandaag niet door technisch onderhoud. U kunt hierdoor niet reageren op woningen.</p><button></button></div>');
          $('#notification button').on('click', function (e)
          {
            e.preventDefault();
            app.methods.discardNotification();
          });
        }
      },
      showNotification: function () {
        return localStorage.getItem("showNotification") !== "false";
      },
      discardNotification: function () {
        localStorage.setItem("showNotification", "false");
        $('#notification').hide();
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    },
    openFromGTM: function () {
      app.methods.init();
    }
  };

}($));;

APP.namespace('APP.Core');

APP.Core.Bootstrap = (function ($) {
  "use strict";

  var app;

  app = {
    config: {
      version: 0
    },
    methods: {
      set: function (options) {
        $.extend(app.config, options);
      },
      onPanelReady: function () {
        APP.trace('Log: [core|bootstrap] onPanelReady | Update blocks and components...');

        APP.Block.EqualHeight.update();
        APP.Components.Panel.update();
        APP.Form.FilterWoonRuimte.update();
        APP.Form.AutoCompleteSearchBox.init();
        APP.Form.AutoCompleteStreet.init();

        setTimeout(function () {
          APP.Form.SearchRealEstate.togglePanel();
        }, 200);

        initCustomCheckboxes();

        if (typeof PlaatsStadsdeel !== 'undefined') {
          PlaatsStadsdeel.initMultiSelect();
        }
      },
        init: function (options) {

            // https://api.jquery.com/jquery.holdready/
            // fix vue virtual dom issue
            $.holdReady(true)

        app.methods.set(options);

        APP.trace('Log: [core|bootstrap] Instantiate application bootstrap...');
        APP.trace('Log: [core|bootstrap] JavaScript library version ' + app.config.version);

        app.methods.initDevices();
        app.methods.initFaq();
        app.methods.initTracking();
        app.methods.initComponents();
        app.methods.initForm();
        app.methods.initFrontend();
        app.methods.initBlock();
        app.methods.initPlugin();
        app.methods.initHelpers();
        app.methods.initUtilities();

        initCustomCheckboxes();
        if (typeof PlaatsStadsdeel !== 'undefined') {
          PlaatsStadsdeel.initMultiSelect();
        }
      },
      initDevices: function () {
        if (APP.Core.DeviceManager.isMobile() === true) {
          $('html').addClass('isTouch');
        }
        if (APP.Core.DeviceManager.isDesktop() === true) {
          $('html').addClass('isDesktop');
        }
        if (APP.Core.DeviceManager.isIE() === 9) {
          $('html').addClass('isIE9');
        }
      },
      initFaq: function () {
        var hashValue,
          element;

        hashValue = window.location.hash.substr(1);
        hashValue = hashValue.toString().toLowerCase().replace(' ', '-');

        if (typeof hashValue === 'string' && hashValue !== '') {
          element = $('a[name="' + hashValue + '"]');
          if (!element.length) element = $('a[id="' + hashValue + '"]');
          if (element.length) {
            element.trigger('click');
            $('html, body').animate({
              scrollTop: element.offset().top
            }, 500);
          }
        }

        // find 'wie doet wat' expanded items (has class=expanded set by back-end
        var expandItem = $('.expanded [data-toggle=collapse]');
        if (expandItem.length > 0) {
          expandItem.trigger('click');
          $('html, body').animate({
            scrollTop: expandItem.offset().top
          }, 500);
        }

      },
      initTracking: function () {
        APP.Core.Tracking.init();
      },
      initComponents: function () {

        if ($('.panel-filter').length) {
          APP.Components.Panel.init();
        }
        
        if ($('[data-component="gallery"]').length) {
          APP.Components.Gallery.init();
        }

        if ($('.tab-list').length) {
          APP.Components.TabList.init();
        }

        APP.Components.Chat.init();

        APP.Components.TabPanelRealEstate.init();

        APP.Components.ExpandableList.init();

        APP.Components.Employees.init();

        APP.Components.Tabs.init();

        if ($('#vacancy-slider').length) {
          APP.Components.VacancySlider.init();
        }
        if ($('[data-toggle="popover"]').length) {
          APP.Components.BSPopOver.init();
        }

        APP.Components.PasswordStrength.init();

        if ($('.tab-panel').length) {
          APP.Components.TabPanel.init();
        }

        APP.Components.Click.init();
        APP.Components.BackButton.init();
        APP.Components.ConfirmButton.init();

        APP.Components.CookieBar.init();
        APP.Components.CookieStatement.init();

          APP.Components.YoutubePlayer.init();
          APP.Components.Plyr.init();
          APP.Components.ResponsiveBgImage.init();
       // APP.Components.Notification.init();
      },
      initForm: function () {
        APP.Form.DateRange.init();
        APP.Form.FilterWoonRuimte.init();
        APP.Form.AutoCompleteSearchBox.init();
        APP.Form.AutoCompleteStreet.init();
        APP.Form.AanmeldenNieuwsbriefHuren.init();
        APP.Form.Emandate.init();
        APP.Form.Woonwensen.init();
        APP.Form.Registreer.init();
        APP.Form.SearchRealEstate.init();
        APP.Form.Documenten.init();
        APP.Form.Doelgroepen.init();
        APP.Form.HurenJaarinkomen.init();
        APP.Form.WoningRuil.init();
        APP.Form.HuurParkeerruimteOpzeggen.init();
        APP.Form.Huurverlaging.init();
        APP.Form.TijdelijkeVerhuur.MijnGegevens.init();
        APP.Form.TijdelijkeVerhuur.Reageer.init();

        APP.Form.VSH.Login.init();
        APP.Form.VSH.UwSituatie.init();
        APP.Form.VSH.MijnGegevens.init();

        if (typeof (APP.Form.AutoCompleteWDW) !== 'undefined') APP.Form.AutoCompleteWDW.init();

        APP.Form.Element.AutoFillAddress.init();
        APP.Form.Element.File.init();
        APP.Form.Element.OpenOption.init();
        APP.Form.Element.RangeSelector.init();
        APP.Form.Element.Select.init();
      },
      initFrontend: function () {
        APP.Frontend.Navigation.init();
        APP.Frontend.Bottom.init();
        APP.Frontend.Footer.init();
      },
      initBlock: function () {
        APP.Block.Column.init();
        APP.Block.EqualHeight.init();
        APP.Block.Featured.init();
      },
      initPlugin: function () {
        APP.Plugin.Align.init();
        APP.Plugin.ExternalLink.init();
      },
      initHelpers: function () {
        APP.Helper.placeholder.create({
          element: $('[data-helper="placeholder"]')
        });
      },

      initUtilities: function () {
        if ($('[data-util="datepicker"]').length) {
          APP.Utilities.Datepicker.attach();
        }
        if ($('[data-util="print"]').length) {
          APP.Utilities.Print.attach();
        }
        if ($('[data-src-default]').length) {
          APP.Utilities.HiddenImage.attach();
        }

      }
    }

  };

  return {
    init: function (options) {
      app.methods.init(options);
    },
    onPanelReady: function () {
      app.methods.onPanelReady();
    }
  };

}($));
;

APP.namespace('APP.Core');

APP.Core.DeviceManager = (function($, window) {
    "use strict";
	
	var DeviceManager;
	
	DeviceManager = {
		hasFlex : function (){
			var s = document.body || document.documentElement;
			return ( s.style.webkitFlexWrap == '' || s.style.msFlexWrap == '' || s.style.flexWrap == '' );
		},
		isiPad : function () {
			return (navigator.platform.match(/iPad/i));
		},
		isiPod : function () {
			return (navigator.platform.match(/iPod/i));
		},
		isiPhone : function () {
			return (navigator.platform.match(/iPhone/i));
		},
		isMac : function () {
			return (navigator.platform.match(/Mac/i));
		},
		isChrome : function () {
			return (navigator.userAgent.match(/Chrome/i)) ? !DeviceManager.isAndroid() : false;
		},
		isSafari : function () {
			return (navigator.userAgent.match(/Safari/i)) ? !DeviceManager.isChrome() : false;
		},
		isAndroid: function() {
			return navigator.userAgent.match(/Android/i);
		},
		isIE : function () {
			var ua;

			ua = navigator.userAgent.toLowerCase();

			return (ua.indexOf('msie') != -1) ? parseInt(ua.split('msie')[1]) : false;
		},
		isBlackBerry: function() {
			return navigator.userAgent.match(/BlackBerry/i);
		},
		isiOS: function() {
			return navigator.userAgent.match(/iPhone|iPad|iPod/i);
		},
		iOSVersion : function () {
			return (DeviceManager.isiOS()) ? navigator.appVersion.match(/OS (.)/i)[1] : 0;
		},
		isOpera: function() {
			return navigator.userAgent.match(/Opera Mini/i);
		},
		isWindows: function() {
			return navigator.userAgent.match(/IEMobile/i);
		},
		isMobile : function () {
			var a;
				
			a = navigator.userAgent||navigator.vendor||window.opera;
			a = a.toLowerCase();
			
			if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(a) ) {
				return true;
			}
			
			return false;			
		},
		isMobileAll : function () {
			var a;
			
			a = navigator.userAgent||navigator.vendor||window.opera;
			a = a.toLowerCase();
			
			return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)));			
		},
		isDesktop : function () {
			return !DeviceManager.isMobile() ? true : false;
			//Removed window.screenX != 0
			// failed in Chrome...
		}
	};

    return {
		hasFlex : function () {
			return DeviceManager.hasFlex();
		},
		isiPad : function () {
			return DeviceManager.isiPad();
		},
		isAndroid : function () {
			return DeviceManager.isMobile();
		},
		isBlackBerry : function () {
			return DeviceManager.isBlackBerry();
		},
		isiPhone : function () {
			return DeviceManager.isiPhone();
		},
		isiOS : function () {
			return DeviceManager.isiOS();
		},
		isOpera : function () {
			return DeviceManager.isOpera();
		},
		isIE : function () {
			return DeviceManager.isIE();
		},
		isWindows : function () {
			return DeviceManager.isWindows();
		},
		isMobile : function () {
			return DeviceManager.isMobile();
		},
		isMobileAll : function () {
			return DeviceManager.isMobileAll();
		},
		isDesktop : function () {
			return DeviceManager.isDesktop();
		}
    };

}($, window));;

APP.namespace('APP.Core');

APP.Core.Tracking = (function ($) {
    "use strict";

    var app;

    app = {
        events: {
            onButtonClick: function (evt) {
                var el = $(this),
                    href = evt.currentTarget.href,
                    gaLabel = 'Outbound link: ' + el.text() + ' (' + href + ')',
                    openingInNewWindow = evt.target.target && !evt.target.target.match(/^_(self|parent|top)$/i) || evt.ctrlKey || evt.shiftKey || evt.metaKey;

                if (!openingInNewWindow) {
                    evt.preventDefault();
                }

                app.methods.set({
                    trackingType: 'event',
                    eventCategory: 'tracked link',
                    eventAction: 'click',
                    eventLabel: gaLabel,
                    hitCallback: openingInNewWindow ? null : function () {
                        window.location.href = href;
                    },
                    hitCallbackFail: openingInNewWindow ? null : function () {
                        window.location.href = href;
                    }
                });

                return openingInNewWindow;
            }
        },
        methods: {
            init: function () {
                APP.trace('Log: [core|tracking] Instantiate GA Tracking...');

                app.methods.track_ga_events_forms();
                app.methods.attach();
            },
            set: function (props) {
                var properties;

                window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({
                    'event': 'trackEvent', // GTM event
                    'eventCategory': props.eventCategory,
                    'eventAction': props.eventAction,
                    'eventLabel': props.eventLabel,
                    'eventCallback': typeof props.hitCallback === 'function' ? props.hitCallback : null,
                    'eventCallbackFail': typeof props.hitCallbackFail === 'function' ? props.hitCallbackFail : null
                });

                return true;
            },
            send_profileevent: function (profile, zipcode) {
                var default_zipcode;

                default_zipcode = "1234 AB";

                app.methods.set({
                    trackingType: 'event',
                    eventCategory: 'Profiles',
                    eventAction: 'Set profile',
                    eventLabel: profile
                });

                if (zipcode !== default_zipcode) {
                    app.methods.set({
                        trackingType: 'event',
                        eventCategory: 'Profiles',
                        eventAction: 'Set zipcode',
                        eventLabel: zipcode
                    });
                }
            },
            track_ga_events_forms: function () {
                var action,
                    path = $(location).attr('pathname'),
                    flag = false;

                // Umbraco form tracking
                if ($('.umbraco-forms-submitmessage').length > 0) {
                    action = 'Formulier bedank pagina';
                    flag = true;
                } else if ($('.umbraco-forms-form input[type="submit"]').length > 0) {
                    action = 'Formulier pagina';
                    flag = true;
              
                } else {
                // legacy form tracking
                    if ($('input[value="Volgende"]').length > 0) {
                        action = 'Formulier pagina';
                        flag = true;
                    } else if ($('input[value="Versturen en afronden"]').length > 0) {
                        action = 'Formulier bevestig pagina';
                        flag = true;
                    } else if ($(location).attr('search') == "?status=succes") {
                        action = 'Formulier bedank pagina';
                        flag = true;
                    }
                }
       
                if (flag === true) {
                    app.methods.set({
                        trackingType: 'event',
                        eventCategory: 'GA_FORM_TRACKING',
                        eventAction: action,
                        eventLabel: path
                    });
                }
            },
            attach: function () {
                $('a[href*="mijn.eigenhaard.nl"]')
                    .off('click', app.events.onButtonClick)
                    .on('click', app.events.onButtonClick);

                // Both events are Profile stuff, going to be removed in next release...
                $("#ehHelpHeader_btnSetProfile").mousedown(function () {
                    var profile = $("div.profile_selector span.center").html();
                    var zipcode = $("#ehHelpHeader_divPostal input#postcode").val();
                    app.methods.send_profileevent(profile, zipcode);
                });

                $("#ehHelpBox_btnSetProfile").mousedown(function () {
                    var profile = $("div#header #ehHelpBox_pnlProfileChoice div.select-area span.center").html();
                    var zipcode = $("input#ehHelpBox_postcode").val();
                    app.methods.send_profileevent(profile, zipcode);
                });
            }
        }
    };

    return {
        init: app.methods.init,
        set: app.methods.set
    };

}($));;

APP.namespace('APP.Form.Element');

APP.Form.Element.AutoFillAddress = (function(){

    var app,
        PRO6PP_AUTH_KEY = 'TjGC8TzkHYnrYHpz',
        PRO66PP_ENABLED = true,
        requestData = {
            postcode: '',
            huisnummer: ''
        },
        cityObj = {
            parent : '',
            placeholder : '',
            input : ''
        },
        streetObj = {
            parent: '',
            placeholder: '',
            input: ''
        };

    app = {
        events : {
            update: function () {
                var fieldset = $(this).parents('fieldset:eq(0)');
                
                requestData.postcode = fieldset.find('input.postcode').val().replace(" ", "");
                requestData.huisnummer = fieldset.find('input.huisnummer').val();

                if (requestData.postcode.length !== 6 || requestData.huisnummer.length === 0) {
                    return;
                }

                app.methods.processRequest(fieldset);
            }
        },
        methods : {
            init : function () {
                if (!PRO66PP_ENABLED) {
                    return;
                }

                var legacyFormAutoFill = $('[data-autofill-address]').length;
                var umbracoFormAutoFill = $('.umbraco-forms-field.postcode').length;

                if (!legacyFormAutoFill && !umbracoFormAutoFill) {
                    return;
                }

                // adds the required classes to the Umbraco form fields to make the script work
                if (umbracoFormAutoFill) {

                    $('fieldset').each(function() {
                        var postcodeField = $(this).find('.umbraco-forms-field.postcode');
                        var huisnummerField = $(this).find('.umbraco-forms-field.huisnummer');
                        var straatnaamField = $(this).find('.umbraco-forms-field.straatnaam');
                        var plaatsnaamField = $(this).find('.umbraco-forms-field.plaatsnaam');
    
                        if (postcodeField.length && huisnummerField.length && straatnaamField.length && plaatsnaamField.length) {

                            // check if postcode fields and 
                            var fieldIndex1 = postcodeField.index() == huisnummerField.index() - 1;
                            var fieldIndex2 = straatnaamField.index() == plaatsnaamField.index() - 1;
                            if(fieldIndex1 && fieldIndex2) {
                                postcodeField.find('input').addClass('postcode');
                                huisnummerField.find('input').addClass('huisnummer');
                                straatnaamField.find('input').addClass('straatnaam');
                                plaatsnaamField.find('input').addClass('plaatsnaam');
                            }
                        }
                    });
                }

                app.methods.render();
                app.methods.attach();
            },
            render : function () {
                // loop items and create placeholders...


                $.each($('input.straatnaam, input.plaatsnaam'), function(i, item) {
                    $(item).hide();

                    var el = $('<div/>', {
                        'class' : 'input-disabled-placeholder',
                        'text' : $(this).val()
                    });

                    el.prependTo( $(this).parent() );
                });

                // initial setup...
                $('input.postcode').each(app.events.update);
            },
            getRequestData : function () {
                var url = '';

                url += location.protocol;
                url += "//api.pro6pp.nl/v1/autocomplete";

                // because we changed the api method from GET to POST,
                //  we are returning an object with data instead of an url string...
                // url += "?auth_key=" + PRO6PP_AUTH_KEY;
                // url += "&nl_sixpp=" + requestData.postcode;
                // url += "&streetnumber=" + requestData.huisnummer;
                // url += "&format=json&pretty=True&callback=?";
                
                return {
                    url : url,
                    data : {
                        auth_key : PRO6PP_AUTH_KEY,
                        nl_sixpp: requestData.postcode,
                        streetnumber: requestData.huisnummer
                    }
                };
            },

            /*
             *
             * GD:
             *  maybe add this to the endpoint call, but maybe it will add more problems than it solves?
             *  var extension = $('input.toevoeging').val();
             *  &extension=extension
             *
             */

            processRequest: function (fieldset) {
                var data = app.methods.getRequestData();

                // store city object references locally...
                cityObj.parent = fieldset.find('input.plaatsnaam').parent();
                cityObj.placeholder = cityObj.parent.find('.input-disabled-placeholder');
                cityObj.input = cityObj.parent.find('input');

                // store street object references locally...
                streetObj.parent = fieldset.find('input.straatnaam').parent();
                streetObj.placeholder = streetObj.parent.find('.input-disabled-placeholder');
                streetObj.input = streetObj.parent.find('input');

                // get data...
                $.ajax({
                    method : "POST",
                    url : data.url,
                    data : data.data,
                    success : app.methods.ajaxHandler,
                    dataType : 'json'
                });
            },
            ajaxHandler : function (data) {
                var status = data.status,
                    result,
                    i;

                app.methods.toggleFields(status);

                if (status !== 'ok') {
                    return;
                }

                result = data.results;

                if (result.length === 1) {
                    cityObj.placeholder.text( result[0].city );
                    streetObj.placeholder.text( result[0].street );

                    cityObj.input.val( result[0].city );
                    streetObj.input.val( result[0].street );

                    return;
                }

                for (i = 0; i < data.results.length; i++) {
                    var streetNrs = result[i].streetnumbers;

                    if (app.methods.numberMatchesStreetNrs(requestData.huisnummer, streetNrs)) {
                        cityObj.placeholder.text( result[i].city );
                        streetObj.placeholder.text( result[i].street );

                        cityObj.input.val( result[i].city );
                        streetObj.input.val( result[i].street );

                        break;
                    }
                }
            },
            numberMatchesStreetNrs : function (nr, streetNrsStr) {
                var nrMatch = nr.match(/^[0-9]+/),
                    ranges,
                    nrs,
                    nrsInt,
                    r;
                
                if (!nrMatch) {
                    return false;
                }

                ranges = streetNrsStr.split(';');

                for (r = 0; r < ranges.length; r++) {
                    nrs = ranges[r].split('-');
                    nrsInt = nrMatch[0];

                    if (nrs.length === 1) {
                        if (parseInt(nrs[0], 10) == nrsInt) {
                            return true;
                        }
                    } else {
                        if (nrsInt >= parseInt(nrs[0], 10) && nrsInt <= parseInt(nrs[1], 10)) {
                            return true;
                        }
                    }
                }

                return false;
            },
            toggleFields : function (status) {
                // reset city object values...
                cityObj.input.val('');
                cityObj.placeholder.text('');

                // reset placeholder object values...
                streetObj.input.val('');
                streetObj.placeholder.text('');

                // toggle on status...
                if (status !== 'ok') {
                    cityObj.placeholder.hide();
                    cityObj.input.show();

                    streetObj.placeholder.hide();
                    streetObj.input.show();
                } else {
                    cityObj.placeholder.show();
                    cityObj.input.hide();

                    streetObj.placeholder.show();
                    streetObj.input.hide();
                }
            },
            attach : function () {
                $('input.huisnummer, input.postcode')
                    .off('change', app.events.update)
                    .on('change', app.events.update);
            }
        }
    };

    return {
        init : app.methods.init
    };

}());;

APP.namespace('APP.Form.Element');

APP.Form.Element.File = (function(){

    var app,
        inputObj;

    app = {
        templates : {
            getSpan : function (c) {
               return $('<span/>', {
                   'class' : c
               })
            }
        },
        events : {
            eventHandler : function (evt) {
                evt.preventDefault();

                var jqObject = $(this),
                    focusClass = 'focus',
                    type = evt.type;

                switch (type) {
                    case 'focus':
                        jqObject.next('.custom-file-upload').addClass(focusClass);
                        break;
                    case 'blur':
                        jqObject.next('.custom-file-upload').removeClass(focusClass);
                        break;
                    case 'change':
                        app.methods.appendFileName.call(this);
                        break;
                }
            },
            onReset : function () {
                app.methods.create.call(this);
            }
        },
        methods : {
            init : function () {
                inputObj = $('.input-container.input-file input[type="file"]');

                if (!inputObj.length) {
                    return;
                }

                APP.trace('Log: [form.element.file] Instantiate element...');

                app.methods.render();
                app.methods.attach();
            },
            render : function () {
                inputObj.addClass('maxfilesize');

                inputObj.each(function(){
                    app.methods.create.call(this);
                });
            },
            create : function () {
                var inputSelector = $(this),
                    inputValue = inputSelector.data('original-file') || '';

                inputSelector
                    .val('')
                    .next('.custom-file-upload')
                    .text(inputValue);

                if (inputSelector.prev().hasClass('file-status')) {
                    inputSelector.prev().remove();
                }
            },
            appendFileName : function () {
                var el = $(this),
                    inputValue = el.val().split('C:\\fakepath\\').join(''),
                    spanObj;

                if (!inputValue.length) {
                    return;
                }

                el.next('.custom-file-upload').text(inputValue);

                spanObj = app.templates.getSpan('file-status status-ok');
                spanObj.insertBefore(el);
            },
            attach : function () {
                inputObj
                    .off('focus blur change', app.events.eventHandler)
                    .on('focus blur change', app.events.eventHandler);

                inputObj
                    .off('file.reset', app.events.onReset)
                    .on('file.reset', app.events.onReset);
            }
        }
    };

    return {
        init : app.methods.init
    };

}());;

APP.namespace('APP.Form');

APP.Form.Element.Select = (function (window, document) {

  var app,
    jqObj;

  app = {
    methods: {
      init: function () {
        jqObj = $('.scfDropListGeneralPanel > select');
        if (!jqObj.length) {
          return;
        }

        APP.trace('Log: [form|element|select] Instantiate component...');

        app.methods.create();
      },
      create: function () {
        var wrapper = $('<div/>', {
          'class': 'select-container'
        });

        jqObj.wrap(wrapper);
      }
    }
  };

  return {
    init: app.methods.init
  };

}(window, document));;

/**
 *
 * APP.Form.Element.OpenOption
 *
 * Component to toggle elements from an input field (eg. radio, checkbox),
 *  based on a #id passed as data attribute: data-open-option="target_element_id"...
 *
 * Toggle target:
 *  <div id="target_element_id"> = show or hide
 *  <input id="target_element_id"> = enable or disable
 *
 * Additional note:
 *  1. Toggle multiple targets with a pipe, eg. target_element_1|target_element_2;
 *  2. Also possible to use a input[type="radio"] list;
 *
 * @author  K van den Broek     <k.vandenbroek@uselab.com>
 * @return  init                function to instantiate the component...
 *
 * --------------------------------------------------------------------------------------------
 *
 * Example 1) Single checkbox element to toggle a <div> element:
 *      <input type="checkbox" data-open-option="target_element_id" />
 *      <div id="target_element_id"></div>
 *
 * Example 2) Single checkbox element to toggle multiple <div> elements:
 *      <input type="checkbox" data-open-option="target_element_id_1|target_element_id_2" />
 *      <div id="target_element_id_1"></div>
 *      <div id="target_element_id_2"></div>
 *
 * Example 3) Single checkbox element to toggle a disabled input[type="text"] element:
 *      <input type="checkbox" data-open-option="target_element_id" />
 *      <input type="text" disabled id="target_element_id" />
 *
 * Example 4) Radio button list, eg. input[type="radio"],
 *  where the 2nd radio button hides the target <div> again:
 *      <input type="radio" name="list_name" data-open-option="target_element_id_1" />
 *      <input type="radio" name="list_name" />
 *      <div id="target_element_id_1"></div>
 *
 */

APP.namespace('APP.Form.Element');

APP.Form.Element.OpenOption = (function(){

    var app,
        element;

    app = {
        events : {
            eventHandler : function () {
                var el = $(this),
                    type = app.methods.getType(el);

                if (type === 'radio') {
                    el = $('input[name="'+ el.attr('name') +'"]');
                }

                app.methods.process(el);
            }
        },
        methods : {
            init : function () {
                element = $('[data-open-option]');

                if (!element.length) {
                    return;
                }

                APP.trace('Log: [form.element.open-option] Instantiate element...');
                APP.Form.Element.OpenOption.active = true;

                app.methods.render(function(){
                    element = $('[data-open-option]');

                    var d = [];

                    element.each(function(){
                        var el = $(this),
                            type = app.methods.getType(el),
                            name = 'input:radio[name="'+ el.attr('name') +'"]';

                        if (type === 'radio' && d.indexOf(name) === -1) {
                            d.push( name );
                        }
                    });

                    var searchString = '[data-open-option]';

                    if (d.length) {
                        searchString += ',' + d.join(',')
                    }
                    element = $(searchString);

                    app.methods.process();
                    app.methods.attach();
                });
            },
            getType : function (el) {
                return el.attr('type') || (el.length ? el.get(0).tagName.toLowerCase() : '');
            },
            render : function (callback) {
                element.each(function(){
                    var el = $(this);

                    if (app.methods.getType(el) === 'div') {
                        var jqObject = el.find('input:eq(0), select:eq(0)');

                        if (jqObject.length) {
                            jqObject.attr('data-open-option', el.data('open-option'));
                            el.removeAttr('data-open-option');
                        }
                    }
                });

                if (typeof callback === 'function') {
                    callback.call(undefined);
                }
            },
            process : function (selection) {
                APP.trace('Log: [form.element.open-option] process(selection=' + selection + ')');
                if (typeof selection === 'undefined') {
                    selection = element;
                }

                var elActive = null
                selection.each(function(){
                    var el = $(this),
                        type = app.methods.getType(el),
                        toggleOption = el.data('open-option'),
                        target = (typeof toggleOption !== 'undefined' ? toggleOption.split('|') : ''),
                        isActive;

                    if (!target.length) {
                        return;
                    }

                    if (type === 'select') {
                        isActive = el.find('option:selected').val() === el.data('option-value');
                    } else {
                        isActive = el.prop('checked');
                    }
                    if (isActive) {
                        elActive = target;
                    } else {
                        app.methods.toggle(target, isActive);
                    }
                });
                if (elActive != null) {
                    app.methods.toggle(elActive, true);
                }
            },
            toggle: function (target, isActive) {
                var accepted_types = [
                    'div',
                    'fieldset'
                ];

                $.each(target, function(k,v){
                    var el = $('[data-open-target="' + v + '"]').last(),
                        type = app.methods.getType(el);

                    if (!el.length) {
                        return;
                    }

                    if (!isActive) {
                        el.css({
                            'position': 'absolute', 'right': '9000px'
                        });
                    } else {
                        el.css({
                            'position': 'relative', 'right': '0px'
                        });
                    }
                });
            },
            attach : function () {
                element
                    .off('change', app.events.eventHandler)
                    .on('change', app.events.eventHandler);
            }
        }
    };

    return {
        init : app.methods.init,
        active : false
    };

}());;

APP.namespace('APP.Form.Element');

APP.Form.Element.RangeSelector = (function(){

    var app,
        jqObj;

    app = {
        events : {

            /*
             * onChange()
             *  Change event handler for the select selector...
             *
             */

            onChange : function () {
                var type = $(this).data('range-selector');

                switch (type) {
                    case 'from':
                        app.methods.changeFromSelector.call(this);
                        break;
                    case 'to':
                        app.methods.changeToSelector.call(this);
                        break;
                }
            }
        },
        methods : {

            /*
             * init()
             *  Instantiate component...
             *
             */

            init : function () {
                jqObj = $('select[data-range-selector]');

                if (!jqObj.length) {
                    return;
                }

                APP.trace('Log: [form.element.range-selector] Instantiate element...');

                app.methods.render();
                app.methods.attach();
            },

            /*
             * render()
             *  Render view, change last value when values are the same.
             *  In timeout because field options needs to be set first, which is done by JS in some cases.
             *
             *  Example: When 'from' and 'to' are both zero set to 'from' to max value...
             *
             */

            render : function () {
                setTimeout(function(){
                    $('[data-range-selector="to"]').each(function() {
                        var parent = app.methods.getParentSelector( $(this) ),
                            fromSelector = parent.find('select[data-range-selector="from"]'),
                            fromValue = app.methods.getValue( fromSelector.val() ),
                            toValue = app.methods.getValue( $(this).val() ),
                            firstValue = app.methods.getValue( fromSelector.find('option').first().val() );

                        if (toValue === firstValue && fromValue === firstValue) {
                            var lastValue = $(this).find('option').last().val();
                            $(this).val(lastValue)
                        }
                    });
                }, 0);
            },

            /*
             * getValue()
             *  Return a valid integer value...
             *
             * @param   v       input integer value
             * @return  value   output integer value (valid)
             *
             */

            getValue : function (v) {
                var value = parseInt(v, 10);
                return (isNaN(value) ? 0 : value);
            },

            /*
             * getParentSelector()
             *  Return parent object based on a selector...
             *
             * @param   el      jquery selector
             * @return  parent  parent .form-row or .form-group selector
             *
             */

            getParentSelector : function (el) {
                return (el.closest('.form-row').length ? el.closest('.form-row') : el.parents('.form-group-inline:eq(0)'));
            },

            /*
             * changeFromSelector()
             *  Change the 'from' select value based on the 'to' select value...
             *  Increase value of 'to' when possible...
             *
             */

            changeFromSelector : function () {
                var parent = app.methods.getParentSelector( $(this) ),
                    toSelector = parent.find('select[data-range-selector="to"]'),
                    toValue = app.methods.getValue( toSelector.val() ),
                    fromValue = app.methods.getValue( $(this).val() );

                if (fromValue >= toValue) {
                    var nextValue = $(this).find('option:selected').next().val();

                    if (!nextValue) {
                        nextValue = $(this).find('option').last().val();
                    }

                    toSelector.val(nextValue);
                }
            },

            /*
             * changeToSelector()
             *  Change the to select value based on the from select value...
             *  Decrease value of 'from' when possible...
             *
             */

            changeToSelector : function () {
                var parent = app.methods.getParentSelector( $(this) ),
                    fromSelector = parent.find('select[data-range-selector="from"]'),
                    fromValue = app.methods.getValue( fromSelector.val() ),
                    toValue = app.methods.getValue( $(this).val() );

                if (toValue <= fromValue) {
                    var prevValue = $(this).find('option:selected').prev().val();

                    if (!prevValue) {
                        prevValue = $(this).find('option').first().val();
                    }

                    fromSelector.val(prevValue);
                }
            },

            /*
             * attach()
             *  Bind DOM events...
             *
             */

            attach : function () {
                jqObj
                    .off('change', app.events.onChange)
                    .on('change', app.events.onChange);

                // custom event to (re)render view in dynamic cases,
                //  which is triggered in '/components/tab-panel.js' [line 112]
                $(document)
                    .off("tab.panel.change", app.methods.render)
                    .on("tab.panel.change", app.methods.render);
            }
        }
    };

    return {
        init : app.methods.init
    };

}());;

APP.namespace('APP.Form.TijdelijkeVerhuur');

APP.Form.TijdelijkeVerhuur.MijnGegevens = (function(document, window){

	var app,
		jqSelector = 'input#content_0_partner_toevoegen',
		FIELD = {
			rfValGeslachtPartner : 'input[name="content_0$rblGeslachtPartner"]',
			rfValVoorlettersPartner : 'input#content_0_txtVoorlettersPartner',
			rfValAchternaamPartner : 'input#content_0_txtAchternaamPartner',
			rfValAkkoord : 'input#content_0_cbValAkkoord',
			rfValInkomenPartner : 'input#content_0_txtInkomenPartner',
			rfValRegios : 'table#content_0_chkblRegios',
			rfValGeboortedatumPartner : 'input[name="content_0$txtGeboortedatumPartner"]'
        },
        regex = {
            rfValVoorlettersPartner: /^.{0,10}$/
        };

    app = {
    	events : {
    		onChange : function () {
    			var s = $(this).data('reference'),
                    errorSelector = $('#content_0_' + s),
                    regexSelector = $('#content_0_' + s.replace('rfVal', 'reExpr')),
					fieldSelector = FIELD[s];

				if (app.methods.isValid(fieldSelector)) {
					errorSelector.hide();
				} else {
					errorSelector.show();
                }

                if (regexSelector.length) {
                    if (app.methods.isRegexValid(s)) {
                        regexSelector.hide();
                    } else {
                        regexSelector.show();
                    }
                }
            },
            onClick: function () {
                app.methods.validateForm();
            }
	    },
    	methods : {
    		init : function () {
				if (!$('[data-form="tijdelijke-verhuur|mijn-gegevens"]').length) {
					return;
				}

				APP.trace('Log: [form|tijdelijke-verhuur|mijn-gegevens] Instantiate form...');

				app.methods.attach();
			},
    		isChecked : function () {
    			return $(jqSelector).is(':checked');
            },
            isRegexValid: function (s, partner) {
                if (partner && !app.methods.isChecked()) {
                    return true;
                }

                var ref = FIELD[s],
                    element = $(ref),
                    value = element.val(),
                    expr = regex[s];

                return expr.test(value);
            },
			isValid : function (s, partner) {
				if (partner && !app.methods.isChecked()) {
					return true;
				}

				var element = $(s),
					type = element.attr('type') || element[0].nodeName.toLowerCase(),
					isValid = false;

				switch (type) {
					case 'text':
						var minLength = element.data('length-min') || 1;
						isValid = element.val().toString().length >= minLength;
						break;
					case 'radio':
					case 'checkbox':
						isValid = element.filter(':checked').length > 0;
						break;
					case 'table':
						isValid = element.find('input[type="checkbox"]').filter(':checked').length > 0;
						break;
				}

				return isValid;
            },
            validateForm : function() {
                var errorMessage = $('.error-message:not(.all):visible');

                if (errorMessage.length > 0) {
                    $('.error-message.all').show();
                } else {
                    $('.error-message.all').hide();
                }  
            },
		    attach : function () {
				var i;

				for (i in FIELD) {
					if (FIELD.hasOwnProperty(i)) {
						$(FIELD[i])
							.attr('data-reference', i)
							.off('change', app.events.onChange)
							.on('change', app.events.onChange);
					}
                }

                $('[data-form="tijdelijke-verhuur|mijn-gegevens"]').parent().parent().find('input')
                    .off('change', app.events.onClick)
                    .on('change', app.events.onClick);

                $('#content_0_Button1')
                    .off('click', app.events.onClick)
                    .on('click', app.events.onClick);
		    }
		},
		validator : {
			rfValGeslachtPartner : function(sender, e){
				e.IsValid = app.methods.isValid( FIELD['rfValGeslachtPartner'], true );
			},
			rfValVoorlettersPartner : function(sender, e){
				e.IsValid = app.methods.isValid( FIELD['rfValVoorlettersPartner'], true );
            },
            reExprPartnerVoorletters: function (sender, e) {
                e.IsValid = app.methods.isRegexValid('rfValVoorlettersPartner', true );
            },
			rfValAchternaamPartner : function(sender, e){
				e.IsValid = app.methods.isValid( FIELD['rfValAchternaamPartner'], true );
			},
			rfValAkkoord : function(sender, e){
				e.IsValid = app.methods.isValid( FIELD['rfValAkkoord'], false );
			},
			rfValInkomenPartner : function(sender, e){
				e.IsValid = app.methods.isValid( FIELD['rfValInkomenPartner'], true );
			},
			rfValRegios : function(sender, e){
				e.IsValid = app.methods.isValid( FIELD['rfValRegios'], false );
			},
			rfValGeboortedatumPartner : function(sender, e) {
				e.IsValid = app.methods.isValid(FIELD['rfValGeboortedatumPartner'], true);
			}
		}
    };

    return {
    	init : app.methods.init,
		Validator : {
			rfValGeslachtPartner : app.validator.rfValGeslachtPartner,
            rfValVoorlettersPartner: app.validator.rfValVoorlettersPartner,
            reExprPartnerVoorletters: app.validator.reExprPartnerVoorletters,
			rfValAchternaamPartner : app.validator.rfValAchternaamPartner,
			rfValAkkoord : app.validator.rfValAkkoord,
			rfValInkomenPartner : app.validator.rfValInkomenPartner,
			rfValRegios : app.validator.rfValRegios,
			rfValGeboortedatumPartner : app.validator.rfValGeboortedatumPartner
		}
    };

}(document, window));
;

APP.namespace('APP.Form.TijdelijkeVerhuur');

APP.Form.TijdelijkeVerhuur.Reageer = (function(document, window){

	var app,
		FIELDS = {
			reactOption_0 : {
				//openOption: 'feedback_bezichtiging',
				mandatoryField: 'content_0_txtBezichtigingToelichting'
			},
			reactOption_3 : {
				//openOption: 'feedback_weigering',
				mandatoryField: 'content_0_txtWeigeringReden'
			}
		};

    app = {
    	events : {
			onChange : function (evt) {
				var data = evt.data || {},
					id = (data.id ? data.id : $(this).attr('id')),
					errorSelector = $('#content_0_cvlFeedback');

				if ( typeof FIELDS[id] === 'undefined' || !data.id || app.methods.isValid() ) {
					errorSelector.hide();
				} else {
					errorSelector.show();
				}
			}
		},
    	methods : {
    		init : function () {
				if (!$('[data-form="tijdelijke-verhuur|reageer"]').length) {
					return;
				}

				APP.trace('Log: [form|tijdelijke-verhuur|reageer] Instantiate form...');

				app.methods.create();
				app.methods.reset();
				app.methods.attach();
			},
			create : function () {
				$.each(FIELDS, function(k,v){
					var jqSelector = $('input#' + k),
						jqMandatorySelector = $('#'+v.openOption);

					//jqSelector
					//	.attr('data-open-option', v.openOption);

					jqMandatorySelector
						.off('change', app.events.onChange)
						.on('change', { id : k}, app.events.onChange)
				});
			},
			reset : function () {
				if (APP.Form.Element.OpenOption.active) {
					APP.Form.Element.OpenOption.init();
				}
			},
			isValid : function () {
				var result = true;

				$.each(FIELDS, function(k,v){
					var jqSelector = $('input#' + k),
						isChecked = jqSelector.prop('checked') || false,
						jqMandatoryValue = $('#' + v.mandatoryField).val().length;

					if (isChecked && !jqMandatoryValue) {
						result = false;
					}
				});

				return result;
			},
			attach : function () {
				$('input[name="content_0$rblReageerOptions"]')
					.off('change', app.events.onChange)
					.on('change', app.events.onChange);
			}
		},
		validator : {
			isEmpty : function (sender, e) {
				e.IsValid = app.methods.isValid();
			}
		}
    };

    return {
    	init : app.methods.init,
		Validator : {
			isEmpty : app.validator.isEmpty
		}
    };

}(document, window));
;

APP.namespace('APP.Form.VSH');

APP.Form.VSH.Login = (function(document, window){

    var app,
        loginFormObj,
        createFormObj;

    app = {
        events: {
            onFocusBlur: function (evt) {
                var form = (evt.data && evt.data.form ? evt.data.form : null);

                if (!form) return;

                form.find('.error-message').css('display', 'none');
            }
        },
    	methods : {
            init: function () {
                loginFormObj = $('[data-form="vsh|login"]');
                createFormObj = $('[data-form="vsh|create"]');

                if (!loginFormObj.length && !createFormObj.length) {
                    return;
                }

                APP.trace('Log: [form|vsh|login] Instantiate form...');

                app.methods.attach();
			},
            attach: function () {
                createFormObj.find('input#content_0_txtEmailRegistreer').on('focus blur', { form: loginFormObj }, app.events.onFocusBlur);
                loginFormObj.find('input[type="text"],input[type="password"]').on('focus blur', { form: createFormObj }, app.events.onFocusBlur);
            }
		}
    };

    return {
    	init : app.methods.init
    };

}(document, window));
;

APP.namespace('APP.Form.VSH');

APP.Form.VSH.UwSituatie = (function(document, window){

	var app,
        fields = {
            rfValPartnerGeboortedatum: 'input[name="content_0$txtPartnerGeboortedatum"]',
            rfValPartnerBrutoJaarInkomen: 'input[name="content_0$txtPartnerJaarInkomen"]'
        };

    app = {
        events: {
            onChange: function () {
                var s = $(this).data('reference'),
                    errorSelector = $('#content_0_' + s),
                    fieldSelector = fields[s];

                if (app.methods.isValid(fieldSelector)) {
                    errorSelector.hide();
                } else {
                    errorSelector.show();
                }
            },
            onClick: function (evt) {
                var validationResult = true;

                if (typeof window.Page_ClientValidate === 'function') {
                    validationResult = Page_ClientValidate();
                }

                if (!validationResult) {
                    evt.preventDefault();
                }
            }
	    },
    	methods : {
            init: function () {
				if (!$('[data-form="vsh|uw-situatie"]').length) {
					return;
				}

				APP.trace('Log: [form|vsh|uw-situatie] Instantiate form...');

				app.methods.attach();
			},
            isChecked: function (selector) {
                return $(selector).is(':checked');
            },
            isValid: function (s, dependency) {
                var element = $(s),
                    isValid = false,
                    type;

                if (!element.length || (dependency && !app.methods.isChecked(dependency))) {
                    return true;
                }

                type = element.attr('type') || element[0].nodeName.toLowerCase();

                switch (type) {
                    case 'select':
                        var minLength = element.data('length-min') || 1;
                        isValid = element.val().toString().length >= minLength;
                    case 'text':
                        var minLength = element.data('length-min') || 1;
                        isValid = element.val().toString().length >= minLength;
                        break;
                    case 'radio':
                    case 'checkbox':
                        isValid = element.filter(':checked').length > 0;
                        break;
                    case 'table':
                        isValid = element.find('input[type="checkbox"]').filter(':checked').length > 0;
                        break;
                }

                return isValid;
            },
            attach: function () {
                var i;

                for (i in fields) {
                    if (fields.hasOwnProperty(i)) {
                        $(fields[i])
                            .attr('data-reference', i)
                            .off('change', app.events.onChange)
                            .on('change', app.events.onChange);
                    }
                }

                $('#content_0_btVolgende')
                    .off('click', app.events.onClick)
                    .on('click', app.events.onClick);
            }
		},
        validator: {
            rfValPartnerGeboortedatum: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerGeboortedatum, 'input#content_0_partner_toevoegen');
            },
            rfValPartnerBrutoJaarInkomen: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerBrutoJaarInkomen, 'input#content_0_partner_toevoegen');
            }
		}
    };

    return {
    	init : app.methods.init,
		Validator : {
            rfValPartnerGeboortedatum: app.validator.rfValPartnerGeboortedatum,
            rfValPartnerBrutoJaarInkomen: app.validator.rfValPartnerBrutoJaarInkomen
		}
    };

}(document, window));
;

APP.namespace('APP.Form.VSH');

APP.Form.VSH.MijnGegevens = (function(document, window){

    var app,
        fields = {
            // partner
            rfValPartnerAanhef: 'input[name="PartnerGeslacht"]',
            rfValPartnerVoorletters: 'input[name="PartnerVoorletters"]',
            rfValPartnerAchternaam: 'input[name="PartnerAchternaam"]',
            rfValPartnerEmailadres: 'input[name="PartnerEmailadres"]',
            rfValPartnerTelefoon: 'input[name="PartnerTelefoon"]',
            rfValPartnerGeboortedatum: 'input[name="PartnerGeboortedatum"]',
            rfValPartnerBrutoJaarInkomen: 'input[name="PartnerJaarInkomen"]',
            // afwijkend adres
            rfValPartnerPostcode: 'input[name="PartnerPostcode"]',
            rfValPartnerHuisnummer: 'input[name="PartnerHuisnummer"]',
            rfValPartnerToevoeging: 'input[name="PartnerToevoeging"]'            
        },
        regex = {
            rfValPartnerVoorletters: /^.{0,10}$/,
            rfValPartnerToevoeging: /^.{0,7}$/
        };

    app = {
        events: {
            onChange: function () {
                var s = $(this).data('reference'),
                    errorSelector = $('#content_0_' + s),
                    regexSelector = $('#content_0_' + s.replace('rfVal', 'reExpr')),
                    fieldSelector = fields[s],
                    valid = true;
               
                if (app.methods.isValid(fieldSelector)) {
                    errorSelector.hide();
                } else {
                    valid = false;
                    errorSelector.show();
                }

                if (regexSelector.length) {
                    if (app.methods.isRegexValid(s)) {
                        regexSelector.hide();
                    } else {
                        regexSelector.show();
                    }
                }
            },
            onClick: function (evt) {
                var validationResult = true;

                if (typeof window.Page_ClientValidate === 'function') {
                    validationResult = Page_ClientValidate();
                }

                if (!validationResult) {
                    evt.preventDefault();
                }
            }
	    },
    	methods : {
            init: function () {
                /*
				if (!$('[data-form="vsh|mijn-gegevens"]').length) {
					return;
				}

                return;
                APP.trace('Log: [form|vsh|mijn-gegevens] Instantiate form...');
				app.methods.attach();
                */
			},
    		isChecked : function (selector) {
                return $(selector).is(':checked');
            },
            isRegexValid: function (s, dependency) {
                var ref = fields[s],
                    element = $(ref);

                if (!element.length || (dependency && !app.methods.isChecked(dependency))) {
                    return true;
                }

                var value = element.val(),
                    expr = regex[s];

                return expr.test(value);
            },
            isValid: function (s, dependency) {
                var element = $(s),
                    isValid = false,
                    type;

                if (!element.length || (dependency && !app.methods.isChecked(dependency)) ) {
                    return true;
                }

                type = element.attr('type') || element[0].nodeName.toLowerCase();

                switch (type) {
                    case 'select':
                        var minLength = element.data('length-min') || 1;
                        isValid = element.val().toString().length >= minLength;
                    case 'text':
                        var minLength = element.data('length-min') || 1;
                        isValid = (element.val().toString().length >= minLength);
                        break;
                    case 'radio':
                    case 'checkbox':
                        isValid = element.filter(':checked').length > 0;
                        break;
                    case 'table':
                        isValid = element.find('input[type="checkbox"]').filter(':checked').length > 0;
                        break;
                }

                return isValid;
            },
            attach: function () {
                var i;

                for (i in fields) {
                    if (fields.hasOwnProperty(i)) {
                        $(fields[i])
                            .attr('data-reference', i)
                            .off('change', app.events.onChange)
                            .on('change', app.events.onChange);
                    }
                }

                $('#content_0_btSubmit')
                    .off('click', app.events.onClick)
                    .on('click', app.events.onClick);

                // when user comes on the form page to fill out missing information
                // run client side validation
                setTimeout(function () {
                    if ($('[data-validate-onload="true"]').length) {
                        Page_ClientValidate();
                    }
                });
            }
		},
        validator: {
            rfValPartnerAanhef: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerAanhef, 'input#content_0_partner_toevoegen');
            },
            reExprPartnerVoorletters: function (sender, e) {
                e.IsValid = app.methods.isRegexValid('rfValPartnerVoorletters', 'input#content_0_partner_toevoegen');
            },
            rfValPartnerVoorletters: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerVoorletters, 'input#content_0_partner_toevoegen');
            },
            rfValPartnerAchternaam: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerAchternaam, 'input#content_0_partner_toevoegen');
            },
            rfValPartnerEmailadres: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerEmailadres, 'input#content_0_partner_toevoegen');
            },
            rfValPartnerTelefoon: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerTelefoon, 'input#content_0_partner_toevoegen');
            },
            rfValPartnerGeboortedatum: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerGeboortedatum, 'input#content_0_partner_toevoegen');
            },
            rfValPartnerBrutoJaarInkomen: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerBrutoJaarInkomen, 'input#content_0_partner_toevoegen');
            },
            rfValPartnerPostcode: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerPostcode, 'input#content_0_cbAfwijkendAdres');
            },
            rfValPartnerHuisnummer: function (sender, e) {
                e.IsValid = app.methods.isValid(fields.rfValPartnerHuisnummer, 'input#content_0_cbAfwijkendAdres');
            },
            reExprPartnerToevoeging: function (sender, e) {
                e.IsValid = app.methods.isRegexValid('rfValPartnerToevoeging', 'input#content_0_cbAfwijkendAdres');
                
            }
		}
    };

    return {
    	init : app.methods.init,
        Validator: {
            rfValPartnerAanhef: app.validator.rfValPartnerAanhef,
            rfValPartnerVoorletters: app.validator.rfValPartnerVoorletters,
            reExprPartnerVoorletters: app.validator.reExprPartnerVoorletters,
            rfValPartnerAchternaam: app.validator.rfValPartnerAchternaam,
            rfValPartnerEmailadres: app.validator.rfValPartnerEmailadres,
            rfValPartnerTelefoon: app.validator.rfValPartnerTelefoon,
            rfValPartnerGeboortedatum: app.validator.rfValPartnerGeboortedatum,
            rfValPartnerBrutoJaarInkomen: app.validator.rfValPartnerBrutoJaarInkomen,
            rfValPartnerPostcode: app.validator.rfValPartnerPostcode,
            rfValPartnerHuisnummer: app.validator.rfValPartnerHuisnummer,
            reExprPartnerToevoeging: app.validator.reExprPartnerToevoeging,
		}
    };

}(document, window));
;

APP.namespace('APP.Form');

APP.Form.DateRange = (function ($, window) {

  var app,
    domWindow,
    defaultLength = 10,
    format = 'dd-mm-yy',
    fromSelector,
    toSelector,
    placeholder = 'DD-MM-JJJJ',
    regexMatch = /(\d+)-(\d+)-(\d+)/;

  app = {
    events: {
      toggleInput: function (evt) {
        evt.preventDefault();
        $(this).prev().trigger('focus');
      }
    },
    methods: {
      init: function () {

        fromSelector = $('.dateFrom');
        toSelector = $('.dateTo');
        if (!fromSelector.length && !toSelector.length) {
          return;
        }

        APP.trace('Log: [form|daterange] Instantiate form...');

        app.methods.create();
        app.methods.iconToggle();
      },
      iconToggle: function () {
        if (fromSelector.next().hasClass('ui-datepicker-trigger')) {
          fromSelector.next()
            .off('click', app.events.toggleInput)
            .on('click', app.events.toggleInput)
        }

        if (toSelector.next().hasClass('ui-datepicker-trigger')) {
          toSelector.next()
            .off('click', app.events.toggleInput)
            .on('click', app.events.toggleInput)
        }
      },
      create: function () {


        $('.search-filter-form button[type=submit]').on('click', function (e) {
          e.preventDefault();

          var from = fromSelector.val();
          if (from == placeholder) from = '';

          var to = toSelector.val();
          if (to == placeholder) to = '';

          if (from && to && app.methods.isValidRange(from, to)) {

            var params = {
              filter: "datum",
              waarde: from + '|' + to
            };

            if ($('#hddnQuery').length > 0 && $('#hddnQuery').val()) {
              params[$('#hddnQuery').attr("rel")] = $('#hddnQuery').val();
            }

            window.location.href = window.location.pathname + '?' + $.param(params);
          } else {
            alert('Geef een geldige van/tot datum op.')
          }
        });

        fromSelector.datepicker({
          dateFormat: format,
          onClose: function (selectedDate) {

            var from = $(this).val();
            if (from == placeholder) from = '';

            var to = toSelector.val();
            if (to == placeholder) to = '';

            if (from && to && app.methods.isValidRange(from, to)) {

              var params = {
                filter: "datum",
                waarde: from + '|' + to
              };

              if ($('#hddnQuery').length > 0 && $('#hddnQuery').val()) {
                params[$('#hddnQuery').attr("rel")] = $('#hddnQuery').val();
              }

              // window.location.href = window.location.pathname + '?' + $.param(params);

            } else {
              if (selectedDate != placeholder) {
                toSelector.datepicker("option", "minDate", selectedDate);
              }
            }
          }
        });

        toSelector.datepicker({
          dateFormat: format,
          onClose: function (selectedDate) {

            var from = fromSelector.val();
            if (from == placeholder) from = '';

            var to = $(this).val();
            if (to == placeholder) to = '';

            if (from && to && app.methods.isValidRange(from, to)) {

              var params = {
                filter: "datum",
                waarde: from + '|' + to
              };
              //
              if ($('#hddnQuery').length > 0 && $('#hddnQuery').val()) {
                params[$('#hddnQuery').attr("rel")] = $('#hddnQuery').val();
              }

              // window.location.href = window.location.pathname + '?' + $.param(params);

            } else {
              if (selectedDate != placeholder) {
                fromSelector.datepicker("option", "maxDate", selectedDate);
              }
            }
          }
        });

        if (fromSelector.val() == '') {
          fromSelector.val(placeholder);
        }

        if (toSelector.val() == '') {
          toSelector.val(placeholder);
        }
      },
      isValidRange: function (from, to) {
        var fromDate = app.methods.toDate(from);
        var toDate = app.methods.toDate(to);

        if (fromDate && toDate && fromDate <= toDate) {
          return true;
        }

        return false;
      },
      toDate: function (dateString) {
        if (typeof dateString != 'string') {
          return false;
        } else if (dateString.length != defaultLength) {
          return false;
        } else if (dateString == placeholder) {
          return false;
        } else {
          try {
            var regDate = new RegExp(regexMatch);
            var match = regDate.exec(dateString);
            var year = parseInt(match[3], 10);
            var month = parseInt(match[2], 10) - 1;
            var day = parseInt(match[1], 10);
            return new Date(year, month, day);
          }
          catch (e) {
            return false;
          }
        }
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    }
  };

}($, window));;

APP.namespace('APP.Form');

APP.Form.FilterWoonRuimte = (function($){

    var app;
    app = {
		events : {
			onChangeHuurOfKoop : function () {
				app.methods.toggleHuurOfKoop();
			}
		},
        methods : {
            init: function () {
				APP.trace('Log: [form|filterwoonruimte] Instantiate form...');

				app.methods.attach();
            },
			toggleHuurOfKoop : function () {
				var jqObj,
					selectValue;

				jqObj = $('#panel-huur-contract');
				selectValue = $('.select-soort > select').val();

				if (!jqObj.hasClass('hidden')) {
					jqObj.addClass('hidden');
				}

				if (selectValue === 'Huur') {
					jqObj.removeClass('hidden');
				}
			},
			forceInt : function (val) {
				var tmp = parseInt(val, 10);
				if(isNaN(tmp)) tmp = 0;
				return tmp;
			},
			attach : function () {
				$('.select-soort > select').on('change', app.events.onChangeHuurOfKoop);
				app.methods.toggleHuurOfKoop();

				if($('.select-van select').length == 0) return;

				// price from select
				$('.select-van select').on('change', function() 
				{
					var selectTo = $(this).closest('.form-row').find('.select-tot select');
					var valFrom = app.methods.forceInt($(this).val());
					var valTo = app.methods.forceInt(selectTo.val());

					// increase value of 'to' if possible
					if(valFrom >= valTo) {
						var nextValue = $(this).find('option:selected').next().val();
						if(!nextValue) nextValue = $(this).find('option').last().val();
						selectTo.val(nextValue);
					}				
				});
				
				// price to select				
				$('.select-tot select').on('change', function() 
				{
					var selectFrom = $(this).closest('.form-row').find('.select-van select');
					var valFrom = app.methods.forceInt(selectFrom.val());
					var valTo = app.methods.forceInt($(this).val());
					
					// decrease value of 'from' if possible
					if(valTo <= valFrom) {
						var prevValue = $(this).find('option:selected').prev().val();
						if(!prevValue) prevValue = $(this).find('option').first().val();
						selectFrom.val(prevValue);
					}					
				});
				
				// if 'from' & 'to' are both 0, set to 'from' to max value
				$('.select-tot select').each(function(e) {
					var selectTo = $(this).closest('.form-row').find('.select-tot select');		
					var valFrom = app.methods.forceInt($(this).val());
					var valTo = app.methods.forceInt(selectTo.val());
					
					if(valTo == 0 && valFrom == 0) {
						var lastValue = $(this).find('option').last().val();
						$(this).val(lastValue)
					}
				});

				$('.filter-woonruimte .select-soort select').on('change', function() 
				{
					app.methods.onchange();
				});
				
				app.methods.onchange();
			},
			onchange : function () {
				switch($('.filter-woonruimte .select-soort select').val()) {
					default:
					case 'Huur':
						app.methods.showHuur();
						break;					
					case 'Koop':
						app.methods.showKoop();							
						break;
				}
			},			
			update: function() {
				$('.select-van select').off('change');
				$('.select-tot select').off('change');
				$('.filter-woonruimte .select-soort select').off('change');		
				app.methods.attach();
			},
			showHuur: function() {
				$('.filter-woonruimte .vantot-huur').show();
				$('.filter-woonruimte .vantot-koop').hide();
			},
			showKoop: function() {
				$('.filter-woonruimte .vantot-huur').hide();
				$('.filter-woonruimte .vantot-koop').show();	
			}			
		}
    };

    return {
        init : function () {
            app.methods.init();
        },
		update : function() {
			app.methods.update();
		}
    };

}($));;
APP.namespace('APP.Form');

APP.Form.AutoCompleteSearchBox = (function ($) {

  var app,
    bodyObj,
    windowObj,
    element,
    initialized = false;

  app = {
    config: {
      limit: 5
    },
    events: {
      onResize: function () {
        var searchBox = $('.search-box');


        searchBox.each(function () {
          var el = $(this);

          if (el.is(':visible')) {
            el.removeClass('search-box-active');
          }
        });
      }
    },
    methods: {
      init: function () {
        bodyObj = $('body');
        windowObj = $(window);
        element = $('.filterCriteria');
        initialized = false;
        if (!element.length) {
          return;
        }

        APP.trace('Log: [form|autocomplete.searchbox] Instantiate form');

        app.methods.create();
        app.methods.attach();
      },
      getWrapper: function (id) {
        return $('<div/>', {
          'class': 'search-box search-box-' + id
        });
      },
      create: function () {
        if (initialized) {
          return;
        }

        element.autocomplete({
          source: function (request, response) {
            var apiUrl = app.methods.getRequestURL(request);

            $.getJSON(apiUrl, function (data) {
              if (data.status == 'ok') {
                response($.map(data.results, function (value, key) {
                  return {
                    label: value.searchTerm,
                    value: value.searchTerm
                  };
                }));
              } else {
                response($.map({}, function (value, key) {
                  return {
                    label: value.searchterm,
                    value: value.searchterm
                  };
                }));
              }
            });
          },
          open: app.methods.onOpen,
          close: app.methods.onClose,
          select: app.methods.onSelect,
          minLength: 2
        });

        initialized = true;
      },
      onOpen: function () {
        var widget = $(this).autocomplete('widget'),
          widgetId = widget.attr('id'),
          width = widget.css('width'),
          wrapperObj = $('.search-box-' + widgetId),
          offset = {
            top: widget.css('top'),
            left: widget.css('left')
          };

        if (!wrapperObj.length) {
          wrapperObj = app.methods.getWrapper(widgetId);
        }

        if (element.parents('#header').length) {
          wrapperObj.addClass('search-box-header');
        }

        wrapperObj.append(widget);
        bodyObj.append(wrapperObj);

        if (!wrapperObj.hasClass('search-box-active')) {
          widget.removeAttr('style');

          wrapperObj.css({
            'width': width,
            'top': offset.top,
            'left': offset.left
          });

          setTimeout(function () {
            wrapperObj.addClass('search-box-active');
          }, 100);
        }

        widget.removeAttr('style');
      },
      onClose: function () {
        var widget = $(this).autocomplete('widget'),
          widgetId = widget.attr('id'),
          wrapperObj = $('.search-box-' + widgetId);

        wrapperObj
          .removeClass('search-box-active')
          .removeAttr('style');

        widget.appendTo(bodyObj);
      },
      onSelect: function (event, ui) {
        var value = ui.item.value;
        element.val(value);
        element.closest('form').trigger('submit');
      },
      getRequestURL: function (request) {
        var url = "/api/Search/SearchTermSuggest";

        url += "?term=" + request.term;
        url += "&limit=" + app.config.limit;

        return url;
      },
      attach: function () {
        windowObj
          .off('resize', app.events.onResize)
          .on('resize', app.events.onResize);
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    },
    update: function () {
      app.methods.update();
    }
  };

}($));;

APP.namespace('APP.Form');

APP.Form.AutoCompleteStreet = (function($){

    var app;
	var cityKeys = [];
	
    app = {
		events : {
			//
		},
        methods : {
			
            init: function () {
				APP.trace('Log: [form|autoccompletestreet] Instantiate form');
				app.methods.attach();
				
            },
			
			attach : function () {
				
				// track changes to plaats stad select
				$('.plaats_stad').off('change');
				$('.plaats_stad').on('change', function () {
					app.methods.update();
				});
			
				app.methods.update();
				
				//
				if($('.filterStraatnaam').data('initialized')) {
					return;
				} else {
					$('.filterStraatnaam').data('initialized', true );
					$('.filterStraatnaam').prop('autocomplete', false);
				}

				$('.filterStraatnaam').autocomplete({
					source: function (request, response) {
						$.getJSON(app.methods.getRequestURL(request), function (data) {
							if (data.status == 'ok') {
								response($.map(data.results, function (value, key) {
									return {
										label: value.street,
										value: value.street
									};
								}));
							} else {
								// return empty dataset
								response($.map({}, function (value, key) {
									return {
										label: value.street,
										value: value.street
									};
								}));
							}
						});
					},
					open: function () {
						$(this).autocomplete('widget').css('z-index', 100);
						return false;
					},
					minLength: 2
				})
			},

			getRequestURL : function(request) {
				var url = "/api/Geo/Streets?street=" + request.term;
				// add regions if available
				var regions = cityKeys.join("%2C");
				if (regions) {
					url += "&regions=" + regions;
				}
				return url;
			},
			
			update : function() {
	
				cityKeys = [];
				$('.plaats_stad :selected').each(function (i, selectedElement) {
					cityKeys.push($(selectedElement).val());
				});

			}
		}
    };

    return {
        init : function () {
            app.methods.init();
        },
		update : function() {
			app.methods.update();
		}
    };
	
}($));;

APP.namespace('APP.Form');
/* auto complete for 'Wie doet wat' */

APP.Form.AutoCompleteWDW = (function($){

    var app;
	var cityKeys = [];
	
    app = {
		events : {
			//
		},
        methods : {
			
            init: function () {
				APP.trace('Log: [form|autocompletewdw] Instantiate form...');
				app.methods.attach();
				
            },
			
			attach : function () {

				if($('.wdw-input').length == 0) return;

				// track changes to plaats stad select
				$('.wdw-input').off('change');
				$('.wdw-input').on('change', function () {
					app.methods.update();
				});
			
				app.methods.update();
				
				//
				if($('.wdw-input').data('initialized')) {
					return;
				} else {
					$('.wdw-input').data('initialized', true );
					$('.wdw-input').prop('autocomplete', false);
				}

				$('.wdw-input').autocomplete({
					source: function (request, response) {
						$.getJSON(app.methods.getRequestURL(request), function (data) {
							if (data.status == 'ok') {
								response($.map(data.results, function (value, key) {
									return {
										label: value,
										value: value
									};
								}));	
							} else {
								// return empty dataset
								response($.map({}, function (value, key) {
									return {
										label: value,
										value: value
									};
								}));								
							}

							$('.ui-autocomplete').addClass('wdw-autocomplete');
						});
					},
					open: function () {
						$(this).autocomplete('widget').css('z-index', 100);
						return false;
					},
					minLength: 2,
					select: function(event, ui) {

						if (ui.item){
							$('.wdw-input').val(ui.item.value);
						}

						$('.wdw-input').closest('form').submit();
					}
				})
			},

			getRequestURL : function(request) {
				var url = "/api/digitalbrochure/autocomplete?qa=" + request.term;
				return url;
			},
			
			update : function() {

			}
		}
    };

    return {
        init : function () {
            app.methods.init();
        },
		update : function() {
			app.methods.update();
		}
    };
	
}($));;



APP.namespace('APP.Form');

APP.Form.AanmeldenNieuwsbriefHuren = (function($){

    var app,
		formRefObject;

    app = {
		config : {
			objectId : '#form_45B110C778374411ADA9BD6B236F872E_field_2A6609D45BFA4666BBB57C655437DC9Flist_1',
			toggleItems : [
				{
					inputId : '#form_45B110C778374411ADA9BD6B236F872E_field_D0793C787F7749689510E1832ECACD1Dcheckbox',
					targetId : [
						'#form_45B110C778374411ADA9BD6B236F872E_field_936DC34805F34742A1EB462FC2FBF14Bscope',
                        '#form_45B110C778374411ADA9BD6B236F872E_field_F41F18000F584D4289A16B2D7269F9A9scope'
					]
				},
				{
					inputId : '#form_45B110C778374411ADA9BD6B236F872E_field_C130CC829C9E42D280A2D78049F0F3D9checkbox',
					targetId : [
						'#form_45B110C778374411ADA9BD6B236F872E_field_D1A995D87E544362ABA63B9640D60571scope',
						'#form_45B110C778374411ADA9BD6B236F872E_field_5174B3AD32B748A8A5A7CDF22697633Ascope'
					]
				}
			],
			checkOnInit : [
				'#form_45B110C778374411ADA9BD6B236F872E_field_2A6609D45BFA4666BBB57C655437DC9Flist_1'
			],
			submitId : '#form_45B110C778374411ADA9BD6B236F872E_form_45B110C778374411ADA9BD6B236F872E_submit'
		},
		templates : {
			getSpan : function (t) {
				var config = {};

				switch (t) {
					case 'REQUIRED_SUFFIX' :
						config.class = 'scfRequired';
						config.text = '*';
						break;
					case 'ERROR_HUUR_KOOP' :
						config.class = 'scfValidatorRequired customError';
						config.text = 'Wat zoekt u? (Huur &oacute;f Koop) is een verplicht veld.';
						break;
				}

				return $('<span/>',{
					'class' : config.class,
					'html' : config.text,
					'data-tpl-type' : t
				});
			}
		},
		events : {
			onClick : function () {
				var inputObj = $(this),
					id = '#'+ inputObj.attr('id'),
					items = app.config.toggleItems;

				$.each(items, function(k,v){
					if (id === v.inputId) {
						app.ui.toggle.apply(inputObj[0], [v.targetId]);
					}
				});
			},

			/*
			 * onSubmitClick
			 *
			 * Click events that handles a custom validation on the 'Huur of Koop' checkboxes,
			 * because the user needs to select one of the options...
			 *
			 */

			onSubmitClick : function (evt) {
				var position,
					spanObj,
					docObj,
					jumpToObj,
					errorObj = $('.customError');

				// remove old errors...
				if (errorObj.length) {
					errorObj.remove();
				}

				// validate custom checkboxes...
				if (!app.methods.isValid()) {
					// prevent submit...
					evt.preventDefault();

					// create error...
					spanObj = app.templates.getSpan('ERROR_HUUR_KOOP');

					// manipulate and insert error
					spanObj.css({
						'padding-bottom' : '25px',
						'margin-top' : '-10px'
					}).insertAfter('#form_45B110C778374411ADA9BD6B236F872E_field_C130CC829C9E42D280A2D78049F0F3D9');
				}

				// jquery selector of first visible error...
				jumpToObj = $('.scfValidatorRequired:visible').eq(0);

				// selector of html/body...
				docObj = $("html, body");

				if (jumpToObj.length) {
					position = jumpToObj.parent().parent().offset().top;
					docObj.scrollTop( parseInt(position, 10) );
				}
			}
		},
		ui : {
			render : function () {
				$.each(app.config.toggleItems, function(k,v){
					var inputObj,
						parentObj,
						spanObj;

					inputObj = $(v.inputId);

					spanObj = app.templates.getSpan('REQUIRED_SUFFIX');
					spanObj.css({
						'top' : 0,
						'margin-top' : '-8px'
					});

					parentObj = inputObj.parents('.scfCheckboxBorder').eq(0);
					parentObj.append(spanObj);

					app.ui.toggle.apply(inputObj[0], [v.targetId]);
					app.methods.bind.apply(inputObj[0]);
				});
			},
			toggle : function (data) {
				var inputObj = $(this),
					toggle = inputObj.prop('checked') ? 'show' : 'hide',
					i;

				if (typeof data !== 'object') {
					return;
				}

				for (i in data) {
					if (data.hasOwnProperty(i)) {
						var target = $(data[i]);
						if (target.length) {
							switch (toggle) {
								case 'show':
									target.show();
									break;
								case 'hide':
									target.hide();
									break;
							}

						}
					}
				}
			},
			updateFormStatus: function (el) {
				if(el.prop('checked')) {
					app.ui.showAllFieldsetsAfterID(app.config.objectId);
				} else {
					app.ui.hideAllFieldsetsAfterID(app.config.objectId);
				}
			},
			hideAllFieldsetsAfterID: function(id) {
				var checkboxFound = false;
				$('fieldset').each(function() {
					if (checkboxFound) $(this).hide();
					if($(this).find(id).length == 1) {
						checkboxFound = true;
					}
				});
			},
			showAllFieldsetsAfterID: function(id) {
				var checkboxFound = false;
				$('fieldset').each(function() {
					if (checkboxFound) $(this).show();
					if($(this).find(id).length == 1) {
						checkboxFound = true;
					}
				});
			}
		},
        methods : {
          init: function () {
            formRefObject = $('#form_45B110C778374411ADA9BD6B236F872E_formreference');
				if (!formRefObject.length) {
					return;
				}

				APP.trace('Log: [form|aanmeldennieuwsbriefhuren] Instantiate form...');

				app.ui.render();

				app.methods.checkOnInit();
				app.methods.attach();
				app.methods.validate();
            },
			checkOnInit : function () {
				$.each(app.config.checkOnInit, function(k,v){
					var jqObj = $(v);
					jqObj.prop('checked', true);
				});
			},
			bind : function () {
				var inputObj = $(this);

				if (!inputObj.length) {
					return;
				}

				inputObj
					.off('click', app.events.onClick)
					.on('click', app.events.onClick);
			},
			isValid : function () {
				var checkboxes = app.config.toggleItems,
					i;

				for (i in checkboxes) {
					if (checkboxes.hasOwnProperty(i)) {
						if ($(checkboxes[i].inputId).is(':checked')) {
							return true;
						}
					}
				}

				return false;
			},
			validate : function () {
				var submitObject = $(app.config.submitId);

				if(!submitObject.length) {
					return;
				}

				submitObject
					.on('click', app.events.onSubmitClick);
			},
			attach : function () {
				var inputObject = $(app.config.objectId);

				if(!inputObject.length) {
					return;
				}

				inputObject.on('click', function() {
					app.ui.updateFormStatus($(this));
				});

				app.ui.updateFormStatus(inputObject);


			}
		}
    };

    return {
        init : function () {
            app.methods.init();
        }
    };

}($));
;


APP.namespace('APP.Form');

APP.Form.Documenten = (function(){



    var app,
        formSelector,
        currentSelector;

    app = {
        templates : {
            error : function (type, refId) {
                return $('<span/>', {
                    'class' : 'error-message',
                    'data-ref-id' : refId,
                    'text' : type + ' is een verplicht veld.'
                })
            }
        },
        config : {
            modal : {
                'DELETE' : {
                    modal : 'modal-alert',
                    title : 'Bestand verwijderen',
                    text : 'Weet u zeker dat u dit bestand wilt verwijderen?',
                    button : {
                        cancel : 'Annuleren',
                        confirm : 'Verwijderen'
                    }
                },
                'CONFIRM' : {
                    modal : 'modal-info',
                    title : 'Wijziging opslaan',
                    text : 'Uw wijzigingen zijn (nog) niet opgeslagen.<br/>Weet u zeker dat u verder wilt gaan?',
                    button : {
                        cancel : 'Opslaan',
                        confirm : 'Verder zonder opslaan'
                    }
                }
            }
        },
        events : {
            onSubmit : function(evt) {
                formSelector.each(function(){
                    var el = $(this),
                        data = el.data(),
                        editObj = el.find('.inner[data-type="edit"]');

                    if (data.validate && editObj.hasClass('show')) {
                        var formRowObj = editObj.find('.form-row').eq(0),
                            fileInput = formRowObj.find('input[type="file"]');

                        if (formRowObj.find('.required').length && !app.methods.isValid(fileInput) ) {
                            var type = editObj.find('legend').text(),
                                refId = fileInput.attr('id'),
                                errorObj = app.templates.error(type, refId);

                            if (!$('.error-message[data-ref-id="'+refId+'"]').length) {
                                errorObj.insertAfter(formRowObj);
                            }

                            evt.preventDefault();
                        }
                    }
                });
            },
            onChange : function () {
                var el = $(this),
                    itemId = el.attr('id'),
                    errorObj = $('.error-message[data-ref-id="'+itemId+'"]');

                setTimeout(function(){
                    if (app.methods.isValid(el) && errorObj.length) {
                        errorObj.remove();
                    }
                }, 0);
            },
            onDeleteClick : function (evt) {
                evt.preventDefault();

                var button = $(this),
                    buttonHref = button.attr('href'),
                    formRowObj = button.parents('.form-row:eq(0)'),
                    modalData = app.config.modal['DELETE'];

                modalData.url = buttonHref;

                // Please note: when there's only an anchor link, eg. #delete,
                //  the file isn't uploaded yet, so we can reset the input field,
                //  in all other cases we are showing the user an modal to confirm the delete,
                //  then process the link click...
                if (buttonHref === '#delete') {
                    formRowObj
                        .removeClass('active')
                        .addClass('hidden')
                        .find('.input-file input[type="file"]').trigger('file.reset');
                } else {
                    app.methods.showModal('DELETE', modalData);
                }
            },
            onToggleClick : function (evt) {
                evt.preventDefault();

                var button = $(this),
                    type = button.data('type'),
                    modalData,
                    fileInput;

                currentSelector = button.parents('[data-js-form="documenten"]');
                fileInput = currentSelector.find('input[type="file"]');

                if (type === 'edit' || !app.methods.hasChanged(fileInput)) {
                    app.methods.toggle(type);
                } else {
                    modalData = app.config.modal['CONFIRM'];
                    modalData.toggle = type;

                    app.methods.showModal('CONFIRM', modalData);
                }
            },
            onAddRowClick : function (evt) {
                evt.preventDefault();

                var button = $(this),
                    formObj = button.parents('[data-js-form="documenten"]');

                formObj.find('.form-row.hidden:eq(0)')
                    .removeClass('hidden')
                    .addClass('active');

                if (!formObj.find('.form-row.hidden:eq(0)').length) {
                    button.hide();
                }
            }
        },
        methods : {
            init : function () {
                formSelector = $('[data-js-form="documenten"]');

                if (!formSelector.length) {
                    return;
                }

                APP.trace('Log: [form.documenten] Instantiate form...');

                app.methods.attach();
                app.methods.create();
            },
            create : function () {
                formSelector.each(function(){
                    var el = $(this),
                        files = el.find('.file-list li');

                    if (files.length) {
                        app.methods.toggle('list', el);
                    } else {
                        app.methods.toggle('edit', el);

                        el.find('button[data-event="toggle"], .form-row:eq(0) .pull-sm-right').addClass('hidden');
                        el.find('button[data-event="add-row"]').trigger('click');
                    }
                });
            },
            hasChanged : function (fileInput) {
                var hasChanged = false;

                fileInput.each(function(){
                    var el = $(this),
                        value = el.val().split('C:\\fakepath\\').join(''),
                        origFileName = el.data('original-file');

                    if (value.length && value !== origFileName) {
                        hasChanged = true;
                    }
                });

                return hasChanged;
            },
            isValid : function (fileInput) {
                var isValid = false;

                fileInput.each(function(){
                    var el = $(this),
                        value = el.val().split('C:\\fakepath\\').join(''),
                        origFileName = el.data('original-file');

                    if (value.length || (!value.length && origFileName)) {
                        isValid = true;
                    }
                });

                return isValid;
            },
            resetForm : function () {
                var rowSelector = currentSelector.find('.form-row');

                rowSelector.each(function(){
                    var jqObj = $(this);

                    jqObj.find('.input-file input[type="file"]').trigger('file.reset');

                    if (jqObj.hasClass('active')) {
                        jqObj.removeClass('active').addClass('hidden');
                    }
                });

                if (rowSelector.find('hidden')) {
                    currentSelector.find('button[data-event="add-row"]').show();
                }
            },
            submitForm : function () {
                // $(formSelector).parent('form').trigger('submit');
            },
            showModal : function (type, data) {
                var buttons;

                if (type === 'CONFIRM') {
                    buttons = [
                        {
                            text : data.button.confirm,
                            callback : 'confirm',
                            'class' : 'btn btn-primary',
                            dismiss : true
                        },
                        {
                            text : data.button.cancel,
                            'class' : 'btn btn-default btn-alt',
                            callback : 'save',
                            dismiss : true
                        }
                    ];
                } else {
                    buttons = [
                        {
                            text : data.button.cancel,
                            'class': 'btn btn-primary',
                            dismiss : true
                        },
                        {
                            text : data.button.confirm,
                            callback : 'confirm',
                            'class': 'btn btn-default btn-alt',
                            dismiss : true
                        }

                    ];
                }

                APP.Components.Modal.create({
                    data : {
                        type : data.modal,
                        title : data.title,
                        text : data.text,
                        animation : true,
                        button : buttons
                    },
                    callback : {
                        save : {
                            type : 'click',
                            fn : function () {
                                app.methods.submitForm();
                            }
                        },
                        confirm : {
                            type : 'click',
                            fn : function() {
                                switch (type) {
                                    case 'default':
                                    case 'CONFIRM':
                                        app.methods.resetForm();
                                        app.methods.toggle(data.toggle);
                                        break;
                                    case 'DELETE':
                                        window.location.href = data.url;
                                        break;
                                }
                            }
                        }
                    }
                });
            },
            toggle : function (type, element) {
                var el = element || currentSelector;

                el.find('.inner').removeClass('show');
                el.find('.inner[data-type="'+ type +'"]').addClass('show');
            },
            attach : function () {
                formSelector.find('button[data-event="add-row"]')
                    .off('click', app.events.onAddRowClick)
                    .on('click', app.events.onAddRowClick);

                formSelector.find('button[data-event="toggle"]')
                    .off('click', app.events.onToggleClick)
                    .on('click', app.events.onToggleClick);

                formSelector.find('a[href="#delete"], a[data-event="delete"]')
                    .off('click', app.events.onDeleteClick)
                    .on('click', app.events.onDeleteClick);

                formSelector.find('input[type="file"]')
                    .off('change', app.events.onChange)
                    .on('change', app.events.onChange);

                formSelector.parents('form:eq(0)').find('input[type="submit"]')
                    .off('click', app.events.onSubmit)
                    .on('click', app.events.onSubmit);
            }
        }
    };

    return {
        init : app.methods.init
    };

}());
;

APP.namespace('APP.Form');

APP.Form.Doelgroepen = (function($){

    var app,
        formSelector;

    app = {
        config : {
            modal : {
                type : 'modal-info',
                title : 'Let op',
                text : 'U staat op het punt om de door u gekozen situatie aan te passen. In dit geval moet u een aantal nieuwe documenten toevoegen. Bestaande documenten komen te vervallen. Deze aanpassing is niet herstelbaar.',
                button : {
                    cancel : 'Annuleren',
                    confirm : 'Aanpassen'
                }
            },
            origValue : ''
        },
        events : {
            onSubmit : function (evt) {
                var newValue = formSelector.find('input[type="radio"]:checked').val();
                APP.trace('og: [form.doelgroepen] newValue=' + newValue);
                if (typeof(newValue) !== 'undefined') {
                    evt.preventDefault();
                    if (app.config.origValue.length && (newValue !== app.config.origValue)) {
                        app.methods.showModal();
                    } else {
                        app.methods.submitForm();
                    }
                }
            }
        },
        methods : {
            setConfig : function () {
                app.config.origValue = formSelector.find('input[type="radio"]:checked').val() || '';
            },
            init : function () {
                formSelector = $('form[data-js-form="doelgroepen"]');

                if (!formSelector.length) {
                    return;
                }

                APP.trace('Log: [form.doelgroepen] Instantiate form...');

                app.methods.setConfig();
                app.methods.attach();
            },
            submitForm : function () {
                $(formSelector).trigger('submit');
            },
            showModal : function () {
                var modalData = app.config.modal;

                APP.Components.Modal.create({
                    data : {
                        type : modalData.type,
                        title : modalData.title,
                        text : modalData.text,
                        animation : true,
                        button : [
                            {
                                text : modalData.button.cancel,
                                dismiss : true,
                                'class': 'btn btn-primary'
                            },
                            {
                                text : modalData.button.confirm,
                                dismiss : true,
                                callback : 'confirm',
                                'class' : 'btn btn-default btn-alt'
                            }
                        ]
                    },
                    callback : {
                        confirm : {
                            type : 'click',
                            fn : function() {
                                app.methods.submitForm();
                            }
                        }
                    }
                });
            },
            attach : function () {
                formSelector.find('button[data-event="submit"]')
                    .off('click', app.events.onSubmit)
                    .on('click', app.events.onSubmit);
            }
        }
    };

    return {
        init : app.methods.init
    };

}($));
;

APP.namespace('APP.Form');

APP.Form.HurenJaarinkomen = (function($){

    var app,
		inputInkomen1,
		inputInkomen2,
		inputInkomen3,
		inputTotal;

	// check for this specific form ID so we know it's
	// huren form
	var form;

    app = {
    	events : {
			onChanged : function() {

				var val1 = parseInt(inputInkomen1.val()) | 0;
				var val2 = parseInt(inputInkomen2.val()) | 0;
				var val3 = parseInt(inputInkomen3.val()) | 0;

				var total = val1 + val2 + val3;
				inputTotal.val(total);
			}
		},
		methods : {
			init : function () {
        form = $('#form_1BCFB1F333F848E0BB345A6C2DE83E8C');
				if (!form.length) {
					return;
				}

				inputInkomen1 = $('#form_1BCFB1F333F848E0BB345A6C2DE83E8C_field_69CC92D8CCA74621942F76F96AC23F03');
				inputInkomen2 = $('#form_1BCFB1F333F848E0BB345A6C2DE83E8C_field_A355758B37B64128853FB0A50F9217D7');
				inputInkomen3 = $('#form_1BCFB1F333F848E0BB345A6C2DE83E8C_field_7401A9638C394FEF84433BC4F233CD7B');
				inputTotal = $('#form_1BCFB1F333F848E0BB345A6C2DE83E8C_field_6D68BABDC69A47EA8F44ACDB8FA4FB7E');

				inputTotal.attr('readonly', 'true');
				inputTotal.css('background', 'transparent');

				inputInkomen1.attr('maxlength', 8).on('changed, blur, keyup', function(e) {
					app.events.onChanged();
				});

				inputInkomen2.attr('maxlength', 8).on('changed, blur, keyup', function(e) {
					app.events.onChanged();
				});

				inputInkomen3.attr('maxlength', 8).on('changed, blur, keyup', function(e) {
					app.events.onChanged();
				});

				APP.trace('Log: [form|huren jaarinkomen] Instantiate form...');

			}
		}
    };

    return {
    	init : app.methods.init
    };

}($));
;

APP.namespace('APP.Form');

APP.Form.Registreer = (function($){
    var app;

    app = {
    	events : {
			onChangeCheckboxVoorwaarden : function() {
				if ($("#content_0_chkVoorwaarden").is(':checked')) {
					$("#content_0_cstValVoorwaarden").hide();
				} else {
					$("#content_0_cstValVoorwaarden").show();
				}
			}
		},
		methods : {
			init : function () {
				if (!$('[data-js-form="regisreer"]').length) {
					return;
				}

				APP.trace('Log: [form|registreer] Instantiate form...');

				app.methods.attach();
			},
			attach : function () {
				$("#content_0_chkVoorwaarden")
					.off('change', app.events.onChangeCheckboxVoorwaarden)
					.on('change', app.events.onChangeCheckboxVoorwaarden);
			}
		},
		validator : {
            checkboxVoorwaarden: function (sender, e) {
                e.IsValid = $("#content_0_chkVoorwaarden").is(':checked');
			}
		}
    };

    return {
    	init : app.methods.init,
		Validator : {
			checkboxVoorwaarden : app.validator.checkboxVoorwaarden
		}
    };

}($));
;

APP.namespace('APP.Form');

APP.Form.SearchRealEstate = (function(window, document){

    var app,
        jqObj,
        data,
        submitted;

    app = {
        config : {

            /*
             * baseUrl
             *  base urls to redirect a visitor to the correct page...
             *
             */

            baseUrl : {
                huur : '/te-huur/vrije-sector-huur/zoek?',
                koop : '/te-koop/zoek?',
                bedrijf : '/te-huur/ondernemen/zoek?',
                parkeer : '/te-huur/parkeren/zoek?'
            }
        },
        events : {

            /*
             * onClick()
             *  Event handler for [data-form-submit="search-real-estate"] button...
             *
             */

            onClick : function (evt) {
                evt.preventDefault();
                app.methods.submitHandler();
            }
        },
        methods : {

            /*
             * init()
             *  Instantiate component...
             *
             */

            init : function () {
                jqObj = $('button[data-form-submit="search-real-estate"]');

                if (!jqObj.length) {
                    return;
                }

                $('select[data-field="sort"]').on('change', function () {
                    app.methods.submitHandler();
                });

                APP.trace('Log: [form.search-real-estate] Instantiate form...');

                app.methods.attach();
            },

             /*
             * getExtendedSearchFields()
             *  Return the fields in the extended search panel...
             *
             */

            getExtendedSearchFields: function () {
                var type = (jqObj.data('form-type') || $('.select-soort select').val()),
                    fields = {
                        huur: [
                            'bouwvorm',
                            'kamers',
                            'oppervlakte',
                            'woningtype',
                            'postcode',
                            'straal'
                        ],
                        bedrijf: [
                            'bestemming',
                            'oppervlakte',
                            'postcode',
                            'straal',
                            'adres'
                        ],
                        parkeer: [
                            'prijs_min',
                            'prijs_max',
                            'status',
                            'type'
                        ],
                        koop: [
                            'bouwvorm',
                            'kamers',
                            'oppervlakte',
                            'woningtype',
                            'postcode',
                            'straal'
                        ]
                    };

                return (typeof fields[type] !== 'undefined' ? fields[type] : []);
            },

            /*
             * getLocationHashParams()
             *  Get the query parameters based on the location hash...
             *
             */

            getLocationHashParams: function (h) {
                var hash = (h.indexOf('#/&&') !== -1 ? h.replace('#/&&', '') : h),
                    params = APP.Utilities.URL.getQueryParams(hash);

                return (typeof params !== 'undefined' ? params : {});
            },
            
            /*
             * getFormData()
             *  Return form data...
             *
             *  @return     data    object
             *
             */

            getFormData : function () {
                var data = {
                    form : ( jqObj.data('form-type') || $('.select-soort select').val() ),     // form (eg. huur, koop, parkeer, bedrijf)
                    regions : $('.select-plaats select').val() || null,                        // plaats of stadsdeel
                    adres : $('input[data-field="address"]').val() || null,                    // postcode of straatnaam
                    prijs_min : $('select[data-range-selector="from"]').val() || null,         // minimum prijs 
                    prijs_max: $('select[data-range-selector="to"]').val() || null,            // maximum prijs 
                    straal : $('select[data-field="radius"]').val() || null,                   // straal
                    woningtype : $('select[data-field="objecttype"]').val() || null,           // woningtype
                    type: $('select[data-field="type"]').val() || null,                        // bouwvorm
                    status : $('select[data-field="status"]').val() || null,                   // status of beschikbaarheid
                    bouwvorm: $('select[data-field="construction"]').val() || null,            // bouwvorm
                    oppervlakte : $('select[data-field="surface"]').val() || null,             // oppervlakte
                    kamers : $('select[data-field="rooms"]').val() || null,                    // aantal kamers
                    bestemming : $('select[data-field="destination"]').val() || null,          // bestemming
                    contract: ($('select[data-field="contract"]').val() || null),              // contract
                    sort: ($('select[data-field="sort"]').val() || null),                      // contract
                    page : 0                                                                   // pagination start
                };
                
                data.view = ($('input[name="view"]').val() || (data.form === 'parkeer' ? 'Map' : 'List'));

                return data;
            },

            /*
             * getRedirectUrl()
             *  Return url with correct parameters for search request...
             *
             *  @return     url    string
             *
             */

            getRedirectUrl : function () {
                var k, url;

                if (typeof app.config.baseUrl[data.form] === 'undefined') return;

                // base url...
                url = app.config.baseUrl[data.form];

                // build url parameters...
                for (k in data) {
                    if ( data.hasOwnProperty(k) && (data[k] && k !== 'form') ) {
                        url += '&'+ k +'=' + data[k];
                    }
                }

                return url;
            },

            /*
             * getTrackingString()
             *  Return string which can be send to Analytics...
             *
             *  @return     tracking    string
             *
             */

            getTrackingString: function () {

                console.log(data.form);
                var i,
                    cities = [],
                    tracking = 'Zoekformulier ' + data.form;

                if (data.form !== 'huur' && data.form !== 'bedrijf') {
                    tracking += ' | Van: '+ data.price_min;
                    tracking += ' | Tot: '+ data.price_max;
                }

                if (data.regions) {
                    for (i=0; i<data.regions.length; i++) {
                        if (data.regions.hasOwnProperty(i)) {
                            cities.push( $('.select-plaats select').find('option[value="'+ data.regions[i] +'"]').text() );
                        }
                    }

                    if (cities.length === 0) {
                        tracking += ' | Plaats/stadsdeel: Niet geselecteerd';
                    } else {
                        tracking += ' | Plaats/stadsdeel: ' + cities.sort().join(', ');
                    }

                }

                return tracking;
            },

            /*
             * openPanel()
             *  Open extended search panel when there's a valid
             *   query in url hashbang...
             *
             */

            togglePanel: function () {
                var params = app.methods.getLocationHashParams(window.location.hash),
                    fieldsToCheck,
                    filtered;

                if ($.isEmptyObject(params)) {
                    return;
                }

                fieldsToCheck = app.methods.getExtendedSearchFields();
                filtered = [];

                filtered = fieldsToCheck.filter(function (key) {
                    if (typeof params[key] !== 'undefined') {
                        var value = (key === 'prijs_max' ? $('select[data-range-selector="to"] option').last().val() : '-1');

                        return (params[key][0] !== '0' && params[key][0] !== value);
                    }

                    return false;
                });

                if (filtered.length) {
                  $('#extended-search').addClass('collapse in');
                  $('div[data-target="#extended-search"]').attr('aria-expanded', true);
                }
            },

            /*
             * submitHandler()
             *  Handle the submit request, send tracking event and call the callback...
             *
             */

            submitHandler : function () {
                data = app.methods.getFormData();

                var tracking = app.methods.getTrackingString(data);

                APP.Core.Tracking.set({
                    trackingType : 'event',
                    eventCategory : 'Button',
                    eventAction : 'click',
                    eventLabel : tracking,
                    hitCallback : app.methods.redirectVisitor
                });

                // create timeout to trigger submitHandler when hitCallback fails...
                setTimeout(app.methods.redirectVisitor, 1000);

            },

            /*
             * redirectVisitor()
             *  Handle the redirect when form hasn't been submitted yet...
             *
             */

            redirectVisitor : function () {
                if (submitted) {
                    return;
                }

                submitted = true;

                window.location.href = app.methods.getRedirectUrl();
            },

            /*
             * attach()
             *  Bind DOM events...
             *
             */

            attach: function () {
                jqObj
                    .off('click', app.events.onClick)
                .on('click', app.events.onClick);
            }
        }
    };

    return {
        init: app.methods.init,
        togglePanel: app.methods.togglePanel,
    };

}(window, document));
;

APP.namespace('APP.Form');

APP.Form.WoningRuil = (function ($) {

    var app,
        relatiepartner2Container,
        optionalUploadFields = [];

    // check for this specific form ID so we know it's the woningruil form
    var form;

    var submitId = '#form_B6F93B893EA743AAA2C51F2F7A64A42D_form_B6F93B893EA743AAA2C51F2F7A64A42D_submit';

    var relatiepartner2RequiredFields = new Object();

    app = {
        events: {

            onChangeSelectRuilPartners: function () {
                var value = this.value;
                if (value === "2") {
                    relatiepartner2Container.show();
                } else {
                    relatiepartner2Container.children().find('input,select').each(function () {
                        $(this).val('');
                    });
                    relatiepartner2Container.hide();
                }
            },
            onChangeRelatiepartner2RequiredFields: function () {

                var errorcontainer = $(this).parent().find('.scfValidatorRequired');

                var isRadioButton = false;
                if ($(this).parent().hasClass("customcheckbox")) {
                    isRadioButton = true;
                }

                if (isRadioButton === false) {
                    var value = $.trim($(this).val());
                    if (value.length !== 0) {
                        errorcontainer.hide();
                    } else {
                        errorcontainer.show();
                    }
                } else {
                    errorcontainer = $(this).closest('.scfRadioButtonListGeneralPanel').find('.scfValidatorRequired');
                    errorcontainer.hide();
                }
            },

            addUploadFieldsButtonClick: function () {
                for (var index = 0; index < optionalUploadFields.length; ++index) {
                    var item = optionalUploadFields[index];
                    if (!item.is(":visible")) {
                        item.show();
                        if (index === (optionalUploadFields.length - 1)) {
                            $('.add-upload-fields-button').hide();
                        }
                        break;
                    }
                }
            },
            onSubmitClick: function () {

                if (! relatiepartner2Container.is(":visible")) {
                    return true;
                }

                var errors = false;

                for (var index in relatiepartner2RequiredFields) {
                    var container = relatiepartner2RequiredFields[index];

                    if (container.find('.customcheckbox').length) {
                        if (!container.find('.customcheckbox.checked').length) {
                            $(container).find('.scfValidatorRequired').show();
                            errors = true;
                        }
                    }
                    else {
                        var input = $(container).find('input');
                        var value = $.trim($(input).val());
                        if (value.length === 0) {
                            $(container).find('.scfValidatorRequired').show();
                            errors = true;
                        }
                    }
                }
                if (errors === true) {
                    return false;
                } else {
                    return true;
                }
            }
        },

        methods: {
            init: function () {
                form = $('#form_B6F93B893EA743AAA2C51F2F7A64A42D');
                if (!form.length) {
                    return;
                }

                app.methods.setRelatiepartner2Customisation();
                app.methods.setOptionalUploadFields();
                app.methods.attach();
                app.methods.validate();
            },


            setRelatiepartner2Customisation : function() {
                // add select
                var ruilpartnerselecthtml =
                    '<div class="scfDropListBorder"><label class="scfDropListLabel">Aantal ruilpartners</label><div class="scfDropListGeneralPanel"><select name="selectRuilpartners" class="scfDropList selectRuilpartners"><option value="1">1</option><option value="2">2</option></select></div></div>';

                // Arbitrary choice to retrieve container
                var achternaamfield =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_B02A101568AF4EF8A4C20DC4770EF1EB_scope");
                var mijngegevenscontainer = achternaamfield.closest(".scfSectionContent");

                mijngegevenscontainer.append(ruilpartnerselecthtml);

                // Arbitrary choice to retrieve container for relatiepartner2
                var achternaamRelatiepartner2Field =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_E6C7F9921731402B83A15ABDBFDF14E4_scope");

                relatiepartner2Container = achternaamRelatiepartner2Field.closest(".scfSectionBorderAsFieldSet")
                    .parent();

                relatiepartner2Container.hide();

                relatiepartner2RequiredFields["aanhef"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_50C0E845389648F3A0C7C9E41AFAD215");
                relatiepartner2RequiredFields["voorletters"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_FEFB21A5226B40DE8FA665CD18DB5325_scope");
                relatiepartner2RequiredFields["achternaam"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_E6C7F9921731402B83A15ABDBFDF14E4_scope");
                relatiepartner2RequiredFields["geboortedatum"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_8B1CE2007CDC46DBADB5465B73DC2F11_scope");
                relatiepartner2RequiredFields["postcode"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_74F4B7B3F6B8489B8A11D8603961A86D_scope");
                relatiepartner2RequiredFields["huisnummer"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_72BB30B675FC44C381436CA9FBFBBBBD_scope");
                relatiepartner2RequiredFields["etage"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_513E88ADE7654EEF96B23AEE5D8FCC8E_scope");
                // disabled straat and plaats because of pro6pp autofill
                // relatiepartner2RequiredFields["straatnaam"] = $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_BBD0113294464262B90609A81938893A_scope");
                // relatiepartner2RequiredFields["plaats"] = $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_98246C6F15EC43EBA40F2C108F17BC40_scope");
                relatiepartner2RequiredFields["lift"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_2B3033DED2054DAEB3F28709F6DACFAE");
                relatiepartner2RequiredFields["kamers"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_AD56B57EBAAE4E6FAF3FB184BE32A923_scope");
                relatiepartner2RequiredFields["telefoonnummer"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_26E00659BA8D4C3D9A394B332619C1F5_scope");
                relatiepartner2RequiredFields["emailadres"] =
                    $("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_218E27E4415F452CB757EB9BE1235003_scope");

                var requiredspan = '<span class="scfRequired">*</span>';
                var errormessagespan =
                    '<span  title="Veld is verplicht" class="scfValidatorRequired" style="display:none;">Veld is verplicht</span>';

                for (var index in relatiepartner2RequiredFields) {
                    relatiepartner2RequiredFields[index].append(requiredspan);
                    $(relatiepartner2RequiredFields[index]).find("div").first().append(errormessagespan);
                }
            },

            setOptionalUploadFields: function () {

                optionalUploadFields
                    .push($("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_E98A4E74B30546CB927077CDDFD7AB74scope")
                        .addClass('optional-upload-field')
                        .hide());
                optionalUploadFields
                    .push($("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_8AAFE2BDFC3D4589A8ED87FF390432BBscope")
                        .addClass('optional-upload-field')
                        .hide());
                optionalUploadFields
                    .push($("#form_B6F93B893EA743AAA2C51F2F7A64A42D_field_2848FB196B24436CAB3CB5D68108BF83scope")
                        .addClass('optional-upload-field')
                        .hide());

                var buttoncontainerhtml =
                    '<div class="scfFileUploadBorder"><label></label><div class="scfFileUploadGeneralPanel optionaluploadbuttoncontainer"></div></div>';

                var buttonhtml =
                    '<button type="button" class="add-upload-fields-button" data-event="add-row" style="border: 0; background: none; color: #1570a5; outline: 0;">' +
                        '<span class="icon icon-20px icon-plus"></span> Inkomensverklaring upload veld toevoegen</button>';

                $(".optional-upload-field").wrapAll("<div class='optional-upload-field-container' />");

                var inkomstenverklaring1FieldContainer = $('.optional-upload-field-container');
                inkomstenverklaring1FieldContainer.append(buttoncontainerhtml);
                $('.optionaluploadbuttoncontainer').append(buttonhtml);
            },

            validate: function () {
                var submitObject = $(submitId);

                if (!submitObject.length) {
                    return;
                }

                submitObject.on('click', app.events.onSubmitClick);
            },
            attach: function () {
                $('.add-upload-fields-button').on('click', app.events.addUploadFieldsButtonClick);
                $('.selectRuilpartners').change(app.events.onChangeSelectRuilPartners);

                for (var index in relatiepartner2RequiredFields) {
                    var container = relatiepartner2RequiredFields[index];
                    $(container).find('input').change(app.events.onChangeRelatiepartner2RequiredFields);
                }
            }
        }
    };

    return {
        init: app.methods.init
    };

}($));
;

APP.namespace('APP.Form');

APP.Form.Woonwensen = (function($){
    var app;

    app = {
    	events : {
			onChangeCheckboxKoopHuur : function() {
				if ($("#housingPrefModel_HasHuurwoningen").is(':checked') || $("#housingPrefModel_HasKoopwoningen").is(':checked')) {
					$("#cstValVoorwaarden").hide();
				} else {
					$("#cstValVoorwaarden").show();
				}
			}
		},
		methods : {
			init : function () {
				if (!$('[data-js-form="woonwensen"]').length) {
					return;
				}

				APP.trace('Log: [form|woonwensen] Instantiate form...');

				app.methods.attach();
			},
			attach : function () {
				$('#housingPrefModel_HasHuurwoningen, #housingPrefModel_HasKoopwoningen')
					.off('change', app.events.onChangeCheckboxKoopHuur)
					.on('change', app.events.onChangeCheckboxKoopHuur);

				$('[data-js-form="woonwensen"]')
					.off('submit')
					.on('submit', function (event) { 
						app.events.onChangeCheckboxKoopHuur();
						return $("#cstValVoorwaarden").is(":hidden");
					});
			}
		},
		validator : {
			checkboxKoopHuur : function(sender, e){
			    e.IsValid = ($("#housingPrefModel_HasHuurwoningen").is(':checked') || $("#housingPrefModel_HasKoopwoningen").is(':checked'));
			}
		}
    };

    return {
    	init : app.methods.init,
		Validator : {
			checkboxKoopHuur : app.validator.checkboxKoopHuur
		}
    };

}($));
;
APP.namespace('APP.Form');

APP.Form.Emandate = (function (window, document) {

  var app,
    formObj;

  app = {
    methods: {
      isActive: function () {
        return formObj.length;
      },
      init: function () {
        formObj = $('form[action^="/weten-en-regelen/sociale-huur/huur-en-betalen/automatisch-incasso-formulier"]');
        if (!app.methods.isActive()) {
          return;
        }

        APP.trace('[form.emandate.init] Init form...');
        APP.Form.Emandate.active = true;

        // app.methods.toggleDiv();     obsolete, because radio buttons 'parkeren' and 'bedrijfsruimte'
        // app.methods.attach();         are removed from the template, if you need it check git (2017.04.18) !

        // render form...
        app.methods.showResultPage();
      },
      showResultPage: function () {
        var el = $('#form_977BF9A9071A498B997C3CBF6F12279C .check-form');

        if (!el.length) {
          return;
        }

        $('label').each(function () {
          var el = $(this),
            text = $.trim(el.text()),
            nextText = $.trim(el.next('.check').text());

          if (text === 'Type huurobject' && nextText === 'Parkeerplaats') {
            $('label').each(function () {
              var el = $(this),
                labelText = $.trim(el.text());

              if (labelText === 'Postcode' || labelText === 'Huisnummer') {
                el.parents('.row:eq(0)').hide();
              }
            });
          }
        })
      }
    }
  };

  return {
    init: app.methods.init
  };

}(window, document));;
APP.namespace('APP.Form');

APP.Form.HuurParkeerruimteOpzeggen = (function($) {
  var form;
  var explainScope;
  var formRef = 'form_26D4E93C185248A18A4507CF29FC4565';
  var reasonSelectFieldId = '#form_26D4E93C185248A18A4507CF29FC4565_field_5F15091D77624D91B8937AE254FC73AF';
  var otherExplainFieldId = '#form_26D4E93C185248A18A4507CF29FC4565_field_0399D4FC256D4F0186036A9C7BE7CBC9';
  var requiredSpan = '<span class="scfRequired">*</span>';
  var errormessageSpan = '<span  title="Namelijk is een verplicht veld" class="scfValidatorRequired" style="display:none;">Namelijk is een verplicht veld</span>';

  var app = {
    events: {
      onChangeReasonSelect: function() {
        var value = this.value;
        if (value === 'Anders') {
          explainScope.show();
        } else {
          explainScope.hide();
        }
      },

      onSubmitClick: function(e) {
        return app.methods.validateExplainScope();
      }
    },

    methods: {
      init: function() {
        form = $('#' + formRef);
        explainScope = $(otherExplainFieldId + '_scope');
        if (!form.length || !explainScope.length) {
          return;
        }
        app.methods.prepareHtml();
        app.methods.attach();
        app.methods.extendValidation();
      },

      prepareHtml: function() {
        explainScope.find('.scfSingleLineGeneralPanel').append(requiredSpan);
        explainScope.find('div').first().append(errormessageSpan);
      },

      attach: function() {
        $(reasonSelectFieldId).change(app.events.onChangeReasonSelect);
        explainScope.blur(app.methods.validateExplainScope);
        explainScope.change(app.methods.validateExplainScope);
        // wait a bit before checking the value
        window.setTimeout(function() {
          if ($(reasonSelectFieldId).val() === 'Anders') {
            explainScope.show();
          }
        }, 10);
      },

      extendValidation: function () {
        var submitObject = $('#' + formRef + '_' + formRef + '_submit');

        if (!submitObject.length) {
          return;
        }

        submitObject.on('click', app.events.onSubmitClick);
      },

      validateExplainScope: function() {
        if (!explainScope.is(':visible')) {
          explainScope.find('input').val('');
          explainScope.find('.scfValidatorRequired').hide();
          return true;
        }
        var value = $.trim(explainScope.find('input').val());
        if (value.length === 0) {
          explainScope.find('.scfValidatorRequired').show();
          return false;
        }
        explainScope.find('.scfValidatorRequired').hide();
        return true;
      }
    }
  };

  return {
    init: app.methods.init
  };
}($));
;

APP.namespace('APP.Form');

APP.Form.Huurverlaging = (function($){

    var app,
        formSelector;

    app = {
        events : {
            onSubmit : function (evt) {
            }
        },
        methods : {
          init: function () {
              formSelector = $('#main_0_form_7731A9E6067F4D3EA70F0440D4F0B269_pnlForm');
              if (!formSelector.length) {
                // try to hide intro on confirmation page
                app.methods.hideIntroOnConfirmation();
                return;
              }

              APP.trace('Log: [form.huurverlaging] Instantiate form...');
              app.methods.attach();
          },

          attach : function () {
              app.methods.initHuurVerlagingSections();
          },

          hideIntroOnConfirmation: function() {
            var confirmation = $('#main_0_form_7731A9E6067F4D3EA70F0440D4F0B269_ehFormulierBevestigingspagina_divBevestigingWebsite');
            if (confirmation.length === 0) return;
            $('p.intro').parents('div.row.row-margin').hide();
          },

          initHuurVerlagingSections: function ()
          {
            var elHuurverlaging = $('input[name=HuurverlagingUpdateSections]');
            if (elHuurverlaging.length === 0) return;

            var sectionInfo = JSON.parse(elHuurverlaging.val());

            var loonUitkSections = formSelector.find('.hide-loonuitk');
            loonUitkSections.each(function (index) {
              if (index >= sectionInfo.loonuitkering) {
                $(this).hide();
              } else {
                $(this).show();
                app.methods.setUploadRequired(this);
              }
            });

            var aowSections = formSelector.find('.hide-aow');
            aowSections.each(function (index) {
              if (index >= sectionInfo.aow) {
                $(this).hide();
              } else {
                $(this).show();
                app.methods.setUploadRequired(this);
              }
            });

            var zzpSections = formSelector.find('.hide-zzp');
            zzpSections.each(function (index) {
              if (index >= sectionInfo.zzp) {
                $(this).hide();
              } else {
                $(this).show();
                app.methods.setUploadRequired(this);
              }
            });

            // Todo add extra events on submit to check if visible upload fields have files.
            formSelector.find('input[type=submit]').on('click',
              function (event) {
                // validate file submits
                var result = true;
                formSelector.find('.scfFileUploadGeneralPanel:visible').each(function (index) {
                  var value = $(this).find('input').val();
                  var $validator = $(this).find('.scfValidatorRequired');
                  if (value.length === 0) {
                    $validator.each(function (index2) { $(this).show(); });
                    result = false;
                  } else {
                    $validator.each(function (index3) { $(this).hide(); });
                  }
                });

                // validate akkoord
                var elAkkoord = $('#main_0_form_7731A9E6067F4D3EA70F0440D4F0B269_field_19108CD8E4364A80B3262FD99D6582FE');
                if(!app.methods.validateRequiredCheckbox(elAkkoord)) {
                  result = false;
                }

                // validate waarheid
                var elWaarheid = $('#main_0_form_7731A9E6067F4D3EA70F0440D4F0B269_field_817D7E8C2F6D44608B2D60C333C1D15F');
                if(!app.methods.validateRequiredCheckbox(elWaarheid)) {
                  result = false;
                }

                if (!result) {
                  var firstError = formSelector.find('.scfValidatorRequired:visible').first();
                  var scrollto = firstError.offset().top - formSelector.offset().top + formSelector.scrollTop();
                  $(document).scrollTop(scrollto);
                  event.preventDefault();
                }
              });
          },

          setUploadRequired: function (section) {
            $(section).find('.scfFileUploadGeneralPanel').each(function (index) {
              var fieldLabelText = $(this).parent('div').find('label').first().text();
              if (/aanvullend/i.test(fieldLabelText) || /optioneel/i.test(fieldLabelText) || /pensioen specificatie/i.test(fieldLabelText) || /bijstand specificatie/i.test(fieldLabelText)) return;
              $(this).append(
                '<span title="Dit is een verplicht veld" class="scfValidatorRequired" style="display:none;">Dit is een verplicht veld</span><span class="scfRequired">*</span>');
            });
          },

          validateRequiredCheckbox: function (checkbox) {
            if ($(checkbox).find('input:checked').length === 0) {
              $(checkbox).find('.scfValidatorRequired').each(function (index) {
                $(this).show();
                return false;
              });
            } else {
              $(checkbox).find('.scfValidatorRequired').each(function (index) {
                $(this).hide();
              });
              return true;
            }
          }
      }

    };

    return {
        init : app.methods.init
    };

}($));
;
APP.namespace('APP.Frontend');

APP.Frontend.Bottom = (function ($) {
  "use strict";

  var app,
    bottom;

  app = {
    methods: {
      set: function (options) {
        $.extend(app.config, options);
      },
      init: function (options) {
        bottom = $('#bottom');
        if (typeof options === 'object') {
          app.methods.set(options);
        }

        APP.trace('Log: [frontend|bottom] Instantiate bottom...');

        app.methods.build();
      },
      build: function () {
        if (!bottom.find('.block').length) {
          bottom.remove();
        }
      }
    }
  };

  return {
    init: function (options) {
      app.methods.init(options);
    }
  };

}($));;
APP.namespace('APP.Frontend');

APP.Frontend.Footer = (function (window, document) {
    "use strict";

    var app,
        footer,
        menu;

    app = {
        config: {
            active: false
        },
        events: {
            onResize: function () {
                app.methods.create();
            }
        },
        methods: {
            isDesktop: function () {
                return (footer.find('.container').width() >= 720);
            },
            init: function () {
                footer = $('#footer');
                menu = footer.find('.footer-top ul.collapse');                    

                if (!menu.length) return;

                APP.trace('Log: [frontend|footer] Instantiate footer...');

                app.methods.create();
                app.methods.bind();

                return true;
            },
            create: function () {
                if (app.methods.isDesktop()) {
                    app.methods.destroy();
                } else {
                    app.methods.build();                    
                }
            },
            destroy: function () {
                if (!app.config.active) return;

                app.config.active = false;

                menu.each(function () {
                    var el = $(this),
                        link = (el.prev().is('h3') ? el.prev().find('a') : null);

                    if (link && link.length) {
                        el.removeAttr('id');
                        el.removeAttr('style');
                        el.find('li.is-copied').remove();

                        link.removeAttr('data-toggle');
                        link.attr('href', link.attr('data-href'));
                    }
                })
            },
            build: function () {
                if (app.config.active) return;

                app.config.active = true;

                var index = 0;

                menu.each(function () {
                    var el = $(this),
                        link = (el.prev().is('h3') ? el.prev().find('a') : null),
                        linkClone,
                        href,
                        id;

                    if (link && link.length) {
                        href = link.attr('href');
                        id = 'footer-link-' + index++;

                        el.attr('id', id);
                        linkClone = link.clone();

                        link.attr('data-toggle', 'collapse');
                        link.attr('data-href', href);
                        link.attr('href', '#' + id);

                        if (link.text().trim() !== el.find('li:first a').text().trim()) {
                            var li = $('<li/>', {
                                'class' : 'is-copied'
                            });
                            li.append( linkClone )
                            el.prepend( li );
                        }
                    }
                })
            },
            bind: function () {
                $(window)
                    .off('resize orientationChanged', app.events.onResize)
                    .on('resize orientationChanged', app.events.onResize)
            }
        }
    };

    return {
        init : app.methods.init
    };

}(window, document));;
APP.namespace('APP.Frontend');

APP.Frontend.Navigation = (function ($, window) {
  "use strict";

  var app,
    navigation,
    domWindow,
    containerWidth = 0;

  app = {
    config: {

    },
    events: {

      onResize: function () {
        if (!navigation.hasClass('in')) {
          return;
        }

        var newWidth;

        newWidth = $('.container').width();

        //only horizontal resizing
        if (newWidth !== containerWidth) {
          containerWidth = newWidth;
          navigation.collapse('hide');
        }
      }
    },
    methods: {
      set: function (options) {
        $.extend(app.config, options);
      },
      init: function (options) {

        navigation = $('.main-navigation');
        domWindow = $(window);
        if (typeof options === 'object') {
          app.methods.set(options);
        }

        containerWidth = $('.container').width();

        APP.trace('Log: [frontend|navigation] Instantiate navigation...');

        app.methods.build();
        app.methods.attach();
      },
      toggleClass: function (type) {
        switch (type) {
          case 'open':
            navigation.parent().find('.navbar-toggle > .icon')
              .toggleClass('icon-navbar-hamburger', false)
              .toggleClass('icon-navbar-close', true);
            break;
          case 'close':
            navigation.parent().find('.navbar-toggle > .icon')
              .toggleClass('icon-navbar-hamburger', true)
              .toggleClass('icon-navbar-close', false);
            break;
        }
      },
      build: function () {

        // close login-menu when when clicking other menu's
        $('.nav-link[data-toggle="dropdown"], .b-navbar.b-menu').on('click', function (e) {
          $('.login-menu.collapse[aria-expanded="true"]').collapse('hide');
        });

        // close main menu when when clicking other menu's
        $('.b-navbar.b-login').on('click', function (e) {
          $('.main-navigation.collapse[aria-expanded="true"]').collapse('hide');
        });

        // use enter to submit the search
        $('#navigation input[type=text]').on('keypress', function (e) {
          if (e.which == 13) {
            if ($(this).val() === '') {
              e.preventDefault();
            } else {
              $('#navigation button[type=submit]').trigger('click');
            }
          }
        });

        // Check Bootstrap API documentation before changing these events...
        // Hidden event...
        navigation.on('hidden.bs.collapse', function () {
          var element,
            navCollapse;

          element = $(this);
          navCollapse = element.find('.navbar-collapse');

          element.removeAttr('style');
          navCollapse.find('ul:eq(0)').removeAttr('style');
        });

      },
      attach: function () {
        domWindow.on('resize', app.events.onResize);
      }
    }
  };

  return {
    init: function (options) {
      app.methods.init(options);
    }
  };

}($, window));;

APP.namespace('APP.Helper');

APP.Helper.placeholder = (function($) {

    return {
        create : function (options) {
            if (typeof options !== 'object') {
                return;
            }

            var el;

            el = options.element;
            
			el.each(function(){			
				var element,
					label,
					textValue;
				
				element = $(this);						
				element.addClass('emptyfield');
				
				if (element.val() !== ''){
					textValue = element.val();
				} else {
					label = $(this).prev();
					if (label.hasClass('hidden')) {
						textValue = label.text();
					}
				}

				if (element.val() === ''){
					element.val(textValue);
				}

				element.focus(function(){
					var el;
					
					el = $(this); 
					
					if (el.hasClass('emptyfield')){
						el.removeClass('emptyfield').val('');
					}
				});

				element.blur(function(){
					var el;
					
					el = $(this); 
					
					if (el.val() === ''){
						el.val(textValue).addClass('emptyfield');
					}
				});
			});			
        }
    }
}($));
;

APP.namespace('APP.Helper');

APP.Helper.wordwrap = (function($) {

    return {
        create : function (options) {
            if (typeof options !== 'object') {
                return;
            }

            var el;

            el = options.element;
            el.each(function(){
                var object,
                    wordArray = [];

                object = $(this)[0];
                wordArray = object.innerHTML.split(' ');

                while(object.scrollHeight > object.offsetHeight) {
                    wordArray.pop();
                    object.innerHTML = wordArray.join(' ')  + '...';
                }
            });
        }
    }
}($));
;

APP.namespace('APP.Plugin');

APP.Plugin.Align = (function ($, window) {
  "use strict";

  var app,
    domWindow,
    element;

  app = {
    events: {
      onResize: function () {
        app.methods.build();
      }
    },
    methods: {
      update: function () {
        element = $('[data-align="vertical"],[data-align="horizontal"]');

        if (!element.length) {
          return;
        }

        app.methods.build();
      },
      init: function () {
        domWindow = $(window);
        element = $('[data-align="vertical"],[data-align="horizontal"]');
        if (!element.length) {
          return;
        }

        APP.trace('Log: [plugin|align] Instantiate plugin...');

        app.methods.build();
        app.methods.attach();
      },
      build: function () {
        element.each(function () {
          var element,
            type,
            limit,
            width;

          element = $(this);
          type = element.attr('data-align');
          limit = element.data('align-limit');
          width = $('.container').width();

          //reset...
          element.removeAttr('style');

          //check limit and calculate alignment...
          //limit is maximum width of container to accept the alignment...
          if (!limit || width <= limit) {
            if (type === 'horizontal') {
              element.css({
                marginLeft: (($(this).parent().outerWidth() - $(this).outerWidth()) / 2),
                display: 'inline-block'
              });
            }

            if (type === 'vertical') {
              element.css({
                marginTop: (($(this).parent().outerHeight() - $(this).outerHeight()) / 2),
                display: 'inline-block'
              });
            }
          }
        });
      },
      attach: function () {
        domWindow.unbind('resize', app.events.onResize).on('resize', app.events.onResize);
      }
    }
  };

  return {
    init: function () {
      app.methods.init();
    },
    update: function () {
      app.methods.update();
    }
  };

}($, window));;

APP.namespace('APP.Plugin');

APP.Plugin.ExternalLink = (function($, window) {
    "use strict";

    var app;

    app = {
        events : {

        },
        methods : {
			update : function() {
                
                $('.block a[target="_blank"]').each(function(e) {
                    if($(this).find('img').length == 0) {
                        $(this).addClass('external-link');
                    }
                });

            },
            init : function () {

                APP.trace('Log: [plugin|externallink] Instantiate plugin...');
                app.methods.update();

            }
        }
    };

    return {
        init : function () {
            app.methods.init();
        },
        update : function () {
            app.methods.update();
        }
    };

}($, window));;
APP.namespace('APP.Utilities');

APP.Utilities.Datepicker = (function ($) {
  "use strict";

  var app,
    element;

  app = {
    defaults: {
      options: {
        dateFormat: 'dd-mm-yy',
        autoSize: true,
        buttonImage: '/assets/images/icon-ui-calendar.svg',
        buttonImageOnly: true,
        buttonText: 'Selecteer een datum',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        showOn: 'both',
        showOtherMonths: true,
        showWeek: true
      }
    },
    methods: {
      set: function (newOptions) {
        $.extend(app.defaults.options, newOptions);
      },
      attach: function () {
        element = $('input[data-util="datepicker"]');
        element.datepicker(app.defaults.options);
      },
      destroy: function () {
        element.datepicker('destroy').removeAttr('id');
      }
    }
  };

  return {
    set: function (options) {
      if (typeof options === 'object') {
        app.methods.set(options);
      }
    },
    attach: function () {
      app.methods.attach();
    },
    destroy: function () {
      app.methods.destroy();
    }
  };

}($));;
APP.namespace('APP.Utilities');

APP.Utilities.Print = (function ($, window) {
  "use strict";

  var app,
    element;

  app = {
    events: {
      onClick: function (evt) {
        evt.preventDefault();
        window.print();
      }
    },
    methods: {
      attach: function () {
        element = $('[data-util="print"]');
        element.on('click', app.events.onClick);
      }
    }
  };

  return {
    attach: function () {
      app.methods.attach();
    }
  };

}($, window));;

APP.namespace('APP.Utilities');

APP.Utilities.URL = (function (window, document) {
    "use strict";

    var app;

    app = {
        methods: {
            build: function (data, url) {
                var i;

                url = url || '';

                for (i in data) {
                    if (data.hasOwnProperty(i) && data[i].length) {
                        url += app.methods.questionOrAmpersand(url);
                        url += i + '=' + data[i].toString();
                    }
                }

                return app.methods.getEncodedUrlString(url);
            },
            getEncodedUrlString: function (str) {
                return encodeURI(str);
            },
            getQueryParams: function (input) {
                var search = input || document.location.search,
                    qs = search.split('+').join(' '),
                    re = /[?&]?([^=]+)=([^&]*)/g,
                    params = {},
                    tokens;

                while (tokens = re.exec(qs)) {
                    var key = decodeURIComponent(tokens[1]),
                        value = decodeURIComponent(tokens[2]);

                    if (key.length && value.length) {
                        params[key] = (key !== 'q' ? value.split(',') : value);
                    }
                }

                return (!$.isEmptyObject(params) ? params : undefined);
            },
            questionOrAmpersand: function (string) {
                if (string.indexOf('?') === -1) {
                    return '?';
                }
                if (string.slice(-1) !== '?') {
                    return '&';
                } else {
                    return '';
                }
            }
        }
    };

    return {
        build: app.methods.build,
        getQueryParams: app.methods.getQueryParams
    };

}(window, document));;
APP.namespace('APP.Utilities');

APP.Utilities.Cookie = (function ($) {
    "use strict";

    var app;

    app = {
        methods: {
            set : function (name, value, params) {
                var logData,
                    data = value;

                if (typeof data === 'undefined' || data.length === 0) {
                    data = 'undefined or empty';
                }

                logData = name;
                logData += ' : ';
                logData += data;

                APP.trace('Log: [utilities|cookie] Set cookie data... ' + logData);

                $.cookie(name, value, params);
            },
            get: function (name) {
                return $.cookie(name);
            },
            remove: function (name, params) {
                return $.removeCookie(name, params);
            }
        }
    };

    return {
        set : app.methods.set,
        get : app.methods.get,
        remove: app.methods.remove
    };

}(jQuery));;
APP.namespace('APP.Utilities');

APP.Utilities.HiddenImage = (function ($, window) {
    "use strict";

    var app,
        element,
        img;

    app = {
        events: {
            
        },
        methods: {
            imageCheck: function () {

                var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

                if (w < 768 && $('[data-src-mobile]').length) {
                    img.attr("src", element.data("src-mobile"));
                    return;
                }

                img.attr("src", element.data("src-default"));
            }
        }
    };

    return {
        attach: function () {
            element = $('[data-src-default]');
            img = $('#header-home__img');

            app.methods.imageCheck();

            $(window).resize(function () {
                app.methods.imageCheck();
            });
        }
    };

}($, window));;
/*
 *
 * APP JavaScript library
 *
 * @author      Ken van den Broek | Uselab Amsterdam
 * @copyright 	All intellectual property rights are reserved.
 * @category  	JavaScript
 *
 * -------------------------------------------------------------------------------
 * Start Application When DOM is Ready...
 * -------------------------------------------------------------------------------
 *
 * jslint passfail: true, debug: true, white: true
 * global APP window $ jQuery Image
 *
 */

$(function() {
	var options;
	options = APP.Configuration;
	
	//Bootstrap the application...
	APP.Core.Bootstrap.init(options);
});;
